page.ts 11 KB

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