page.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import mongoose, {
  3. Schema, Model, Document,
  4. } from 'mongoose';
  5. import mongoosePaginate from 'mongoose-paginate-v2';
  6. import uniqueValidator from 'mongoose-unique-validator';
  7. import nodePath from 'path';
  8. import RE2 from 're2';
  9. import { getOrCreateModel, pagePathUtils } from '@growi/core';
  10. import loggerFactory from '../../utils/logger';
  11. import Crowi from '../crowi';
  12. import { IPage } from '../../interfaces/page';
  13. import { getPageSchema, PageQueryBuilder } from './obsolete-page';
  14. const { isTopPage } = pagePathUtils;
  15. const logger = loggerFactory('growi:models:page');
  16. /*
  17. * define schema
  18. */
  19. const GRANT_PUBLIC = 1;
  20. const GRANT_RESTRICTED = 2;
  21. const GRANT_SPECIFIED = 3;
  22. const GRANT_OWNER = 4;
  23. const GRANT_USER_GROUP = 5;
  24. const PAGE_GRANT_ERROR = 1;
  25. const STATUS_PUBLISHED = 'published';
  26. const STATUS_DELETED = 'deleted';
  27. export interface PageDocument extends IPage, Document {}
  28. type TargetAndAncestorsResult = {
  29. targetAndAncestors: PageDocument[]
  30. rootPage: PageDocument
  31. }
  32. export interface PageModel extends Model<PageDocument> {
  33. [x: string]: any; // for obsolete methods
  34. createEmptyPagesByPaths(paths: string[]): Promise<void>
  35. getParentIdAndFillAncestors(path: string): Promise<string | null>
  36. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?): Promise<PageDocument[]>
  37. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  38. findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups?): Promise<PageDocument[]>
  39. findAncestorsChildrenByPathAndViewer(path: string, user, userGroups?): Promise<Record<string, PageDocument[]>>
  40. PageQueryBuilder: typeof PageQueryBuilder
  41. GRANT_PUBLIC
  42. GRANT_RESTRICTED
  43. GRANT_SPECIFIED
  44. GRANT_OWNER
  45. GRANT_USER_GROUP
  46. PAGE_GRANT_ERROR
  47. STATUS_PUBLISHED
  48. STATUS_DELETED
  49. }
  50. const ObjectId = mongoose.Schema.Types.ObjectId;
  51. const schema = new Schema<PageDocument, PageModel>({
  52. parent: {
  53. type: ObjectId, ref: 'Page', index: true, default: null,
  54. },
  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 RE2 instance for one level lower path
  99. */
  100. const generateChildrenRE2 = (path: string): RE2 => {
  101. // https://regex101.com/r/laJGzj/1
  102. // ex. /any_level1
  103. if (isTopPage(path)) return new RE2(/^\/[^/]+$/);
  104. // https://regex101.com/r/mrDJrx/1
  105. // ex. /parent/any_child OR /any_level1
  106. return new RE2(`^${path}(\\/[^/]+)\\/?$`);
  107. };
  108. /*
  109. * Generate RegExp instance for one level lower path
  110. */
  111. const generateChildrenRegExp = (path: string): RegExp => {
  112. // https://regex101.com/r/laJGzj/1
  113. // ex. /any_level1
  114. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  115. // https://regex101.com/r/mrDJrx/1
  116. // ex. /parent/any_child OR /any_level1
  117. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  118. };
  119. /*
  120. * Create empty pages if the page in paths didn't exist
  121. */
  122. schema.statics.createEmptyPagesByPaths = async function(paths: string[]): Promise<void> {
  123. // find existing parents
  124. const builder = new PageQueryBuilder(this.find({}, { _id: 0, path: 1 }));
  125. const existingPages = await builder
  126. .addConditionToListByPathsArray(paths)
  127. .query
  128. .lean()
  129. .exec();
  130. const existingPagePaths = existingPages.map(page => page.path);
  131. // paths to create empty pages
  132. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  133. // insertMany empty pages
  134. try {
  135. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  136. }
  137. catch (err) {
  138. logger.error('Failed to insert empty pages.', err);
  139. throw err;
  140. }
  141. };
  142. /*
  143. * Find the pages parent and update if the parent exists.
  144. * If not,
  145. * - first run createEmptyPagesByPaths with ancestor's paths to ensure all the ancestors exist
  146. * - second update ancestor pages' parent
  147. * - finally return the target's parent page id
  148. */
  149. schema.statics.getParentIdAndFillAncestors = async function(path: string): Promise<Schema.Types.ObjectId> {
  150. const parentPath = nodePath.dirname(path);
  151. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  152. if (parent != null) { // fill parents if parent is null
  153. return parent._id;
  154. }
  155. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  156. // just create ancestors with empty pages
  157. await this.createEmptyPagesByPaths(ancestorPaths);
  158. // find ancestors
  159. const builder = new PageQueryBuilder(this.find({}, { _id: 1, path: 1 }));
  160. const ancestors = await builder
  161. .addConditionToListByPathsArray(ancestorPaths)
  162. .addConditionToSortAncestorPages()
  163. .query
  164. .lean()
  165. .exec();
  166. const ancestorsMap = new Map(); // Map<path, _id>
  167. ancestors.forEach(page => ancestorsMap.set(page.path, page._id));
  168. // bulkWrite to update ancestors
  169. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  170. const operations = nonRootAncestors.map((page) => {
  171. const { path } = page;
  172. const parentPath = nodePath.dirname(path);
  173. return {
  174. updateOne: {
  175. filter: {
  176. path,
  177. },
  178. update: {
  179. parent: ancestorsMap.get(parentPath),
  180. },
  181. },
  182. };
  183. });
  184. await this.bulkWrite(operations);
  185. const parentId = ancestorsMap.get(parentPath);
  186. return parentId;
  187. };
  188. // Utility function to add viewer condition to PageQueryBuilder instance
  189. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  190. let relatedUserGroups = userGroups;
  191. if (user != null && relatedUserGroups == null) {
  192. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  193. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  194. }
  195. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  196. };
  197. /*
  198. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  199. */
  200. schema.statics.findByPathAndViewer = async function(
  201. path: string | null, user, userGroups = null, useFindOne = true,
  202. ): Promise<PageDocument | PageDocument[] | null> {
  203. if (path == null) {
  204. throw new Error('path is required.');
  205. }
  206. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  207. const queryBuilder = new PageQueryBuilder(baseQuery);
  208. await addViewerCondition(queryBuilder, user, userGroups);
  209. return queryBuilder.query.exec();
  210. };
  211. /*
  212. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  213. * The result will include the target as well
  214. */
  215. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string): Promise<TargetAndAncestorsResult> {
  216. let path;
  217. if (!hasSlash(pathOrId)) {
  218. const _id = pathOrId;
  219. const page = await this.findOne({ _id });
  220. if (page == null) throw new Error('Page not found.');
  221. path = page.path;
  222. }
  223. else {
  224. path = pathOrId;
  225. }
  226. const ancestorPaths = collectAncestorPaths(path);
  227. ancestorPaths.push(path); // include target
  228. // Do not populate
  229. const queryBuilder = new PageQueryBuilder(this.find());
  230. const _targetAndAncestors: PageDocument[] = await queryBuilder
  231. .addConditionToListByPathsArray(ancestorPaths)
  232. .addConditionToMinimizeDataForRendering()
  233. .addConditionToSortAncestorPages()
  234. .query
  235. .lean()
  236. .exec();
  237. // no same path pages
  238. const ancestorsMap = new Map<string, PageDocument>();
  239. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  240. const targetAndAncestors = Array.from(ancestorsMap.values());
  241. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  242. return { targetAndAncestors, rootPage };
  243. };
  244. /*
  245. * Find all children by parent's path or id. Using id should be prioritized
  246. */
  247. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  248. let queryBuilder: PageQueryBuilder;
  249. if (hasSlash(parentPathOrId)) {
  250. const path = parentPathOrId;
  251. const regexp = generateChildrenRE2(path);
  252. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp.source } }));
  253. }
  254. else {
  255. const parentId = parentPathOrId;
  256. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId }));
  257. }
  258. await addViewerCondition(queryBuilder, user, userGroups);
  259. return queryBuilder.query.lean().exec();
  260. };
  261. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  262. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path);
  263. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  264. // get pages at once
  265. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }));
  266. await addViewerCondition(queryBuilder, user, userGroups);
  267. const _pages = await queryBuilder
  268. .addConditionToMinimizeDataForRendering()
  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. // make map
  280. const pathToChildren: Record<string, PageDocument[]> = {};
  281. ancestorPaths.forEach((path) => {
  282. pathToChildren[path] = pages.filter(page => nodePath.dirname(page.path) === path);
  283. });
  284. return pathToChildren;
  285. };
  286. /*
  287. * Merge obsolete page model methods and define new methods which depend on crowi instance
  288. */
  289. export default (crowi: Crowi): any => {
  290. // add old page schema methods
  291. const pageSchema = getPageSchema(crowi);
  292. schema.methods = { ...pageSchema.methods, ...schema.methods };
  293. schema.statics = { ...pageSchema.statics, ...schema.statics };
  294. return getOrCreateModel<PageDocument, PageModel>('Page', schema);
  295. };