page.ts 34 KB

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