page.ts 28 KB

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