page.ts 34 KB

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