page.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 { 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. export interface PageModel extends Model<PageDocument> {
  28. createEmptyPagesByPaths(paths: string[]): Promise<void>
  29. getParentIdAndFillAncestors(path: string): Promise<string | null>
  30. findByPathAndViewer(path: string | null, user, userGroups?): Promise<PageDocument[]>
  31. findSiblingsByPathAndViewer(path: string | null, user, userGroups?): Promise<PageDocument[]>
  32. findAncestorsByPath(path: string): Promise<PageDocument[]>
  33. }
  34. const ObjectId = mongoose.Schema.Types.ObjectId;
  35. const schema = new Schema<PageDocument, PageModel>({
  36. parent: {
  37. type: ObjectId, ref: 'Page', index: true, default: null,
  38. },
  39. isEmpty: { type: Boolean, default: false },
  40. path: {
  41. type: String, required: true, index: true,
  42. },
  43. revision: { type: ObjectId, ref: 'Revision' },
  44. redirectTo: { type: String, index: true },
  45. status: { type: String, default: STATUS_PUBLISHED, index: true },
  46. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  47. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  48. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  49. creator: { type: ObjectId, ref: 'User', index: true },
  50. lastUpdateUser: { type: ObjectId, ref: 'User' },
  51. liker: [{ type: ObjectId, ref: 'User' }],
  52. seenUsers: [{ type: ObjectId, ref: 'User' }],
  53. commentCount: { type: Number, default: 0 },
  54. slackChannels: { type: String },
  55. pageIdOnHackmd: { type: String },
  56. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  57. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  58. createdAt: { type: Date, default: Date.now },
  59. updatedAt: { type: Date, default: Date.now },
  60. deleteUser: { type: ObjectId, ref: 'User' },
  61. deletedAt: { type: Date },
  62. }, {
  63. toJSON: { getters: true },
  64. toObject: { getters: true },
  65. });
  66. // apply plugins
  67. schema.plugin(mongoosePaginate);
  68. schema.plugin(uniqueValidator);
  69. /*
  70. * Methods
  71. */
  72. const collectAncestorPaths = (path: string, ancestorPaths: string[] = []): string[] => {
  73. if (isTopPage(path)) return [];
  74. const parentPath = nodePath.dirname(path);
  75. ancestorPaths.push(parentPath);
  76. if (!isTopPage(path)) return collectAncestorPaths(parentPath, ancestorPaths);
  77. return ancestorPaths;
  78. };
  79. schema.statics.createEmptyPagesByPaths = async function(paths: string[]): Promise<void> {
  80. // find existing parents
  81. const builder = new PageQueryBuilder(this.find({}, { _id: 0, path: 1 }));
  82. const existingPages = await builder
  83. .addConditionToListByPathsArray(paths)
  84. .query
  85. .lean()
  86. .exec();
  87. const existingPagePaths = existingPages.map(page => page.path);
  88. // paths to create empty pages
  89. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  90. // insertMany empty pages
  91. try {
  92. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  93. }
  94. catch (err) {
  95. logger.error('Failed to insert empty pages.', err);
  96. throw err;
  97. }
  98. };
  99. schema.statics.getParentIdAndFillAncestors = async function(path: string): Promise<Schema.Types.ObjectId> {
  100. const parentPath = nodePath.dirname(path);
  101. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  102. if (parent != null) { // fill parents if parent is null
  103. return parent._id;
  104. }
  105. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  106. // just create ancestors with empty pages
  107. await this.createEmptyPagesByPaths(ancestorPaths);
  108. // find ancestors
  109. const builder = new PageQueryBuilder(this.find({}, { _id: 1, path: 1 }));
  110. const ancestors = await builder
  111. .addConditionToListByPathsArray(ancestorPaths)
  112. .addConditionToSortAncestorPages()
  113. .query
  114. .lean()
  115. .exec();
  116. const ancestorsMap = new Map(); // Map<path, _id>
  117. ancestors.forEach(page => ancestorsMap.set(page.path, page._id));
  118. // bulkWrite to update ancestors
  119. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  120. const operations = nonRootAncestors.map((page) => {
  121. const { path } = page;
  122. const parentPath = nodePath.dirname(path);
  123. return {
  124. updateOne: {
  125. filter: {
  126. path,
  127. },
  128. update: {
  129. parent: ancestorsMap.get(parentPath),
  130. },
  131. },
  132. };
  133. });
  134. await this.bulkWrite(operations);
  135. const parentId = ancestorsMap.get(parentPath);
  136. return parentId;
  137. };
  138. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  139. let relatedUserGroups = userGroups;
  140. if (user != null && relatedUserGroups == null) {
  141. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  142. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  143. }
  144. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  145. };
  146. schema.statics.findByPathAndViewer = async function(
  147. path: string | null, user, userGroups = null, useFindOne = true,
  148. ): Promise<PageDocument | PageDocument[] | null> {
  149. if (path == null) {
  150. throw new Error('path is required.');
  151. }
  152. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  153. const queryBuilder = new PageQueryBuilder(baseQuery);
  154. await addViewerCondition(queryBuilder, user, userGroups);
  155. return queryBuilder.query.exec();
  156. };
  157. schema.statics.findSiblingsByPathAndViewer = async function(path: string | null, user, userGroups): Promise<PageDocument[]> {
  158. if (path == null) {
  159. throw new Error('path is required.');
  160. }
  161. const _parentPath = nodePath.dirname(path);
  162. // regexr.com/6889f
  163. // ex. /parent/any_child OR /any_level1
  164. const parentPath = isTopPage(_parentPath) ? '' : _parentPath;
  165. let regexp = new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`);
  166. // ex. / OR /any_level1
  167. if (isTopPage(path)) regexp = /^\/[^/]*$/g;
  168. const queryBuilder = new PageQueryBuilder(this.find({ path: regexp }));
  169. await addViewerCondition(queryBuilder, user, userGroups);
  170. return queryBuilder.query.lean().exec();
  171. };
  172. schema.statics.findAncestorsByPath = async function(path: string): Promise<PageDocument[]> {
  173. const ancestorPaths = collectAncestorPaths(path);
  174. // Do not populate
  175. const queryBuilder = new PageQueryBuilder(this.find());
  176. const _ancestors: PageDocument[] = await queryBuilder
  177. .addConditionToListByPathsArray(ancestorPaths)
  178. .addConditionToSortAncestorPages()
  179. .query
  180. .lean()
  181. .exec();
  182. // no same path pages
  183. const ancestorsMap = new Map<string, PageDocument>();
  184. _ancestors.forEach(page => ancestorsMap.set(page.path, page));
  185. const ancestors = Array.from(ancestorsMap.values());
  186. return ancestors;
  187. };
  188. /*
  189. * Merge obsolete page model methods and define new methods which depend on crowi instance
  190. */
  191. export default (crowi: Crowi): any => {
  192. // add old page schema methods
  193. const pageSchema = getPageSchema(crowi);
  194. schema.methods = { ...pageSchema.methods, ...schema.methods };
  195. schema.statics = { ...pageSchema.statics, ...schema.statics };
  196. return getOrCreateModel<PageDocument, PageModel>('Page', schema);
  197. };