page.ts 9.9 KB

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