page.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import nodePath from 'path';
  3. import { HasObjectId, pagePathUtils, pathUtils } from '@growi/core';
  4. import { collectAncestorPaths } from '@growi/core/dist/utils/page-path-utils/collect-ancestor-paths';
  5. import escapeStringRegexp from 'escape-string-regexp';
  6. import mongoose, {
  7. Schema, Model, Document, AnyObject,
  8. } from 'mongoose';
  9. import mongoosePaginate from 'mongoose-paginate-v2';
  10. import uniqueValidator from 'mongoose-unique-validator';
  11. import { IPage, IPageHasId, PageGrant } from '~/interfaces/page';
  12. import { IUserHasId } from '~/interfaces/user';
  13. import { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  14. import loggerFactory from '../../utils/logger';
  15. import { getOrCreateModel } from '../util/mongoose-utils';
  16. import { getPageSchema, extractToAncestorsPaths, populateDataToShowRevision } from './obsolete-page';
  17. const { addTrailingSlash, normalizePath } = pathUtils;
  18. const {
  19. isTopPage, hasSlash,
  20. } = pagePathUtils;
  21. const logger = loggerFactory('growi:models:page');
  22. /*
  23. * define schema
  24. */
  25. const GRANT_PUBLIC = 1;
  26. const GRANT_RESTRICTED = 2;
  27. const GRANT_SPECIFIED = 3; // DEPRECATED
  28. const GRANT_OWNER = 4;
  29. const GRANT_USER_GROUP = 5;
  30. const PAGE_GRANT_ERROR = 1;
  31. const STATUS_PUBLISHED = 'published';
  32. const STATUS_DELETED = 'deleted';
  33. export interface PageDocument extends IPage, Document {
  34. [x:string]: any // for obsolete methods
  35. }
  36. type TargetAndAncestorsResult = {
  37. targetAndAncestors: PageDocument[]
  38. rootPage: PageDocument
  39. }
  40. type PaginatedPages = {
  41. pages: PageDocument[],
  42. totalCount: number,
  43. limit: number,
  44. offset: number
  45. }
  46. export type CreateMethod = (path: string, body: string, user, options: PageCreateOptions) => Promise<PageDocument & { _id: any }>
  47. export interface PageModel extends Model<PageDocument> {
  48. [x: string]: any; // for obsolete static methods
  49. findByIdsAndViewer(pageIds: ObjectIdLike[], user, userGroups?, includeEmpty?: boolean, includeAnyoneWithTheLink?: boolean): Promise<PageDocument[]>
  50. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: true, includeEmpty?: boolean): Promise<PageDocument & HasObjectId | null>
  51. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: false, includeEmpty?: boolean): Promise<(PageDocument & HasObjectId)[]>
  52. countByPathAndViewer(path: string | null, user, userGroups?, includeEmpty?:boolean): Promise<number>
  53. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  54. findRecentUpdatedPages(path: string, user, option, includeEmpty?: boolean): Promise<PaginatedPages>
  55. generateGrantCondition(
  56. user, userGroups, includeAnyoneWithTheLink?: boolean, showPagesRestrictedByOwner?: boolean, showPagesRestrictedByGroup?: boolean,
  57. ): { $or: any[] }
  58. PageQueryBuilder: typeof PageQueryBuilder
  59. GRANT_PUBLIC
  60. GRANT_RESTRICTED
  61. GRANT_SPECIFIED
  62. GRANT_OWNER
  63. GRANT_USER_GROUP
  64. PAGE_GRANT_ERROR
  65. STATUS_PUBLISHED
  66. STATUS_DELETED
  67. }
  68. type IObjectId = mongoose.Types.ObjectId;
  69. const ObjectId = mongoose.Schema.Types.ObjectId;
  70. const schema = new Schema<PageDocument, PageModel>({
  71. parent: {
  72. type: ObjectId, ref: 'Page', index: true, default: null,
  73. },
  74. descendantCount: { type: Number, default: 0 },
  75. isEmpty: { type: Boolean, default: false },
  76. path: {
  77. type: String, required: true, index: true,
  78. },
  79. revision: { type: ObjectId, ref: 'Revision' },
  80. status: { type: String, default: STATUS_PUBLISHED, index: true },
  81. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  82. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  83. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  84. creator: { type: ObjectId, ref: 'User', index: true },
  85. lastUpdateUser: { type: ObjectId, ref: 'User' },
  86. liker: [{ type: ObjectId, ref: 'User' }],
  87. seenUsers: [{ type: ObjectId, ref: 'User' }],
  88. commentCount: { type: Number, default: 0 },
  89. pageIdOnHackmd: { type: String },
  90. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  91. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  92. expandContentWidth: { type: Boolean },
  93. updatedAt: { type: Date, default: Date.now }, // Do not use timetamps for updatedAt because it breaks 'updateMetadata: false' option
  94. deleteUser: { type: ObjectId, ref: 'User' },
  95. deletedAt: { type: Date },
  96. }, {
  97. timestamps: { createdAt: true, updatedAt: false },
  98. toJSON: { getters: true },
  99. toObject: { getters: true },
  100. });
  101. // apply plugins
  102. schema.plugin(mongoosePaginate);
  103. schema.plugin(uniqueValidator);
  104. export class PageQueryBuilder {
  105. query: any;
  106. constructor(query, includeEmpty = false) {
  107. this.query = query;
  108. if (!includeEmpty) {
  109. this.query = this.query
  110. .and({
  111. $or: [
  112. { isEmpty: false },
  113. { isEmpty: null }, // for v4 compatibility
  114. ],
  115. });
  116. }
  117. }
  118. /**
  119. * Used for filtering the pages at specified paths not to include unintentional pages.
  120. * @param pathsToFilter The paths to have additional filters as to be applicable
  121. * @returns PageQueryBuilder
  122. */
  123. addConditionToFilterByApplicableAncestors(pathsToFilter: string[]): PageQueryBuilder {
  124. this.query = this.query
  125. .and(
  126. {
  127. $or: [
  128. { path: '/' },
  129. { path: { $in: pathsToFilter }, grant: GRANT_PUBLIC, status: STATUS_PUBLISHED },
  130. { path: { $in: pathsToFilter }, parent: { $ne: null }, status: STATUS_PUBLISHED },
  131. { path: { $nin: pathsToFilter }, status: STATUS_PUBLISHED },
  132. ],
  133. },
  134. );
  135. return this;
  136. }
  137. addConditionToExcludeTrashed(): PageQueryBuilder {
  138. this.query = this.query
  139. .and({
  140. $or: [
  141. { status: null },
  142. { status: STATUS_PUBLISHED },
  143. ],
  144. });
  145. return this;
  146. }
  147. /**
  148. * generate the query to find the pages '{path}/*' and '{path}' self.
  149. * If top page, return without doing anything.
  150. */
  151. addConditionToListWithDescendants(path: string, option?): PageQueryBuilder {
  152. // No request is set for the top page
  153. if (isTopPage(path)) {
  154. return this;
  155. }
  156. const pathNormalized = pathUtils.normalizePath(path);
  157. const pathWithTrailingSlash = addTrailingSlash(path);
  158. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  159. this.query = this.query
  160. .and({
  161. $or: [
  162. { path: pathNormalized },
  163. { path: new RegExp(`^${startsPattern}`) },
  164. ],
  165. });
  166. return this;
  167. }
  168. /**
  169. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  170. */
  171. addConditionToListOnlyDescendants(path: string, option): PageQueryBuilder {
  172. // exclude the target page
  173. this.query = this.query.and({ path: { $ne: path } });
  174. if (isTopPage(path)) {
  175. return this;
  176. }
  177. const pathWithTrailingSlash = addTrailingSlash(path);
  178. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  179. this.query = this.query
  180. .and(
  181. { path: new RegExp(`^${startsPattern}`) },
  182. );
  183. return this;
  184. }
  185. addConditionToListOnlyAncestors(path: string): PageQueryBuilder {
  186. const pathNormalized = pathUtils.normalizePath(path);
  187. const ancestorsPaths = extractToAncestorsPaths(pathNormalized);
  188. this.query = this.query
  189. // exclude the target page
  190. .and({ path: { $ne: path } })
  191. .and(
  192. { path: { $in: ancestorsPaths } },
  193. );
  194. return this;
  195. }
  196. /**
  197. * generate the query to find pages that start with `path`
  198. *
  199. * In normal case, returns '{path}/*' and '{path}' self.
  200. * If top page, return without doing anything.
  201. *
  202. * *option*
  203. * Left for backward compatibility
  204. */
  205. addConditionToListByStartWith(str: string): PageQueryBuilder {
  206. const path = normalizePath(str);
  207. // No request is set for the top page
  208. if (isTopPage(path)) {
  209. return this;
  210. }
  211. const startsPattern = escapeStringRegexp(path);
  212. this.query = this.query
  213. .and({ path: new RegExp(`^${startsPattern}`) });
  214. return this;
  215. }
  216. addConditionToListByNotStartWith(str: string): PageQueryBuilder {
  217. const path = normalizePath(str);
  218. // No request is set for the top page
  219. if (isTopPage(path)) {
  220. return this;
  221. }
  222. const startsPattern = escapeStringRegexp(str);
  223. this.query = this.query
  224. .and({ path: new RegExp(`^(?!${startsPattern}).*$`) });
  225. return this;
  226. }
  227. addConditionToListByMatch(str: string): PageQueryBuilder {
  228. // No request is set for "/"
  229. if (str === '/') {
  230. return this;
  231. }
  232. const match = escapeStringRegexp(str);
  233. this.query = this.query
  234. .and({ path: new RegExp(`^(?=.*${match}).*$`) });
  235. return this;
  236. }
  237. addConditionToListByNotMatch(str: string): PageQueryBuilder {
  238. // No request is set for "/"
  239. if (str === '/') {
  240. return this;
  241. }
  242. const match = escapeStringRegexp(str);
  243. this.query = this.query
  244. .and({ path: new RegExp(`^(?!.*${match}).*$`) });
  245. return this;
  246. }
  247. async addConditionForParentNormalization(user): Promise<PageQueryBuilder> {
  248. // determine UserGroup condition
  249. let userGroups;
  250. if (user != null) {
  251. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model
  252. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  253. }
  254. const grantConditions: any[] = [
  255. { grant: null },
  256. { grant: GRANT_PUBLIC },
  257. ];
  258. if (user != null) {
  259. grantConditions.push(
  260. { grant: GRANT_OWNER, grantedUsers: user._id },
  261. );
  262. }
  263. if (userGroups != null && userGroups.length > 0) {
  264. grantConditions.push(
  265. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  266. );
  267. }
  268. this.query = this.query
  269. .and({
  270. $or: grantConditions,
  271. });
  272. return this;
  273. }
  274. async addConditionAsMigratablePages(user): Promise<PageQueryBuilder> {
  275. this.query = this.query
  276. .and({
  277. $or: [
  278. { grant: { $ne: GRANT_RESTRICTED } },
  279. { grant: { $ne: GRANT_SPECIFIED } },
  280. ],
  281. });
  282. this.addConditionAsRootOrNotOnTree();
  283. this.addConditionAsNonRootPage();
  284. this.addConditionToExcludeTrashed();
  285. await this.addConditionForParentNormalization(user);
  286. return this;
  287. }
  288. // add viewer condition to PageQueryBuilder instance
  289. async addViewerCondition(user, userGroups = null, includeAnyoneWithTheLink = false): Promise<PageQueryBuilder> {
  290. let relatedUserGroups = userGroups;
  291. if (user != null && relatedUserGroups == null) {
  292. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  293. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  294. }
  295. this.addConditionToFilteringByViewer(user, relatedUserGroups, includeAnyoneWithTheLink);
  296. return this;
  297. }
  298. addConditionToFilteringByViewer(
  299. user, userGroups, includeAnyoneWithTheLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  300. ): PageQueryBuilder {
  301. const condition = generateGrantCondition(user, userGroups, includeAnyoneWithTheLink, showPagesRestrictedByOwner, showPagesRestrictedByGroup);
  302. this.query = this.query
  303. .and(condition);
  304. return this;
  305. }
  306. addConditionToPagenate(offset, limit, sortOpt?): PageQueryBuilder {
  307. this.query = this.query
  308. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  309. return this;
  310. }
  311. addConditionAsNonRootPage(): PageQueryBuilder {
  312. this.query = this.query.and({ path: { $ne: '/' } });
  313. return this;
  314. }
  315. addConditionAsRootOrNotOnTree(): PageQueryBuilder {
  316. this.query = this.query
  317. .and({ parent: null });
  318. return this;
  319. }
  320. addConditionAsOnTree(): PageQueryBuilder {
  321. this.query = this.query
  322. .and(
  323. {
  324. $or: [
  325. { parent: { $ne: null } },
  326. { path: '/' },
  327. ],
  328. },
  329. );
  330. return this;
  331. }
  332. /*
  333. * Add this condition when get any ancestor pages including the target's parent
  334. */
  335. addConditionToSortPagesByDescPath(): PageQueryBuilder {
  336. this.query = this.query.sort('-path');
  337. return this;
  338. }
  339. addConditionToSortPagesByAscPath(): PageQueryBuilder {
  340. this.query = this.query.sort('path');
  341. return this;
  342. }
  343. addConditionToMinimizeDataForRendering(): PageQueryBuilder {
  344. this.query = this.query.select('_id path isEmpty grant revision descendantCount');
  345. return this;
  346. }
  347. addConditionToListByPathsArray(paths): PageQueryBuilder {
  348. this.query = this.query
  349. .and({
  350. path: {
  351. $in: paths,
  352. },
  353. });
  354. return this;
  355. }
  356. addConditionToListByPageIdsArray(pageIds): PageQueryBuilder {
  357. this.query = this.query
  358. .and({
  359. _id: {
  360. $in: pageIds,
  361. },
  362. });
  363. return this;
  364. }
  365. addConditionToExcludeByPageIdsArray(pageIds): PageQueryBuilder {
  366. this.query = this.query
  367. .and({
  368. _id: {
  369. $nin: pageIds,
  370. },
  371. });
  372. return this;
  373. }
  374. populateDataToList(userPublicFields): PageQueryBuilder {
  375. this.query = this.query
  376. .populate({
  377. path: 'lastUpdateUser',
  378. select: userPublicFields,
  379. });
  380. return this;
  381. }
  382. populateDataToShowRevision(userPublicFields): PageQueryBuilder {
  383. this.query = populateDataToShowRevision(this.query, userPublicFields);
  384. return this;
  385. }
  386. addConditionToFilteringByParentId(parentId): PageQueryBuilder {
  387. this.query = this.query.and({ parent: parentId });
  388. return this;
  389. }
  390. }
  391. schema.statics.createEmptyPage = async function(
  392. path: string, parent: any, descendantCount = 0, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506
  393. ): Promise<PageDocument & { _id: any }> {
  394. if (parent == null) {
  395. throw Error('parent must not be null');
  396. }
  397. const Page = this;
  398. const page = new Page();
  399. page.path = path;
  400. page.isEmpty = true;
  401. page.parent = parent;
  402. page.descendantCount = descendantCount;
  403. return page.save();
  404. };
  405. /**
  406. * Replace an existing page with an empty page.
  407. * It updates the children's parent to the new empty page's _id.
  408. * @param exPage a page document to be replaced
  409. * @returns Promise<void>
  410. */
  411. schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?, deleteExPageIfEmpty = false) {
  412. // find parent
  413. const parent = await this.findOne({ _id: exPage.parent });
  414. if (parent == null) {
  415. throw Error('parent to update does not exist. Prepare parent first.');
  416. }
  417. // create empty page at path
  418. const newTarget = pageToReplaceWith == null ? await this.createEmptyPage(exPage.path, parent, exPage.descendantCount) : pageToReplaceWith;
  419. // find children by ex-page _id
  420. const children = await this.find({ parent: exPage._id });
  421. // bulkWrite
  422. const operationForNewTarget = {
  423. updateOne: {
  424. filter: { _id: newTarget._id },
  425. update: {
  426. parent: parent._id,
  427. },
  428. },
  429. };
  430. const operationsForChildren = {
  431. updateMany: {
  432. filter: {
  433. _id: { $in: children.map(d => d._id) },
  434. },
  435. update: {
  436. parent: newTarget._id,
  437. },
  438. },
  439. };
  440. await this.bulkWrite([operationForNewTarget, operationsForChildren]);
  441. const isExPageEmpty = exPage.isEmpty;
  442. if (deleteExPageIfEmpty && isExPageEmpty) {
  443. await this.deleteOne({ _id: exPage._id });
  444. logger.warn('Deleted empty page since it was replaced with another page.');
  445. }
  446. return this.findById(newTarget._id);
  447. };
  448. /*
  449. * Find pages by ID and viewer.
  450. */
  451. schema.statics.findByIdsAndViewer = async function(
  452. pageIds: string[], user, userGroups?, includeEmpty?: boolean, includeAnyoneWithTheLink?: boolean,
  453. ): Promise<PageDocument[]> {
  454. const baseQuery = this.find({ _id: { $in: pageIds } });
  455. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  456. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  457. return queryBuilder.query.exec();
  458. };
  459. /*
  460. * Find a page by path and viewer. Pass true to useFindOne to use findOne method.
  461. */
  462. schema.statics.findByPathAndViewer = async function(
  463. path: string | null, user, userGroups = null, useFindOne = false, includeEmpty = false,
  464. ): Promise<(PageDocument | PageDocument[]) & HasObjectId | null> {
  465. if (path == null) {
  466. throw new Error('path is required.');
  467. }
  468. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  469. const includeAnyoneWithTheLink = useFindOne;
  470. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  471. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  472. return queryBuilder.query.exec();
  473. };
  474. schema.statics.countByPathAndViewer = async function(path: string | null, user, userGroups = null, includeEmpty = false): Promise<number> {
  475. if (path == null) {
  476. throw new Error('path is required.');
  477. }
  478. const baseQuery = this.count({ path });
  479. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  480. await queryBuilder.addViewerCondition(user, userGroups);
  481. return queryBuilder.query.exec();
  482. };
  483. schema.statics.findRecentUpdatedPages = async function(
  484. path: string, user, options, includeEmpty = false,
  485. ): Promise<PaginatedPages> {
  486. const sortOpt = {};
  487. sortOpt[options.sort] = options.desc;
  488. const Page = this;
  489. const User = mongoose.model('User') as any;
  490. if (path == null) {
  491. throw new Error('path is required.');
  492. }
  493. const baseQuery = this.find({});
  494. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  495. if (!options.includeTrashed) {
  496. queryBuilder.addConditionToExcludeTrashed();
  497. }
  498. queryBuilder.addConditionToListWithDescendants(path, options);
  499. queryBuilder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  500. await queryBuilder.addViewerCondition(user);
  501. const pages = await Page.paginate(queryBuilder.query.clone(), {
  502. lean: true, sort: sortOpt, offset: options.offset, limit: options.limit,
  503. });
  504. const results = {
  505. pages: pages.docs, totalCount: pages.totalDocs, offset: options.offset, limit: options.limit,
  506. };
  507. return results;
  508. };
  509. /*
  510. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  511. * The result will include the target as well
  512. */
  513. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  514. let path;
  515. if (!hasSlash(pathOrId)) {
  516. const _id = pathOrId;
  517. const page = await this.findOne({ _id });
  518. path = page == null ? '/' : page.path;
  519. }
  520. else {
  521. path = pathOrId;
  522. }
  523. const ancestorPaths = collectAncestorPaths(path);
  524. ancestorPaths.push(path); // include target
  525. // Do not populate
  526. const queryBuilder = new PageQueryBuilder(this.find(), true);
  527. await queryBuilder.addViewerCondition(user, userGroups);
  528. const _targetAndAncestors: PageDocument[] = await queryBuilder
  529. .addConditionAsOnTree()
  530. .addConditionToListByPathsArray(ancestorPaths)
  531. .addConditionToMinimizeDataForRendering()
  532. .addConditionToSortPagesByDescPath()
  533. .query
  534. .lean()
  535. .exec();
  536. // no same path pages
  537. const ancestorsMap = new Map<string, PageDocument>();
  538. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  539. const targetAndAncestors = Array.from(ancestorsMap.values());
  540. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  541. return { targetAndAncestors, rootPage };
  542. };
  543. /**
  544. * Create empty pages at paths at which no pages exist
  545. * @param paths Page paths
  546. * @param aggrPipelineForExistingPages AggregationPipeline object to find existing pages at paths
  547. */
  548. schema.statics.createEmptyPagesByPaths = async function(paths: string[], aggrPipelineForExistingPages: any[]): Promise<void> {
  549. const existingPages = await this.aggregate(aggrPipelineForExistingPages);
  550. const existingPagePaths = existingPages.map(page => page.path);
  551. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  552. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  553. };
  554. /**
  555. * Find a parent page by path
  556. * @param {string} path
  557. * @returns {Promise<PageDocument | null>}
  558. */
  559. schema.statics.findParentByPath = async function(path: string): Promise<PageDocument | null> {
  560. const parentPath = nodePath.dirname(path);
  561. const builder = new PageQueryBuilder(this.find({ path: parentPath }), true);
  562. const pagesCanBeParent = await builder
  563. .addConditionAsOnTree()
  564. .query
  565. .exec();
  566. if (pagesCanBeParent.length >= 1) {
  567. return pagesCanBeParent[0]; // the earliest page will be the result
  568. }
  569. return null;
  570. };
  571. /*
  572. * Utils from obsolete-page.js
  573. */
  574. export async function pushRevision(pageData, newRevision, user) {
  575. await newRevision.save();
  576. pageData.revision = newRevision;
  577. pageData.lastUpdateUser = user?._id ?? user;
  578. pageData.updatedAt = Date.now();
  579. return pageData.save();
  580. }
  581. /**
  582. * add/subtract descendantCount of pages with provided paths by increment.
  583. * increment can be negative number
  584. */
  585. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  586. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  587. };
  588. /**
  589. * recount descendantCount of a page with the provided id and return it
  590. */
  591. schema.statics.recountDescendantCount = async function(id: ObjectIdLike): Promise<number> {
  592. const res = await this.aggregate(
  593. [
  594. {
  595. $match: {
  596. parent: id,
  597. },
  598. },
  599. {
  600. $project: {
  601. parent: 1,
  602. isEmpty: 1,
  603. descendantCount: 1,
  604. },
  605. },
  606. {
  607. $group: {
  608. _id: '$parent',
  609. sumOfDescendantCount: {
  610. $sum: '$descendantCount',
  611. },
  612. sumOfDocsCount: {
  613. $sum: {
  614. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  615. },
  616. },
  617. },
  618. },
  619. {
  620. $set: {
  621. descendantCount: {
  622. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  623. },
  624. },
  625. },
  626. ],
  627. );
  628. return res.length === 0 ? 0 : res[0].descendantCount;
  629. };
  630. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  631. const self = this;
  632. const target = await this.findById(pageId);
  633. if (target == null) {
  634. throw Error('Target not found');
  635. }
  636. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  637. const parent = await self.findOne({ _id: target.parent });
  638. if (parent == null) {
  639. return ancestors;
  640. }
  641. return findAncestorsRecursively(parent, [...ancestors, parent]);
  642. }
  643. return findAncestorsRecursively(target);
  644. };
  645. // TODO: write test code
  646. /**
  647. * Recursively removes empty pages at leaf position.
  648. * @param pageId ObjectIdLike
  649. * @returns Promise<void>
  650. */
  651. schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> {
  652. const self = this;
  653. const initialPage = await this.findById(pageId);
  654. if (initialPage == null) {
  655. return;
  656. }
  657. if (!initialPage.isEmpty) {
  658. return;
  659. }
  660. async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> {
  661. if (!page.isEmpty) {
  662. return pageIds;
  663. }
  664. const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id });
  665. if (isChildrenOtherThanTargetExist) {
  666. return pageIds;
  667. }
  668. pageIds.push(page._id);
  669. const nextPage = await self.findById(page.parent);
  670. if (nextPage == null) {
  671. return pageIds;
  672. }
  673. return generatePageIdsToRemove(page, nextPage, pageIds);
  674. }
  675. const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage);
  676. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  677. };
  678. schema.statics.normalizeDescendantCountById = async function(pageId) {
  679. const children = await this.find({ parent: pageId });
  680. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  681. const sumChildPages = children.filter(p => !p.isEmpty).length;
  682. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  683. };
  684. schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) {
  685. return this.findByIdAndUpdate(pageId, { $set: { parent: null } });
  686. };
  687. schema.statics.removeEmptyPages = async function(pageIdsToNotRemove: ObjectIdLike[], paths: string[]): Promise<void> {
  688. await this.deleteMany({
  689. _id: {
  690. $nin: pageIdsToNotRemove,
  691. },
  692. path: {
  693. $in: paths,
  694. },
  695. isEmpty: true,
  696. });
  697. };
  698. /**
  699. * Find a not empty parent recursively.
  700. * @param {string} path
  701. * @returns {Promise<PageDocument | null>}
  702. */
  703. schema.statics.findNotEmptyParentByPathRecursively = async function(path: string): Promise<PageDocument | null> {
  704. const parent = await this.findParentByPath(path);
  705. if (parent == null) {
  706. return null;
  707. }
  708. const recursive = async(page: PageDocument): Promise<PageDocument> => {
  709. if (!page.isEmpty) {
  710. return page;
  711. }
  712. const next = await this.findById(page.parent);
  713. if (next == null || isTopPage(next.path)) {
  714. return page;
  715. }
  716. return recursive(next);
  717. };
  718. const notEmptyParent = await recursive(parent);
  719. return notEmptyParent;
  720. };
  721. schema.statics.findParent = async function(pageId): Promise<PageDocument | null> {
  722. return this.findOne({ _id: pageId });
  723. };
  724. schema.statics.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type
  725. export function generateGrantCondition(
  726. user, userGroups, includeAnyoneWithTheLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  727. ): { $or: any[] } {
  728. const grantConditions: AnyObject[] = [
  729. { grant: null },
  730. { grant: GRANT_PUBLIC },
  731. ];
  732. if (includeAnyoneWithTheLink) {
  733. grantConditions.push({ grant: GRANT_RESTRICTED });
  734. }
  735. if (showPagesRestrictedByOwner) {
  736. grantConditions.push(
  737. { grant: GRANT_SPECIFIED },
  738. { grant: GRANT_OWNER },
  739. );
  740. }
  741. else if (user != null) {
  742. grantConditions.push(
  743. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  744. { grant: GRANT_OWNER, grantedUsers: user._id },
  745. );
  746. }
  747. if (showPagesRestrictedByGroup) {
  748. grantConditions.push(
  749. { grant: GRANT_USER_GROUP },
  750. );
  751. }
  752. else if (userGroups != null && userGroups.length > 0) {
  753. grantConditions.push(
  754. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  755. );
  756. }
  757. return {
  758. $or: grantConditions,
  759. };
  760. }
  761. schema.statics.generateGrantCondition = generateGrantCondition;
  762. // find ancestor page with isEmpty: false. If parameter path is '/', return undefined
  763. schema.statics.findNonEmptyClosestAncestor = async function(path: string): Promise<PageDocument | undefined> {
  764. if (path === '/') {
  765. return;
  766. }
  767. const builderForAncestors = new PageQueryBuilder(this.find(), false); // empty page not included
  768. const ancestors = await builderForAncestors
  769. .addConditionToListOnlyAncestors(path) // only ancestor paths
  770. .addConditionToSortPagesByDescPath() // sort by path in Desc. Long to Short.
  771. .query
  772. .exec();
  773. return ancestors[0];
  774. };
  775. export type PageCreateOptions = {
  776. format?: string
  777. grantUserGroupId?: ObjectIdLike
  778. grant?: number
  779. overwriteScopesOfDescendants?: boolean
  780. }
  781. /*
  782. * Merge obsolete page model methods and define new methods which depend on crowi instance
  783. */
  784. export default function PageModel(crowi): any {
  785. // add old page schema methods
  786. const pageSchema = getPageSchema(crowi);
  787. schema.methods = { ...pageSchema.methods, ...schema.methods };
  788. schema.statics = { ...pageSchema.statics, ...schema.statics };
  789. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  790. }