page.ts 15 KB

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