page.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 nodePath from 'path';
  8. import { getOrCreateModel, pagePathUtils } from '@growi/core';
  9. import loggerFactory from '../../utils/logger';
  10. import Crowi from '../crowi';
  11. import { IPage } from '../../interfaces/page';
  12. import { getPageSchema, PageQueryBuilder } from './obsolete-page';
  13. const { isTopPage, collectAncestorPaths } = pagePathUtils;
  14. const logger = loggerFactory('growi:models:page');
  15. /*
  16. * define schema
  17. */
  18. const GRANT_PUBLIC = 1;
  19. const GRANT_RESTRICTED = 2;
  20. const GRANT_SPECIFIED = 3;
  21. const GRANT_OWNER = 4;
  22. const GRANT_USER_GROUP = 5;
  23. const PAGE_GRANT_ERROR = 1;
  24. const STATUS_PUBLISHED = 'published';
  25. const STATUS_DELETED = 'deleted';
  26. export interface PageDocument extends IPage, Document {}
  27. type TargetAndAncestorsResult = {
  28. targetAndAncestors: PageDocument[]
  29. rootPage: PageDocument
  30. }
  31. export interface PageModel extends Model<PageDocument> {
  32. [x: string]: any; // for obsolete methods
  33. createEmptyPagesByPaths(paths: string[], publicOnly?: boolean): Promise<void>
  34. getParentIdAndFillAncestors(path: string): Promise<string | null>
  35. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument[]>
  36. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  37. findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups?): Promise<PageDocument[]>
  38. findAncestorsChildrenByPathAndViewer(path: string, user, userGroups?): Promise<Record<string, PageDocument[]>>
  39. PageQueryBuilder: typeof PageQueryBuilder
  40. GRANT_PUBLIC
  41. GRANT_RESTRICTED
  42. GRANT_SPECIFIED
  43. GRANT_OWNER
  44. GRANT_USER_GROUP
  45. PAGE_GRANT_ERROR
  46. STATUS_PUBLISHED
  47. STATUS_DELETED
  48. }
  49. const ObjectId = mongoose.Schema.Types.ObjectId;
  50. const schema = new Schema<PageDocument, PageModel>({
  51. parent: {
  52. type: ObjectId, ref: 'Page', index: true, default: null,
  53. },
  54. descendantCount: { type: Number, default: 0 },
  55. isEmpty: { type: Boolean, default: false },
  56. path: {
  57. type: String, required: true, index: true,
  58. },
  59. revision: { type: ObjectId, ref: 'Revision' },
  60. redirectTo: { type: String, index: true },
  61. status: { type: String, default: STATUS_PUBLISHED, index: true },
  62. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  63. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  64. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  65. creator: { type: ObjectId, ref: 'User', index: true },
  66. lastUpdateUser: { type: ObjectId, ref: 'User' },
  67. liker: [{ type: ObjectId, ref: 'User' }],
  68. seenUsers: [{ type: ObjectId, ref: 'User' }],
  69. commentCount: { type: Number, default: 0 },
  70. slackChannels: { type: String },
  71. pageIdOnHackmd: { type: String },
  72. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  73. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  74. createdAt: { type: Date, default: new Date() },
  75. updatedAt: { type: Date, default: new Date() },
  76. deleteUser: { type: ObjectId, ref: 'User' },
  77. deletedAt: { type: Date },
  78. }, {
  79. toJSON: { getters: true },
  80. toObject: { getters: true },
  81. });
  82. // apply plugins
  83. schema.plugin(mongoosePaginate);
  84. schema.plugin(uniqueValidator);
  85. const hasSlash = (str: string): boolean => {
  86. return str.includes('/');
  87. };
  88. /*
  89. * Generate RegExp instance for one level lower path
  90. */
  91. const generateChildrenRegExp = (path: string): RegExp => {
  92. // https://regex101.com/r/laJGzj/1
  93. // ex. /any_level1
  94. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  95. // https://regex101.com/r/mrDJrx/1
  96. // ex. /parent/any_child OR /any_level1
  97. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  98. };
  99. /*
  100. * Create empty pages if the page in paths didn't exist
  101. */
  102. schema.statics.createEmptyPagesByPaths = async function(paths: string[], publicOnly = false): Promise<void> {
  103. // find existing parents
  104. const builder = new PageQueryBuilder(this.find(publicOnly ? { grant: GRANT_PUBLIC } : {}, { _id: 0, path: 1 }), true);
  105. const existingPages = await builder
  106. .addConditionToListByPathsArray(paths)
  107. .query
  108. .lean()
  109. .exec();
  110. const existingPagePaths = existingPages.map(page => page.path);
  111. // paths to create empty pages
  112. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  113. // insertMany empty pages
  114. try {
  115. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  116. }
  117. catch (err) {
  118. logger.error('Failed to insert empty pages.', err);
  119. throw err;
  120. }
  121. };
  122. /*
  123. * Find the parent and update if the parent exists.
  124. * If not,
  125. * - first run createEmptyPagesByPaths with ancestor's paths to ensure all the ancestors exist
  126. * - second update ancestor pages' parent
  127. * - finally return the target's parent page id
  128. */
  129. schema.statics.getParentIdAndFillAncestors = async function(path: string): Promise<Schema.Types.ObjectId> {
  130. const parentPath = nodePath.dirname(path);
  131. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  132. if (parent != null) {
  133. return parent._id;
  134. }
  135. /*
  136. * Fill parents if parent is null
  137. */
  138. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  139. // just create ancestors with empty pages
  140. await this.createEmptyPagesByPaths(ancestorPaths);
  141. // find ancestors
  142. const builder = new PageQueryBuilder(this.find({}, { _id: 1, path: 1 }), true);
  143. const ancestors = await builder
  144. .addConditionToListByPathsArray(ancestorPaths)
  145. .addConditionToSortPagesByDescPath()
  146. .query
  147. .lean()
  148. .exec();
  149. const ancestorsMap = new Map(); // Map<path, _id>
  150. ancestors.forEach(page => ancestorsMap.set(page.path, page._id));
  151. // bulkWrite to update ancestors
  152. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  153. const operations = nonRootAncestors.map((page) => {
  154. const { path } = page;
  155. const parentPath = nodePath.dirname(path);
  156. return {
  157. updateOne: {
  158. filter: {
  159. path,
  160. },
  161. update: {
  162. parent: ancestorsMap.get(parentPath),
  163. },
  164. },
  165. };
  166. });
  167. await this.bulkWrite(operations);
  168. const parentId = ancestorsMap.get(parentPath);
  169. return parentId;
  170. };
  171. // Utility function to add viewer condition to PageQueryBuilder instance
  172. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  173. let relatedUserGroups = userGroups;
  174. if (user != null && relatedUserGroups == null) {
  175. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  176. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  177. }
  178. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, false);
  179. };
  180. /*
  181. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  182. */
  183. schema.statics.findByPathAndViewer = async function(
  184. path: string | null, user, userGroups = null, useFindOne = true, includeEmpty = false,
  185. ): Promise<PageDocument | PageDocument[] | null> {
  186. if (path == null) {
  187. throw new Error('path is required.');
  188. }
  189. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  190. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  191. await addViewerCondition(queryBuilder, user, userGroups);
  192. return queryBuilder.query.exec();
  193. };
  194. /*
  195. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  196. * The result will include the target as well
  197. */
  198. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  199. let path;
  200. if (!hasSlash(pathOrId)) {
  201. const _id = pathOrId;
  202. const page = await this.findOne({ _id });
  203. if (page == null) throw new Error('Page not found.');
  204. path = page.path;
  205. }
  206. else {
  207. path = pathOrId;
  208. }
  209. const ancestorPaths = collectAncestorPaths(path);
  210. ancestorPaths.push(path); // include target
  211. // Do not populate
  212. const queryBuilder = new PageQueryBuilder(this.find(), true);
  213. await addViewerCondition(queryBuilder, user, userGroups);
  214. const _targetAndAncestors: PageDocument[] = await queryBuilder
  215. .addConditionAsMigrated()
  216. .addConditionToListByPathsArray(ancestorPaths)
  217. .addConditionToMinimizeDataForRendering()
  218. .addConditionToSortPagesByDescPath()
  219. .query
  220. .lean()
  221. .exec();
  222. // no same path pages
  223. const ancestorsMap = new Map<string, PageDocument>();
  224. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  225. const targetAndAncestors = Array.from(ancestorsMap.values());
  226. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  227. return { targetAndAncestors, rootPage };
  228. };
  229. /*
  230. * Find all children by parent's path or id. Using id should be prioritized
  231. */
  232. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  233. let queryBuilder: PageQueryBuilder;
  234. if (hasSlash(parentPathOrId)) {
  235. const path = parentPathOrId;
  236. const regexp = generateChildrenRegExp(path);
  237. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp } }), true);
  238. }
  239. else {
  240. const parentId = parentPathOrId;
  241. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId }), true);
  242. }
  243. await addViewerCondition(queryBuilder, user, userGroups);
  244. return queryBuilder
  245. .addConditionToSortPagesByAscPath()
  246. .query
  247. .lean()
  248. .exec();
  249. };
  250. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  251. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  252. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  253. // get pages at once
  254. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }), true);
  255. await addViewerCondition(queryBuilder, user, userGroups);
  256. const _pages = await queryBuilder
  257. .addConditionAsMigrated()
  258. .addConditionToMinimizeDataForRendering()
  259. .addConditionToSortPagesByAscPath()
  260. .query
  261. .lean()
  262. .exec();
  263. // mark target
  264. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  265. if (page.path === path) {
  266. page.isTarget = true;
  267. }
  268. return page;
  269. });
  270. /*
  271. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  272. */
  273. const pathToChildren: Record<string, PageDocument[]> = {};
  274. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  275. sortedPaths.every((path) => {
  276. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  277. if (children.length === 0) {
  278. return false; // break when children do not exist
  279. }
  280. pathToChildren[path] = children;
  281. return true;
  282. });
  283. return pathToChildren;
  284. };
  285. /**
  286. * return aggregate condition to get following pages
  287. * - page that has the same path as the provided path
  288. * - pages that are descendants of the above page
  289. * pages without parent will be ignored
  290. */
  291. schema.statics.getAggrConditionForPageWithProvidedPathAndDescendants = function(path:string) {
  292. let match;
  293. if (isTopPage(path)) {
  294. match = {
  295. // https://regex101.com/r/Kip2rV/1
  296. $match: { $or: [{ path: { $regex: '^/.*' }, parent: { $ne: null } }, { path: '/' }] },
  297. };
  298. }
  299. else {
  300. match = {
  301. // https://regex101.com/r/mJvGrG/1
  302. $match: { path: { $regex: `^${path}(/.*|$)` }, parent: { $ne: null } },
  303. };
  304. }
  305. return [
  306. match,
  307. {
  308. $project: {
  309. path: 1,
  310. parent: 1,
  311. field_length: { $strLenCP: '$path' },
  312. },
  313. },
  314. { $sort: { field_length: -1 } },
  315. { $project: { field_length: 0 } },
  316. ];
  317. };
  318. // update descendantCount of pages with provided paths by count
  319. schema.statics.recountDescendantCountOfPathsByCount = async function(paths:string[], count: number):Promise<void> {
  320. const pages = await this.aggregate([{ $match: { path: { $in: paths } } }]);
  321. const operations = pages.map((page) => {
  322. return {
  323. updateOne: {
  324. filter: { path: page.path },
  325. update: { descendantCount: page.descendantCount + count },
  326. },
  327. };
  328. });
  329. await this.bulkWrite(operations);
  330. };
  331. // update descendantCount of a page with provided id
  332. schema.statics.recountDescendantCountOfSelfAndDescendants = async function(id:mongoose.Types.ObjectId):Promise<void> {
  333. const res = await this.aggregate(
  334. [
  335. {
  336. $match: {
  337. parent: id,
  338. },
  339. },
  340. {
  341. $project: {
  342. path: 1,
  343. parent: 1,
  344. descendantCount: 1,
  345. },
  346. },
  347. {
  348. $group: {
  349. _id: '$parent',
  350. sumOfDescendantCount: {
  351. $sum: '$descendantCount',
  352. },
  353. sumOfDocsCount: {
  354. $sum: 1,
  355. },
  356. },
  357. },
  358. {
  359. $set: {
  360. descendantCount: {
  361. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  362. },
  363. },
  364. },
  365. ],
  366. );
  367. const query = { descendantCount: res.length === 0 ? 0 : res[0].descendantCount };
  368. await this.findByIdAndUpdate(id, query);
  369. };
  370. /*
  371. * Merge obsolete page model methods and define new methods which depend on crowi instance
  372. */
  373. export default (crowi: Crowi): any => {
  374. // add old page schema methods
  375. const pageSchema = getPageSchema(crowi);
  376. schema.methods = { ...pageSchema.methods, ...schema.methods };
  377. schema.statics = { ...pageSchema.statics, ...schema.statics };
  378. return getOrCreateModel<PageDocument, PageModel>('Page', schema);
  379. };
  380. /*
  381. * Aggregation utilities
  382. */
  383. // TODO: use the original type when upgraded https://github.com/Automattic/mongoose/blob/master/index.d.ts#L3090
  384. type PipelineStageMatch = {
  385. $match: AnyObject
  386. };
  387. export const generateGrantCondition = async(
  388. user, _userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  389. ): Promise<PipelineStageMatch> => {
  390. let userGroups = _userGroups;
  391. if (user != null && userGroups == null) {
  392. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  393. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  394. }
  395. const grantConditions: AnyObject[] = [
  396. { grant: null },
  397. { grant: GRANT_PUBLIC },
  398. ];
  399. if (showAnyoneKnowsLink) {
  400. grantConditions.push({ grant: GRANT_RESTRICTED });
  401. }
  402. if (showPagesRestrictedByOwner) {
  403. grantConditions.push(
  404. { grant: GRANT_SPECIFIED },
  405. { grant: GRANT_OWNER },
  406. );
  407. }
  408. else if (user != null) {
  409. grantConditions.push(
  410. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  411. { grant: GRANT_OWNER, grantedUsers: user._id },
  412. );
  413. }
  414. if (showPagesRestrictedByGroup) {
  415. grantConditions.push(
  416. { grant: GRANT_USER_GROUP },
  417. );
  418. }
  419. else if (userGroups != null && userGroups.length > 0) {
  420. grantConditions.push(
  421. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  422. );
  423. }
  424. return {
  425. $match: {
  426. $or: grantConditions,
  427. },
  428. };
  429. };