page.ts 22 KB

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