page.ts 31 KB

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