2
0

page.ts 39 KB

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