page.ts 34 KB

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