page.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import mongoose, {
  3. Schema, Model, Document, AnyObject,
  4. } from 'mongoose';
  5. import mongoosePaginate from 'mongoose-paginate-v2';
  6. import uniqueValidator from 'mongoose-unique-validator';
  7. import nodePath from 'path';
  8. import { getOrCreateModel, pagePathUtils } from '@growi/core';
  9. import loggerFactory from '../../utils/logger';
  10. import Crowi from '../crowi';
  11. import { IPage } from '../../interfaces/page';
  12. import { getPageSchema, PageQueryBuilder } from './obsolete-page';
  13. const { isTopPage, collectAncestorPaths } = pagePathUtils;
  14. const logger = loggerFactory('growi:models:page');
  15. /*
  16. * define schema
  17. */
  18. const GRANT_PUBLIC = 1;
  19. const GRANT_RESTRICTED = 2;
  20. const GRANT_SPECIFIED = 3; // DEPRECATED
  21. const GRANT_OWNER = 4;
  22. const GRANT_USER_GROUP = 5;
  23. const PAGE_GRANT_ERROR = 1;
  24. const STATUS_PUBLISHED = 'published';
  25. const STATUS_DELETED = 'deleted';
  26. export interface PageDocument extends IPage, Document {}
  27. type TargetAndAncestorsResult = {
  28. targetAndAncestors: PageDocument[]
  29. rootPage: PageDocument
  30. }
  31. export interface PageModel extends Model<PageDocument> {
  32. [x: string]: any; // for obsolete methods
  33. createEmptyPagesByPaths(paths: string[], publicOnly?: boolean): Promise<void>
  34. getParentAndFillAncestors(path: string): Promise<PageDocument & { _id: any }>
  35. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument[]>
  36. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  37. findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups?): Promise<PageDocument[]>
  38. findAncestorsChildrenByPathAndViewer(path: string, user, userGroups?): Promise<Record<string, PageDocument[]>>
  39. PageQueryBuilder: typeof PageQueryBuilder
  40. GRANT_PUBLIC
  41. GRANT_RESTRICTED
  42. GRANT_SPECIFIED
  43. GRANT_OWNER
  44. GRANT_USER_GROUP
  45. PAGE_GRANT_ERROR
  46. STATUS_PUBLISHED
  47. STATUS_DELETED
  48. }
  49. type IObjectId = mongoose.Types.ObjectId;
  50. const ObjectId = mongoose.Schema.Types.ObjectId;
  51. const schema = new Schema<PageDocument, PageModel>({
  52. parent: {
  53. type: ObjectId, ref: 'Page', index: true, default: null,
  54. },
  55. descendantCount: { type: Number, default: 0 },
  56. isEmpty: { type: Boolean, default: false },
  57. path: {
  58. type: String, required: true, index: true,
  59. },
  60. revision: { type: ObjectId, ref: 'Revision' },
  61. redirectTo: { type: String, index: true },
  62. status: { type: String, default: STATUS_PUBLISHED, index: true },
  63. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  64. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  65. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  66. creator: { type: ObjectId, ref: 'User', index: true },
  67. lastUpdateUser: { type: ObjectId, ref: 'User' },
  68. liker: [{ type: ObjectId, ref: 'User' }],
  69. seenUsers: [{ type: ObjectId, ref: 'User' }],
  70. commentCount: { type: Number, default: 0 },
  71. slackChannels: { type: String },
  72. pageIdOnHackmd: { type: String },
  73. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  74. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  75. createdAt: { type: Date, default: new Date() },
  76. updatedAt: { type: Date, default: new Date() },
  77. deleteUser: { type: ObjectId, ref: 'User' },
  78. deletedAt: { type: Date },
  79. }, {
  80. toJSON: { getters: true },
  81. toObject: { getters: true },
  82. });
  83. // apply plugins
  84. schema.plugin(mongoosePaginate);
  85. schema.plugin(uniqueValidator);
  86. const hasSlash = (str: string): boolean => {
  87. return str.includes('/');
  88. };
  89. /*
  90. * Generate RegExp instance for one level lower path
  91. */
  92. const generateChildrenRegExp = (path: string): RegExp => {
  93. // https://regex101.com/r/laJGzj/1
  94. // ex. /any_level1
  95. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  96. // https://regex101.com/r/mrDJrx/1
  97. // ex. /parent/any_child OR /any_level1
  98. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  99. };
  100. /*
  101. * Create empty pages if the page in paths didn't exist
  102. */
  103. schema.statics.createEmptyPagesByPaths = async function(paths: string[], publicOnly = false): Promise<void> {
  104. // find existing parents
  105. const builder = new PageQueryBuilder(this.find(publicOnly ? { grant: GRANT_PUBLIC } : {}, { _id: 0, path: 1 }), true);
  106. const existingPages = await builder
  107. .addConditionToListByPathsArray(paths)
  108. .query
  109. .lean()
  110. .exec();
  111. const existingPagePaths = existingPages.map(page => page.path);
  112. // paths to create empty pages
  113. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  114. // insertMany empty pages
  115. try {
  116. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  117. }
  118. catch (err) {
  119. logger.error('Failed to insert empty pages.', err);
  120. throw err;
  121. }
  122. };
  123. schema.statics.createEmptyPage = async function(
  124. path: string, parent: any, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506
  125. ): Promise<PageDocument & { _id: any }> {
  126. if (parent == null) {
  127. throw Error('parent must not be null');
  128. }
  129. const Page = this;
  130. const page = new Page();
  131. page.path = path;
  132. page.isEmpty = true;
  133. page.parent = parent;
  134. return page.save();
  135. };
  136. /**
  137. * Replace an existing page with an empty page.
  138. * It updates the children's parent to the new empty page's _id.
  139. * @param exPage a page document to be replaced
  140. * @param pageToReplaceWith (optional) a page document to replace with
  141. * @returns Promise<void>
  142. */
  143. schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?): Promise<void> {
  144. // find parent
  145. const parent = await this.findOne({ _id: exPage.parent });
  146. if (parent == null) {
  147. throw Error('parent to update does not exist. Prepare parent first.');
  148. }
  149. // create empty page at path
  150. let newTarget = pageToReplaceWith;
  151. if (newTarget == null) {
  152. newTarget = await this.createEmptyPage(exPage.path, parent);
  153. }
  154. // find children by ex-page _id
  155. const children = await this.find({ parent: exPage._id });
  156. // bulkWrite
  157. const operationForNewTarget = {
  158. updateOne: {
  159. filter: { _id: newTarget._id },
  160. update: {
  161. parent: parent._id,
  162. },
  163. },
  164. };
  165. const operationsForChildren = {
  166. updateMany: {
  167. filter: {
  168. _id: { $in: children.map(d => d._id) },
  169. },
  170. update: {
  171. parent: newTarget._id,
  172. },
  173. },
  174. };
  175. await this.bulkWrite([operationForNewTarget, operationsForChildren]);
  176. };
  177. /**
  178. * Find parent or create parent if not exists.
  179. * It also updates parent of ancestors
  180. * @param path string
  181. * @returns Promise<PageDocument>
  182. */
  183. schema.statics.getParentAndFillAncestors = async function(path: string): Promise<PageDocument> {
  184. const parentPath = nodePath.dirname(path);
  185. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  186. if (parent != null) {
  187. return parent;
  188. }
  189. /*
  190. * Fill parents if parent is null
  191. */
  192. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  193. // just create ancestors with empty pages
  194. await this.createEmptyPagesByPaths(ancestorPaths);
  195. // find ancestors
  196. const builder = new PageQueryBuilder(this.find(), true);
  197. const ancestors = await builder
  198. .addConditionToListByPathsArray(ancestorPaths)
  199. .addConditionToSortPagesByDescPath()
  200. .query
  201. .exec();
  202. const ancestorsMap = new Map(); // Map<path, page>
  203. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  204. // bulkWrite to update ancestors
  205. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  206. const operations = nonRootAncestors.map((page) => {
  207. const { path } = page;
  208. const parentPath = nodePath.dirname(path);
  209. return {
  210. updateOne: {
  211. filter: {
  212. path,
  213. },
  214. update: {
  215. parent: ancestorsMap.get(parentPath),
  216. },
  217. },
  218. };
  219. });
  220. await this.bulkWrite(operations);
  221. const createdParent = ancestorsMap.get(parentPath);
  222. return createdParent;
  223. };
  224. // Utility function to add viewer condition to PageQueryBuilder instance
  225. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  226. let relatedUserGroups = userGroups;
  227. if (user != null && relatedUserGroups == null) {
  228. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  229. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  230. }
  231. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, false);
  232. };
  233. /*
  234. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  235. */
  236. schema.statics.findByPathAndViewer = async function(
  237. path: string | null, user, userGroups = null, useFindOne = true, includeEmpty = false,
  238. ): Promise<PageDocument | PageDocument[] | null> {
  239. if (path == null) {
  240. throw new Error('path is required.');
  241. }
  242. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  243. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  244. await addViewerCondition(queryBuilder, user, userGroups);
  245. return queryBuilder.query.exec();
  246. };
  247. /*
  248. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  249. * The result will include the target as well
  250. */
  251. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  252. let path;
  253. if (!hasSlash(pathOrId)) {
  254. const _id = pathOrId;
  255. const page = await this.findOne({ _id });
  256. if (page == null) throw new Error('Page not found.');
  257. path = page.path;
  258. }
  259. else {
  260. path = pathOrId;
  261. }
  262. const ancestorPaths = collectAncestorPaths(path);
  263. ancestorPaths.push(path); // include target
  264. // Do not populate
  265. const queryBuilder = new PageQueryBuilder(this.find(), true);
  266. await addViewerCondition(queryBuilder, user, userGroups);
  267. const _targetAndAncestors: PageDocument[] = await queryBuilder
  268. .addConditionAsMigrated()
  269. .addConditionToListByPathsArray(ancestorPaths)
  270. .addConditionToMinimizeDataForRendering()
  271. .addConditionToSortPagesByDescPath()
  272. .query
  273. .lean()
  274. .exec();
  275. // no same path pages
  276. const ancestorsMap = new Map<string, PageDocument>();
  277. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  278. const targetAndAncestors = Array.from(ancestorsMap.values());
  279. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  280. return { targetAndAncestors, rootPage };
  281. };
  282. /*
  283. * Find all children by parent's path or id. Using id should be prioritized
  284. */
  285. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  286. let queryBuilder: PageQueryBuilder;
  287. if (hasSlash(parentPathOrId)) {
  288. const path = parentPathOrId;
  289. const regexp = generateChildrenRegExp(path);
  290. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp } }), true);
  291. }
  292. else {
  293. const parentId = parentPathOrId;
  294. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId }), true);
  295. }
  296. await addViewerCondition(queryBuilder, user, userGroups);
  297. return queryBuilder
  298. .addConditionToSortPagesByAscPath()
  299. .query
  300. .lean()
  301. .exec();
  302. };
  303. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  304. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  305. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  306. // get pages at once
  307. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }), true);
  308. await addViewerCondition(queryBuilder, user, userGroups);
  309. const _pages = await queryBuilder
  310. .addConditionAsMigrated()
  311. .addConditionToMinimizeDataForRendering()
  312. .addConditionToSortPagesByAscPath()
  313. .query
  314. .lean()
  315. .exec();
  316. // mark target
  317. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  318. if (page.path === path) {
  319. page.isTarget = true;
  320. }
  321. return page;
  322. });
  323. /*
  324. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  325. */
  326. const pathToChildren: Record<string, PageDocument[]> = {};
  327. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  328. sortedPaths.every((path) => {
  329. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  330. if (children.length === 0) {
  331. return false; // break when children do not exist
  332. }
  333. pathToChildren[path] = children;
  334. return true;
  335. });
  336. return pathToChildren;
  337. };
  338. /*
  339. * Utils from obsolete-page.js
  340. */
  341. async function pushRevision(pageData, newRevision, user) {
  342. await newRevision.save();
  343. pageData.revision = newRevision;
  344. pageData.lastUpdateUser = user;
  345. pageData.updatedAt = Date.now();
  346. return pageData.save();
  347. }
  348. /**
  349. * return aggregate condition to get following pages
  350. * - page that has the same path as the provided path
  351. * - pages that are descendants of the above page
  352. * pages without parent will be ignored
  353. */
  354. schema.statics.getAggrConditionForPageWithProvidedPathAndDescendants = function(path:string) {
  355. let match;
  356. if (isTopPage(path)) {
  357. match = {
  358. // https://regex101.com/r/Kip2rV/1
  359. $match: { $or: [{ path: { $regex: '^/.*' }, parent: { $ne: null } }, { path: '/' }] },
  360. };
  361. }
  362. else {
  363. match = {
  364. // https://regex101.com/r/mJvGrG/1
  365. $match: { path: { $regex: `^${path}(/.*|$)` }, parent: { $ne: null } },
  366. };
  367. }
  368. return [
  369. match,
  370. {
  371. $project: {
  372. path: 1,
  373. parent: 1,
  374. field_length: { $strLenCP: '$path' },
  375. },
  376. },
  377. { $sort: { field_length: -1 } },
  378. { $project: { field_length: 0 } },
  379. ];
  380. };
  381. /**
  382. * add/subtract descendantCount of pages with provided paths by increment.
  383. * increment can be negative number
  384. */
  385. schema.statics.incrementDescendantCountOfPaths = async function(paths:string[], increment: number):Promise<void> {
  386. const pages = await this.aggregate([{ $match: { path: { $in: paths } } }]);
  387. const operations = pages.map((page) => {
  388. return {
  389. updateOne: {
  390. filter: { path: page.path },
  391. update: { descendantCount: page.descendantCount + increment },
  392. },
  393. };
  394. });
  395. await this.bulkWrite(operations);
  396. };
  397. // update descendantCount of a page with provided id
  398. schema.statics.recountDescendantCountOfSelfAndDescendants = async function(id:mongoose.Types.ObjectId):Promise<void> {
  399. const res = await this.aggregate(
  400. [
  401. {
  402. $match: {
  403. parent: id,
  404. },
  405. },
  406. {
  407. $project: {
  408. path: 1,
  409. parent: 1,
  410. descendantCount: 1,
  411. },
  412. },
  413. {
  414. $group: {
  415. _id: '$parent',
  416. sumOfDescendantCount: {
  417. $sum: '$descendantCount',
  418. },
  419. sumOfDocsCount: {
  420. $sum: 1,
  421. },
  422. },
  423. },
  424. {
  425. $set: {
  426. descendantCount: {
  427. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  428. },
  429. },
  430. },
  431. ],
  432. );
  433. const query = { descendantCount: res.length === 0 ? 0 : res[0].descendantCount };
  434. await this.findByIdAndUpdate(id, query);
  435. };
  436. /*
  437. * Merge obsolete page model methods and define new methods which depend on crowi instance
  438. */
  439. export default (crowi: Crowi): any => {
  440. let pageEvent;
  441. if (crowi != null) {
  442. pageEvent = crowi.event('page');
  443. }
  444. schema.statics.create = async function(path, body, user, options = {}) {
  445. if (crowi.pageGrantService == null || crowi.configManager == null) {
  446. throw Error('Crowi is not setup');
  447. }
  448. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  449. // v4 compatible process
  450. if (!isV5Compatible) {
  451. return this.createV4(path, body, user, options);
  452. }
  453. const Page = this;
  454. const Revision = crowi.model('Revision');
  455. const {
  456. format = 'markdown', redirectTo, grantUserGroupId,
  457. } = options;
  458. let grant = options.grant;
  459. // sanitize path
  460. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  461. // throw if exists
  462. const isExist = (await this.count({ path, isEmpty: false })) > 0; // not validate empty page
  463. if (isExist) {
  464. throw new Error('Cannot create new page to existed path');
  465. }
  466. // force public
  467. if (isTopPage(path)) {
  468. grant = GRANT_PUBLIC;
  469. }
  470. // find an existing empty page
  471. const emptyPage = await Page.findOne({ path, isEmpty: true });
  472. /*
  473. * UserGroup & Owner validation
  474. */
  475. if (grant !== GRANT_RESTRICTED) {
  476. let isGrantNormalized = false;
  477. try {
  478. // It must check descendants as well if emptyTarget is not null
  479. const shouldCheckDescendants = emptyPage != null;
  480. const newGrantedUserIds = grant === GRANT_OWNER ? [user._id] as IObjectId[] : undefined;
  481. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  482. }
  483. catch (err) {
  484. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  485. throw err;
  486. }
  487. if (!isGrantNormalized) {
  488. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  489. }
  490. }
  491. /*
  492. * update empty page if exists, if not, create a new page
  493. */
  494. let page;
  495. if (emptyPage != null) {
  496. page = emptyPage;
  497. page.isEmpty = false;
  498. }
  499. else {
  500. page = new Page();
  501. }
  502. let parentId: IObjectId | string | null = null;
  503. const parent = await Page.getParentAndFillAncestors(path);
  504. if (!isTopPage(path)) {
  505. parentId = parent._id;
  506. }
  507. page.path = path;
  508. page.creator = user;
  509. page.lastUpdateUser = user;
  510. page.redirectTo = redirectTo;
  511. page.status = STATUS_PUBLISHED;
  512. // set parent to null when GRANT_RESTRICTED
  513. if (grant === GRANT_RESTRICTED) {
  514. page.parent = null;
  515. }
  516. else {
  517. page.parent = parentId;
  518. }
  519. page.applyScope(user, grant, grantUserGroupId);
  520. let savedPage = await page.save();
  521. /*
  522. * After save
  523. */
  524. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  525. const revision = await pushRevision(savedPage, newRevision, user);
  526. savedPage = await this.findByPath(revision.path);
  527. await savedPage.populateDataToShowRevision();
  528. pageEvent.emit('create', savedPage, user);
  529. return savedPage;
  530. };
  531. schema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  532. if (crowi.configManager == null || crowi.pageGrantService == null) {
  533. throw Error('Crowi is not set up');
  534. }
  535. const isPageMigrated = pageData.parent != null;
  536. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  537. if (!isV5Compatible || !isPageMigrated) {
  538. // v4 compatible process
  539. return this.updatePageV4(pageData, body, previousBody, user, options);
  540. }
  541. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  542. const grant = options.grant || pageData.grant; // use the previous data if absence
  543. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  544. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  545. const grantedUserIds = pageData.grantedUserIds || [user._id];
  546. const newPageData = pageData;
  547. if (grant === GRANT_RESTRICTED) {
  548. newPageData.parent = null;
  549. }
  550. else {
  551. /*
  552. * UserGroup & Owner validation
  553. */
  554. let isGrantNormalized = false;
  555. try {
  556. const shouldCheckDescendants = true;
  557. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(pageData.path, grant, grantedUserIds, grantUserGroupId, shouldCheckDescendants);
  558. }
  559. catch (err) {
  560. logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err);
  561. throw err;
  562. }
  563. if (!isGrantNormalized) {
  564. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  565. }
  566. }
  567. newPageData.applyScope(user, grant, grantUserGroupId);
  568. // update existing page
  569. let savedPage = await newPageData.save();
  570. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user);
  571. const revision = await pushRevision(savedPage, newRevision, user);
  572. savedPage = await this.findByPath(revision.path);
  573. await savedPage.populateDataToShowRevision();
  574. if (isSyncRevisionToHackmd) {
  575. savedPage = await this.syncRevisionToHackmd(savedPage);
  576. }
  577. pageEvent.emit('update', savedPage, user);
  578. return savedPage;
  579. };
  580. // add old page schema methods
  581. const pageSchema = getPageSchema(crowi);
  582. schema.methods = { ...pageSchema.methods, ...schema.methods };
  583. schema.statics = { ...pageSchema.statics, ...schema.statics };
  584. return getOrCreateModel<PageDocument, PageModel>('Page', schema);
  585. };
  586. /*
  587. * Aggregation utilities
  588. */
  589. // TODO: use the original type when upgraded https://github.com/Automattic/mongoose/blob/master/index.d.ts#L3090
  590. type PipelineStageMatch = {
  591. $match: AnyObject
  592. };
  593. export const generateGrantCondition = async(
  594. user, _userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  595. ): Promise<PipelineStageMatch> => {
  596. let userGroups = _userGroups;
  597. if (user != null && userGroups == null) {
  598. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  599. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  600. }
  601. const grantConditions: AnyObject[] = [
  602. { grant: null },
  603. { grant: GRANT_PUBLIC },
  604. ];
  605. if (showAnyoneKnowsLink) {
  606. grantConditions.push({ grant: GRANT_RESTRICTED });
  607. }
  608. if (showPagesRestrictedByOwner) {
  609. grantConditions.push(
  610. { grant: GRANT_SPECIFIED },
  611. { grant: GRANT_OWNER },
  612. );
  613. }
  614. else if (user != null) {
  615. grantConditions.push(
  616. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  617. { grant: GRANT_OWNER, grantedUsers: user._id },
  618. );
  619. }
  620. if (showPagesRestrictedByGroup) {
  621. grantConditions.push(
  622. { grant: GRANT_USER_GROUP },
  623. );
  624. }
  625. else if (userGroups != null && userGroups.length > 0) {
  626. grantConditions.push(
  627. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  628. );
  629. }
  630. return {
  631. $match: {
  632. $or: grantConditions,
  633. },
  634. };
  635. };