page.ts 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  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.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type
  825. export function generateGrantCondition(
  826. user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  827. ): { $or: any[] } {
  828. const grantConditions: AnyObject[] = [
  829. { grant: null },
  830. { grant: GRANT_PUBLIC },
  831. ];
  832. if (showAnyoneKnowsLink) {
  833. grantConditions.push({ grant: GRANT_RESTRICTED });
  834. }
  835. if (showPagesRestrictedByOwner) {
  836. grantConditions.push(
  837. { grant: GRANT_SPECIFIED },
  838. { grant: GRANT_OWNER },
  839. );
  840. }
  841. else if (user != null) {
  842. grantConditions.push(
  843. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  844. { grant: GRANT_OWNER, grantedUsers: user._id },
  845. );
  846. }
  847. if (showPagesRestrictedByGroup) {
  848. grantConditions.push(
  849. { grant: GRANT_USER_GROUP },
  850. );
  851. }
  852. else if (userGroups != null && userGroups.length > 0) {
  853. grantConditions.push(
  854. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  855. );
  856. }
  857. return {
  858. $or: grantConditions,
  859. };
  860. }
  861. schema.statics.generateGrantCondition = generateGrantCondition;
  862. export type PageCreateOptions = {
  863. format?: string
  864. grantUserGroupId?: ObjectIdLike
  865. grant?: number
  866. }
  867. /*
  868. * Merge obsolete page model methods and define new methods which depend on crowi instance
  869. */
  870. export default (crowi: Crowi): any => {
  871. let pageEvent;
  872. if (crowi != null) {
  873. pageEvent = crowi.event('page');
  874. }
  875. schema.statics.create = async function(path: string, body: string, user, options: PageCreateOptions = {}) {
  876. if (crowi.pageGrantService == null || crowi.configManager == null || crowi.pageService == null || crowi.pageOperationService == null) {
  877. throw Error('Crowi is not setup');
  878. }
  879. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  880. // v4 compatible process
  881. if (!isV5Compatible) {
  882. return this.createV4(path, body, user, options);
  883. }
  884. const canOperate = await crowi.pageOperationService.canOperate(false, null, path);
  885. if (!canOperate) {
  886. throw Error(`Cannot operate create to path "${path}" right now.`);
  887. }
  888. const Page = this;
  889. const Revision = crowi.model('Revision');
  890. const {
  891. format = 'markdown', grantUserGroupId,
  892. } = options;
  893. let grant = options.grant;
  894. // sanitize path
  895. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  896. // throw if exists
  897. const isExist = (await this.count({ path, isEmpty: false })) > 0; // not validate empty page
  898. if (isExist) {
  899. throw new Error('Cannot create new page to existed path');
  900. }
  901. // force public
  902. if (isTopPage(path)) {
  903. grant = GRANT_PUBLIC;
  904. }
  905. // find an existing empty page
  906. const emptyPage = await Page.findOne({ path, isEmpty: true });
  907. /*
  908. * UserGroup & Owner validation
  909. */
  910. if (grant !== GRANT_RESTRICTED) {
  911. let isGrantNormalized = false;
  912. try {
  913. // It must check descendants as well if emptyTarget is not null
  914. const shouldCheckDescendants = emptyPage != null;
  915. const newGrantedUserIds = grant === GRANT_OWNER ? [user._id] as IObjectId[] : undefined;
  916. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(user, path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  917. }
  918. catch (err) {
  919. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  920. throw err;
  921. }
  922. if (!isGrantNormalized) {
  923. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  924. }
  925. }
  926. /*
  927. * update empty page if exists, if not, create a new page
  928. */
  929. let page;
  930. if (emptyPage != null && grant !== GRANT_RESTRICTED) {
  931. page = emptyPage;
  932. const descendantCount = await this.recountDescendantCount(page._id);
  933. page.descendantCount = descendantCount;
  934. page.isEmpty = false;
  935. }
  936. else {
  937. page = new Page();
  938. }
  939. page.path = path;
  940. page.creator = user;
  941. page.lastUpdateUser = user;
  942. page.status = STATUS_PUBLISHED;
  943. // set parent to null when GRANT_RESTRICTED
  944. const isGrantRestricted = grant === GRANT_RESTRICTED;
  945. if (isTopPage(path) || isGrantRestricted) {
  946. page.parent = null;
  947. }
  948. else {
  949. const parent = await Page.getParentAndFillAncestors(path, user);
  950. page.parent = parent._id;
  951. }
  952. page.applyScope(user, grant, grantUserGroupId);
  953. let savedPage = await page.save();
  954. /*
  955. * After save
  956. */
  957. // Delete PageRedirect if exists
  958. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  959. try {
  960. await PageRedirect.deleteOne({ fromPath: path });
  961. logger.warn(`Deleted page redirect after creating a new page at path "${path}".`);
  962. }
  963. catch (err) {
  964. // no throw
  965. logger.error('Failed to delete PageRedirect');
  966. }
  967. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  968. savedPage = await pushRevision(savedPage, newRevision, user);
  969. await savedPage.populateDataToShowRevision();
  970. pageEvent.emit('create', savedPage, user);
  971. // update descendantCount asynchronously
  972. await crowi.pageService.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  973. return savedPage;
  974. };
  975. const shouldUseUpdatePageV4 = (grant: number, isV5Compatible: boolean, isOnTree: boolean): boolean => {
  976. const isRestricted = grant === GRANT_RESTRICTED;
  977. return !isRestricted && (!isV5Compatible || !isOnTree);
  978. };
  979. schema.statics.emitPageEventUpdate = (page: IPageHasId, user: IUserHasId): void => {
  980. pageEvent.emit('update', page, user);
  981. };
  982. schema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  983. if (crowi.configManager == null || crowi.pageGrantService == null || crowi.pageService == null) {
  984. throw Error('Crowi is not set up');
  985. }
  986. const wasOnTree = pageData.parent != null || isTopPage(pageData.path);
  987. const exParent = pageData.parent;
  988. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  989. const shouldUseV4Process = shouldUseUpdatePageV4(pageData.grant, isV5Compatible, wasOnTree);
  990. if (shouldUseV4Process) {
  991. // v4 compatible process
  992. return this.updatePageV4(pageData, body, previousBody, user, options);
  993. }
  994. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  995. const grant = options.grant || pageData.grant; // use the previous data if absence
  996. const grantUserGroupId: undefined | ObjectIdLike = options.grantUserGroupId ?? pageData.grantedGroup?._id.toString();
  997. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  998. const grantedUserIds = pageData.grantedUserIds || [user._id];
  999. const shouldBeOnTree = grant !== GRANT_RESTRICTED;
  1000. const isChildrenExist = await this.count({ path: new RegExp(`^${escapeStringRegexp(addTrailingSlash(pageData.path))}`), parent: { $ne: null } });
  1001. const newPageData = pageData;
  1002. if (shouldBeOnTree) {
  1003. let isGrantNormalized = false;
  1004. try {
  1005. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(user, pageData.path, grant, grantedUserIds, grantUserGroupId, true);
  1006. }
  1007. catch (err) {
  1008. logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err);
  1009. throw err;
  1010. }
  1011. if (!isGrantNormalized) {
  1012. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  1013. }
  1014. if (!wasOnTree) {
  1015. const newParent = await this.getParentAndFillAncestors(newPageData.path, user);
  1016. newPageData.parent = newParent._id;
  1017. }
  1018. }
  1019. else {
  1020. if (wasOnTree && isChildrenExist) {
  1021. // Update children's parent with new parent
  1022. const newParentForChildren = await this.createEmptyPage(pageData.path, pageData.parent, pageData.descendantCount);
  1023. await this.updateMany(
  1024. { parent: pageData._id },
  1025. { parent: newParentForChildren._id },
  1026. );
  1027. }
  1028. newPageData.parent = null;
  1029. newPageData.descendantCount = 0;
  1030. }
  1031. newPageData.applyScope(user, grant, grantUserGroupId);
  1032. // update existing page
  1033. let savedPage = await newPageData.save();
  1034. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user);
  1035. savedPage = await pushRevision(savedPage, newRevision, user);
  1036. await savedPage.populateDataToShowRevision();
  1037. if (isSyncRevisionToHackmd) {
  1038. savedPage = await this.syncRevisionToHackmd(savedPage);
  1039. }
  1040. this.emitPageEventUpdate(savedPage, user);
  1041. // Update ex children's parent
  1042. if (!wasOnTree && shouldBeOnTree) {
  1043. const emptyPageAtSamePath = await this.findOne({ path: pageData.path, isEmpty: true }); // this page is necessary to find children
  1044. if (isChildrenExist) {
  1045. if (emptyPageAtSamePath != null) {
  1046. // Update children's parent with new parent
  1047. await this.updateMany(
  1048. { parent: emptyPageAtSamePath._id },
  1049. { parent: savedPage._id },
  1050. );
  1051. }
  1052. }
  1053. await this.findOneAndDelete({ path: pageData.path, isEmpty: true }); // delete here
  1054. }
  1055. // Sub operation
  1056. // 1. Update descendantCount
  1057. const shouldPlusDescCount = !wasOnTree && shouldBeOnTree;
  1058. const shouldMinusDescCount = wasOnTree && !shouldBeOnTree;
  1059. if (shouldPlusDescCount) {
  1060. await crowi.pageService.updateDescendantCountOfAncestors(newPageData._id, 1, false);
  1061. const newDescendantCount = await this.recountDescendantCount(newPageData._id);
  1062. await this.updateOne({ _id: newPageData._id }, { descendantCount: newDescendantCount });
  1063. }
  1064. else if (shouldMinusDescCount) {
  1065. // Update from parent. Parent is null if newPageData.grant is RESTRECTED.
  1066. if (newPageData.grant === GRANT_RESTRICTED) {
  1067. await crowi.pageService.updateDescendantCountOfAncestors(exParent, -1, true);
  1068. }
  1069. }
  1070. // 2. Delete unnecessary empty pages
  1071. const shouldRemoveLeafEmpPages = wasOnTree && !isChildrenExist;
  1072. if (shouldRemoveLeafEmpPages) {
  1073. await this.removeLeafEmptyPagesRecursively(exParent);
  1074. }
  1075. return savedPage;
  1076. };
  1077. // add old page schema methods
  1078. const pageSchema = getPageSchema(crowi);
  1079. schema.methods = { ...pageSchema.methods, ...schema.methods };
  1080. schema.statics = { ...pageSchema.statics, ...schema.statics };
  1081. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  1082. };