page.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import mongoose, {
  3. Schema, Model, Document, AnyObject,
  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?: boolean): 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. .addConditionToSortPagesByDescPath()
  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, false);
  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, user, userGroups): 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. await addViewerCondition(queryBuilder, user, userGroups);
  231. const _targetAndAncestors: PageDocument[] = await queryBuilder
  232. .addConditionAsMigrated()
  233. .addConditionToListByPathsArray(ancestorPaths)
  234. .addConditionToMinimizeDataForRendering()
  235. .addConditionToSortPagesByDescPath()
  236. .query
  237. .lean()
  238. .exec();
  239. // no same path pages
  240. const ancestorsMap = new Map<string, PageDocument>();
  241. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  242. const targetAndAncestors = Array.from(ancestorsMap.values());
  243. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  244. return { targetAndAncestors, rootPage };
  245. };
  246. /*
  247. * Find all children by parent's path or id. Using id should be prioritized
  248. */
  249. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  250. let queryBuilder: PageQueryBuilder;
  251. if (hasSlash(parentPathOrId)) {
  252. const path = parentPathOrId;
  253. const regexp = generateChildrenRE2(path);
  254. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp.source } }));
  255. }
  256. else {
  257. const parentId = parentPathOrId;
  258. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId }));
  259. }
  260. await addViewerCondition(queryBuilder, user, userGroups);
  261. return queryBuilder
  262. .addConditionToSortPagesByAscPath()
  263. .query
  264. .lean()
  265. .exec();
  266. };
  267. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  268. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  269. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  270. // get pages at once
  271. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }));
  272. await addViewerCondition(queryBuilder, user, userGroups);
  273. const _pages = await queryBuilder
  274. .addConditionAsMigrated()
  275. .addConditionToMinimizeDataForRendering()
  276. .addConditionToSortPagesByAscPath()
  277. .query
  278. .lean()
  279. .exec();
  280. // mark target
  281. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  282. if (page.path === path) {
  283. page.isTarget = true;
  284. }
  285. return page;
  286. });
  287. /*
  288. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  289. */
  290. const pathToChildren: Record<string, PageDocument[]> = {};
  291. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  292. sortedPaths.every((path) => {
  293. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  294. if (children.length === 0) {
  295. return false; // break when children do not exist
  296. }
  297. pathToChildren[path] = children;
  298. return true;
  299. });
  300. return pathToChildren;
  301. };
  302. /*
  303. * Merge obsolete page model methods and define new methods which depend on crowi instance
  304. */
  305. export default (crowi: Crowi): any => {
  306. // add old page schema methods
  307. const pageSchema = getPageSchema(crowi);
  308. schema.methods = { ...pageSchema.methods, ...schema.methods };
  309. schema.statics = { ...pageSchema.statics, ...schema.statics };
  310. return getOrCreateModel<PageDocument, PageModel>('Page', schema);
  311. };
  312. /*
  313. * Aggregation utilities
  314. */
  315. // TODO: use the original type when upgraded https://github.com/Automattic/mongoose/blob/master/index.d.ts#L3090
  316. type PipelineStageMatch = {
  317. $match: AnyObject
  318. };
  319. export const generateGrantCondition = async(
  320. user, _userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  321. ): Promise<PipelineStageMatch> => {
  322. let userGroups = _userGroups;
  323. if (user != null && userGroups == null) {
  324. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  325. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  326. }
  327. const grantConditions: AnyObject[] = [
  328. { grant: null },
  329. { grant: GRANT_PUBLIC },
  330. ];
  331. if (showAnyoneKnowsLink) {
  332. grantConditions.push({ grant: GRANT_RESTRICTED });
  333. }
  334. if (showPagesRestrictedByOwner) {
  335. grantConditions.push(
  336. { grant: GRANT_SPECIFIED },
  337. { grant: GRANT_OWNER },
  338. );
  339. }
  340. else if (user != null) {
  341. grantConditions.push(
  342. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  343. { grant: GRANT_OWNER, grantedUsers: user._id },
  344. );
  345. }
  346. if (showPagesRestrictedByGroup) {
  347. grantConditions.push(
  348. { grant: GRANT_USER_GROUP },
  349. );
  350. }
  351. else if (userGroups != null && userGroups.length > 0) {
  352. grantConditions.push(
  353. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  354. );
  355. }
  356. return {
  357. $match: {
  358. $or: grantConditions,
  359. },
  360. };
  361. };