page.ts 28 KB

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