page.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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): 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(pageIds: string[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]> {
  452. const baseQuery = this.find({ _id: { $in: pageIds } });
  453. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  454. await queryBuilder.addViewerCondition(user, userGroups);
  455. return queryBuilder.query.exec();
  456. };
  457. /*
  458. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  459. */
  460. schema.statics.findByPathAndViewer = async function(
  461. path: string | null, user, userGroups = null, useFindOne = false, includeEmpty = false,
  462. ): Promise<(PageDocument | PageDocument[]) & HasObjectId | null> {
  463. if (path == null) {
  464. throw new Error('path is required.');
  465. }
  466. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  467. const includeAnyoneWithTheLink = useFindOne;
  468. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  469. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  470. return queryBuilder.query.exec();
  471. };
  472. schema.statics.countByPathAndViewer = async function(path: string | null, user, userGroups = null, includeEmpty = false): Promise<number> {
  473. if (path == null) {
  474. throw new Error('path is required.');
  475. }
  476. const baseQuery = this.count({ path });
  477. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  478. await queryBuilder.addViewerCondition(user, userGroups);
  479. return queryBuilder.query.exec();
  480. };
  481. schema.statics.findRecentUpdatedPages = async function(
  482. path: string, user, options, includeEmpty = false,
  483. ): Promise<PaginatedPages> {
  484. const sortOpt = {};
  485. sortOpt[options.sort] = options.desc;
  486. const Page = this;
  487. const User = mongoose.model('User') as any;
  488. if (path == null) {
  489. throw new Error('path is required.');
  490. }
  491. const baseQuery = this.find({});
  492. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  493. if (!options.includeTrashed) {
  494. queryBuilder.addConditionToExcludeTrashed();
  495. }
  496. queryBuilder.addConditionToListWithDescendants(path, options);
  497. queryBuilder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  498. await queryBuilder.addViewerCondition(user);
  499. const pages = await Page.paginate(queryBuilder.query.clone(), {
  500. lean: true, sort: sortOpt, offset: options.offset, limit: options.limit,
  501. });
  502. const results = {
  503. pages: pages.docs, totalCount: pages.totalDocs, offset: options.offset, limit: options.limit,
  504. };
  505. return results;
  506. };
  507. /*
  508. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  509. * The result will include the target as well
  510. */
  511. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  512. let path;
  513. if (!hasSlash(pathOrId)) {
  514. const _id = pathOrId;
  515. const page = await this.findOne({ _id });
  516. path = page == null ? '/' : page.path;
  517. }
  518. else {
  519. path = pathOrId;
  520. }
  521. const ancestorPaths = collectAncestorPaths(path);
  522. ancestorPaths.push(path); // include target
  523. // Do not populate
  524. const queryBuilder = new PageQueryBuilder(this.find(), true);
  525. await queryBuilder.addViewerCondition(user, userGroups);
  526. const _targetAndAncestors: PageDocument[] = await queryBuilder
  527. .addConditionAsOnTree()
  528. .addConditionToListByPathsArray(ancestorPaths)
  529. .addConditionToMinimizeDataForRendering()
  530. .addConditionToSortPagesByDescPath()
  531. .query
  532. .lean()
  533. .exec();
  534. // no same path pages
  535. const ancestorsMap = new Map<string, PageDocument>();
  536. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  537. const targetAndAncestors = Array.from(ancestorsMap.values());
  538. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  539. return { targetAndAncestors, rootPage };
  540. };
  541. /**
  542. * Create empty pages at paths at which no pages exist
  543. * @param paths Page paths
  544. * @param aggrPipelineForExistingPages AggregationPipeline object to find existing pages at paths
  545. */
  546. schema.statics.createEmptyPagesByPaths = async function(paths: string[], aggrPipelineForExistingPages: any[]): Promise<void> {
  547. const existingPages = await this.aggregate(aggrPipelineForExistingPages);
  548. const existingPagePaths = existingPages.map(page => page.path);
  549. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  550. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  551. };
  552. /**
  553. * Find a parent page by path
  554. * @param {string} path
  555. * @returns {Promise<PageDocument | null>}
  556. */
  557. schema.statics.findParentByPath = async function(path: string): Promise<PageDocument | null> {
  558. const parentPath = nodePath.dirname(path);
  559. const builder = new PageQueryBuilder(this.find({ path: parentPath }), true);
  560. const pagesCanBeParent = await builder
  561. .addConditionAsOnTree()
  562. .query
  563. .exec();
  564. if (pagesCanBeParent.length >= 1) {
  565. return pagesCanBeParent[0]; // the earliest page will be the result
  566. }
  567. return null;
  568. };
  569. /*
  570. * Utils from obsolete-page.js
  571. */
  572. export async function pushRevision(pageData, newRevision, user) {
  573. await newRevision.save();
  574. pageData.revision = newRevision;
  575. pageData.lastUpdateUser = user?._id ?? user;
  576. pageData.updatedAt = Date.now();
  577. return pageData.save();
  578. }
  579. /**
  580. * add/subtract descendantCount of pages with provided paths by increment.
  581. * increment can be negative number
  582. */
  583. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  584. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  585. };
  586. /**
  587. * recount descendantCount of a page with the provided id and return it
  588. */
  589. schema.statics.recountDescendantCount = async function(id: ObjectIdLike): Promise<number> {
  590. const res = await this.aggregate(
  591. [
  592. {
  593. $match: {
  594. parent: id,
  595. },
  596. },
  597. {
  598. $project: {
  599. parent: 1,
  600. isEmpty: 1,
  601. descendantCount: 1,
  602. },
  603. },
  604. {
  605. $group: {
  606. _id: '$parent',
  607. sumOfDescendantCount: {
  608. $sum: '$descendantCount',
  609. },
  610. sumOfDocsCount: {
  611. $sum: {
  612. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  613. },
  614. },
  615. },
  616. },
  617. {
  618. $set: {
  619. descendantCount: {
  620. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  621. },
  622. },
  623. },
  624. ],
  625. );
  626. return res.length === 0 ? 0 : res[0].descendantCount;
  627. };
  628. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  629. const self = this;
  630. const target = await this.findById(pageId);
  631. if (target == null) {
  632. throw Error('Target not found');
  633. }
  634. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  635. const parent = await self.findOne({ _id: target.parent });
  636. if (parent == null) {
  637. return ancestors;
  638. }
  639. return findAncestorsRecursively(parent, [...ancestors, parent]);
  640. }
  641. return findAncestorsRecursively(target);
  642. };
  643. // TODO: write test code
  644. /**
  645. * Recursively removes empty pages at leaf position.
  646. * @param pageId ObjectIdLike
  647. * @returns Promise<void>
  648. */
  649. schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> {
  650. const self = this;
  651. const initialPage = await this.findById(pageId);
  652. if (initialPage == null) {
  653. return;
  654. }
  655. if (!initialPage.isEmpty) {
  656. return;
  657. }
  658. async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> {
  659. if (!page.isEmpty) {
  660. return pageIds;
  661. }
  662. const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id });
  663. if (isChildrenOtherThanTargetExist) {
  664. return pageIds;
  665. }
  666. pageIds.push(page._id);
  667. const nextPage = await self.findById(page.parent);
  668. if (nextPage == null) {
  669. return pageIds;
  670. }
  671. return generatePageIdsToRemove(page, nextPage, pageIds);
  672. }
  673. const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage);
  674. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  675. };
  676. schema.statics.normalizeDescendantCountById = async function(pageId) {
  677. const children = await this.find({ parent: pageId });
  678. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  679. const sumChildPages = children.filter(p => !p.isEmpty).length;
  680. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  681. };
  682. schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) {
  683. return this.findByIdAndUpdate(pageId, { $set: { parent: null } });
  684. };
  685. schema.statics.removeEmptyPages = async function(pageIdsToNotRemove: ObjectIdLike[], paths: string[]): Promise<void> {
  686. await this.deleteMany({
  687. _id: {
  688. $nin: pageIdsToNotRemove,
  689. },
  690. path: {
  691. $in: paths,
  692. },
  693. isEmpty: true,
  694. });
  695. };
  696. /**
  697. * Find a not empty parent recursively.
  698. * @param {string} path
  699. * @returns {Promise<PageDocument | null>}
  700. */
  701. schema.statics.findNotEmptyParentByPathRecursively = async function(path: string): Promise<PageDocument | null> {
  702. const parent = await this.findParentByPath(path);
  703. if (parent == null) {
  704. return null;
  705. }
  706. const recursive = async(page: PageDocument): Promise<PageDocument> => {
  707. if (!page.isEmpty) {
  708. return page;
  709. }
  710. const next = await this.findById(page.parent);
  711. if (next == null || isTopPage(next.path)) {
  712. return page;
  713. }
  714. return recursive(next);
  715. };
  716. const notEmptyParent = await recursive(parent);
  717. return notEmptyParent;
  718. };
  719. schema.statics.findParent = async function(pageId): Promise<PageDocument | null> {
  720. return this.findOne({ _id: pageId });
  721. };
  722. schema.statics.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type
  723. export function generateGrantCondition(
  724. user, userGroups, includeAnyoneWithTheLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  725. ): { $or: any[] } {
  726. const grantConditions: AnyObject[] = [
  727. { grant: null },
  728. { grant: GRANT_PUBLIC },
  729. ];
  730. if (includeAnyoneWithTheLink) {
  731. grantConditions.push({ grant: GRANT_RESTRICTED });
  732. }
  733. if (showPagesRestrictedByOwner) {
  734. grantConditions.push(
  735. { grant: GRANT_SPECIFIED },
  736. { grant: GRANT_OWNER },
  737. );
  738. }
  739. else if (user != null) {
  740. grantConditions.push(
  741. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  742. { grant: GRANT_OWNER, grantedUsers: user._id },
  743. );
  744. }
  745. if (showPagesRestrictedByGroup) {
  746. grantConditions.push(
  747. { grant: GRANT_USER_GROUP },
  748. );
  749. }
  750. else if (userGroups != null && userGroups.length > 0) {
  751. grantConditions.push(
  752. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  753. );
  754. }
  755. return {
  756. $or: grantConditions,
  757. };
  758. }
  759. schema.statics.generateGrantCondition = generateGrantCondition;
  760. // find ancestor page with isEmpty: false. If parameter path is '/', return undefined
  761. schema.statics.findNonEmptyClosestAncestor = async function(path: string): Promise<PageDocument | undefined> {
  762. if (path === '/') {
  763. return;
  764. }
  765. const builderForAncestors = new PageQueryBuilder(this.find(), false); // empty page not included
  766. const ancestors = await builderForAncestors
  767. .addConditionToListOnlyAncestors(path) // only ancestor paths
  768. .addConditionToSortPagesByDescPath() // sort by path in Desc. Long to Short.
  769. .query
  770. .exec();
  771. return ancestors[0];
  772. };
  773. export type PageCreateOptions = {
  774. format?: string
  775. grantUserGroupId?: ObjectIdLike
  776. grant?: number
  777. overwriteScopesOfDescendants?: boolean
  778. }
  779. /*
  780. * Merge obsolete page model methods and define new methods which depend on crowi instance
  781. */
  782. export default function PageModel(crowi): any {
  783. // add old page schema methods
  784. const pageSchema = getPageSchema(crowi);
  785. schema.methods = { ...pageSchema.methods, ...schema.methods };
  786. schema.statics = { ...pageSchema.statics, ...schema.statics };
  787. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  788. }