page.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. createEmptyPagesByPaths(paths: string[]): Promise<void>
  34. getParentIdAndFillAncestors(path: string): Promise<string | null>
  35. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?): 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. }
  40. const ObjectId = mongoose.Schema.Types.ObjectId;
  41. const schema = new Schema<PageDocument, PageModel>({
  42. parent: {
  43. type: ObjectId, ref: 'Page', index: true, default: null,
  44. },
  45. isEmpty: { type: Boolean, default: false },
  46. path: {
  47. type: String, required: true, index: true,
  48. },
  49. revision: { type: ObjectId, ref: 'Revision' },
  50. redirectTo: { type: String, index: true },
  51. status: { type: String, default: STATUS_PUBLISHED, index: true },
  52. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  53. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  54. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  55. creator: { type: ObjectId, ref: 'User', index: true },
  56. lastUpdateUser: { type: ObjectId, ref: 'User' },
  57. liker: [{ type: ObjectId, ref: 'User' }],
  58. seenUsers: [{ type: ObjectId, ref: 'User' }],
  59. commentCount: { type: Number, default: 0 },
  60. slackChannels: { type: String },
  61. pageIdOnHackmd: { type: String },
  62. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  63. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  64. createdAt: { type: Date, default: Date.now },
  65. updatedAt: { type: Date, default: Date.now },
  66. deleteUser: { type: ObjectId, ref: 'User' },
  67. deletedAt: { type: Date },
  68. }, {
  69. toJSON: { getters: true },
  70. toObject: { getters: true },
  71. });
  72. // apply plugins
  73. schema.plugin(mongoosePaginate);
  74. schema.plugin(uniqueValidator);
  75. /*
  76. * Methods
  77. */
  78. const collectAncestorPaths = (path: string, ancestorPaths: string[] = []): string[] => {
  79. if (isTopPage(path)) return ancestorPaths;
  80. const parentPath = nodePath.dirname(path);
  81. ancestorPaths.push(parentPath);
  82. return collectAncestorPaths(parentPath, ancestorPaths);
  83. };
  84. const hasSlash = (str: string): boolean => {
  85. return str.includes('/');
  86. };
  87. /*
  88. * Generate RE2 instance for one level lower path
  89. */
  90. const generateChildrenRE2 = (path: string): RE2 => {
  91. // https://regex101.com/r/laJGzj/1
  92. // ex. /any_level1
  93. if (isTopPage(path)) return new RE2(/^\/[^/]+$/);
  94. // https://regex101.com/r/mrDJrx/1
  95. // ex. /parent/any_child OR /any_level1
  96. return new RE2(`^${path}(\\/[^/]+)\\/?$`);
  97. };
  98. /*
  99. * Generate RegExp instance for one level lower path
  100. */
  101. const generateChildrenRegExp = (path: string): RegExp => {
  102. // https://regex101.com/r/laJGzj/1
  103. // ex. /any_level1
  104. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  105. // https://regex101.com/r/mrDJrx/1
  106. // ex. /parent/any_child OR /any_level1
  107. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  108. };
  109. /*
  110. * Create empty pages if the page in paths didn't exist
  111. */
  112. schema.statics.createEmptyPagesByPaths = async function(paths: string[]): Promise<void> {
  113. // find existing parents
  114. const builder = new PageQueryBuilder(this.find({}, { _id: 0, path: 1 }));
  115. const existingPages = await builder
  116. .addConditionToListByPathsArray(paths)
  117. .query
  118. .lean()
  119. .exec();
  120. const existingPagePaths = existingPages.map(page => page.path);
  121. // paths to create empty pages
  122. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  123. // insertMany empty pages
  124. try {
  125. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  126. }
  127. catch (err) {
  128. logger.error('Failed to insert empty pages.', err);
  129. throw err;
  130. }
  131. };
  132. /*
  133. * Find the pages parent and update if the parent exists.
  134. * If not,
  135. * - first run createEmptyPagesByPaths with ancestor's paths to ensure all the ancestors exist
  136. * - second update ancestor pages' parent
  137. * - finally return the target's parent page id
  138. */
  139. schema.statics.getParentIdAndFillAncestors = async function(path: string): Promise<Schema.Types.ObjectId> {
  140. const parentPath = nodePath.dirname(path);
  141. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  142. if (parent != null) { // fill parents if parent is null
  143. return parent._id;
  144. }
  145. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  146. // just create ancestors with empty pages
  147. await this.createEmptyPagesByPaths(ancestorPaths);
  148. // find ancestors
  149. const builder = new PageQueryBuilder(this.find({}, { _id: 1, path: 1 }));
  150. const ancestors = await builder
  151. .addConditionToListByPathsArray(ancestorPaths)
  152. .addConditionToSortAncestorPages()
  153. .query
  154. .lean()
  155. .exec();
  156. const ancestorsMap = new Map(); // Map<path, _id>
  157. ancestors.forEach(page => ancestorsMap.set(page.path, page._id));
  158. // bulkWrite to update ancestors
  159. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  160. const operations = nonRootAncestors.map((page) => {
  161. const { path } = page;
  162. const parentPath = nodePath.dirname(path);
  163. return {
  164. updateOne: {
  165. filter: {
  166. path,
  167. },
  168. update: {
  169. parent: ancestorsMap.get(parentPath),
  170. },
  171. },
  172. };
  173. });
  174. await this.bulkWrite(operations);
  175. const parentId = ancestorsMap.get(parentPath);
  176. return parentId;
  177. };
  178. // Utility function to add viewer condition to PageQueryBuilder instance
  179. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  180. let relatedUserGroups = userGroups;
  181. if (user != null && relatedUserGroups == null) {
  182. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  183. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  184. }
  185. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  186. };
  187. /*
  188. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  189. */
  190. schema.statics.findByPathAndViewer = async function(
  191. path: string | null, user, userGroups = null, useFindOne = true,
  192. ): Promise<PageDocument | PageDocument[] | null> {
  193. if (path == null) {
  194. throw new Error('path is required.');
  195. }
  196. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  197. const queryBuilder = new PageQueryBuilder(baseQuery);
  198. await addViewerCondition(queryBuilder, user, userGroups);
  199. return queryBuilder.query.exec();
  200. };
  201. /*
  202. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  203. * The result will include the target as well
  204. */
  205. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string): Promise<TargetAndAncestorsResult> {
  206. let path;
  207. if (!hasSlash(pathOrId)) {
  208. const _id = pathOrId;
  209. const page = await this.findOne({ _id });
  210. if (page == null) throw new Error('Page not found.');
  211. path = page.path;
  212. }
  213. else {
  214. path = pathOrId;
  215. }
  216. const ancestorPaths = collectAncestorPaths(path);
  217. ancestorPaths.push(path); // include target
  218. // Do not populate
  219. const queryBuilder = new PageQueryBuilder(this.find());
  220. const _targetAndAncestors: PageDocument[] = await queryBuilder
  221. .addConditionToListByPathsArray(ancestorPaths)
  222. .addConditionToMinimizeDataForRendering()
  223. .addConditionToSortAncestorPages()
  224. .query
  225. .lean()
  226. .exec();
  227. // no same path pages
  228. const ancestorsMap = new Map<string, PageDocument>();
  229. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  230. const targetAndAncestors = Array.from(ancestorsMap.values());
  231. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  232. return { targetAndAncestors, rootPage };
  233. };
  234. /*
  235. * Find all children by parent's path or id. Using id should be prioritized
  236. */
  237. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  238. let queryBuilder: PageQueryBuilder;
  239. if (hasSlash(parentPathOrId)) {
  240. const path = parentPathOrId;
  241. const regexp = generateChildrenRE2(path);
  242. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp.source } }));
  243. }
  244. else {
  245. const parentId = parentPathOrId;
  246. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId }));
  247. }
  248. await addViewerCondition(queryBuilder, user, userGroups);
  249. return queryBuilder.query.lean().exec();
  250. };
  251. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  252. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path);
  253. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  254. // get pages at once
  255. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }));
  256. await addViewerCondition(queryBuilder, user, userGroups);
  257. const _pages = await queryBuilder
  258. .addConditionToMinimizeDataForRendering()
  259. .query
  260. .lean()
  261. .exec();
  262. // mark target
  263. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  264. if (page.path === path) {
  265. page.isTarget = true;
  266. }
  267. return page;
  268. });
  269. // make map
  270. const pathToChildren: Record<string, PageDocument[]> = {};
  271. ancestorPaths.forEach((path) => {
  272. pathToChildren[path] = pages.filter(page => nodePath.dirname(page.path) === path);
  273. });
  274. return pathToChildren;
  275. };
  276. /*
  277. * Merge obsolete page model methods and define new methods which depend on crowi instance
  278. */
  279. export default (crowi: Crowi): any => {
  280. // add old page schema methods
  281. const pageSchema = getPageSchema(crowi);
  282. schema.methods = { ...pageSchema.methods, ...schema.methods };
  283. schema.statics = { ...pageSchema.statics, ...schema.statics };
  284. return getOrCreateModel<PageDocument, PageModel>('Page', schema);
  285. };