obsolete-page.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. import { GroupType, Origin } from '@growi/core';
  2. import { templateChecker, pagePathUtils, pathUtils } from '@growi/core/dist/utils';
  3. import { differenceInYears } from 'date-fns/differenceInYears';
  4. import escapeStringRegexp from 'escape-string-regexp';
  5. import { Comment } from '~/features/comment/server/models/comment';
  6. import ExternalUserGroup from '~/features/external-user-group/server/models/external-user-group';
  7. import ExternalUserGroupRelation from '~/features/external-user-group/server/models/external-user-group-relation';
  8. import loggerFactory from '~/utils/logger';
  9. import UserGroup from './user-group';
  10. import UserGroupRelation from './user-group-relation';
  11. // disable no-return-await for model functions
  12. /* eslint-disable no-return-await */
  13. /* eslint-disable no-use-before-define */
  14. const nodePath = require('path');
  15. const debug = require('debug')('growi:models:page');
  16. const mongoose = require('mongoose');
  17. const urljoin = require('url-join');
  18. const { isTopPage, isTrashPage } = pagePathUtils;
  19. const { checkTemplatePath } = templateChecker;
  20. const logger = loggerFactory('growi:models:page');
  21. const GRANT_PUBLIC = 1;
  22. const GRANT_RESTRICTED = 2;
  23. const GRANT_SPECIFIED = 3;
  24. const GRANT_OWNER = 4;
  25. const GRANT_USER_GROUP = 5;
  26. const PAGE_GRANT_ERROR = 1;
  27. const STATUS_PUBLISHED = 'published';
  28. const STATUS_DELETED = 'deleted';
  29. // schema definition has moved to page.ts
  30. const pageSchema = {
  31. statics: {},
  32. methods: {},
  33. };
  34. /**
  35. * return an array of ancestors paths that is extracted from specified pagePath
  36. * e.g.
  37. * when `pagePath` is `/foo/bar/baz`,
  38. * this method returns [`/foo/bar/baz`, `/foo/bar`, `/foo`, `/`]
  39. *
  40. * @param {string} pagePath
  41. * @return {string[]} ancestors paths
  42. */
  43. export const extractToAncestorsPaths = (pagePath) => {
  44. const ancestorsPaths = [];
  45. let parentPath;
  46. while (parentPath !== '/') {
  47. parentPath = nodePath.dirname(parentPath || pagePath);
  48. ancestorsPaths.push(parentPath);
  49. }
  50. return ancestorsPaths;
  51. };
  52. /**
  53. * populate page (Query or Document) to show revision
  54. * @param {any} page Query or Document
  55. * @param {string} userPublicFields string to set to select
  56. * @param {boolean} shouldExcludeBody boolean indicating whether to include 'revision.body' or not
  57. */
  58. /* eslint-disable object-curly-newline, object-property-newline */
  59. export const populateDataToShowRevision = (page, userPublicFields, shouldExcludeBody = false) => {
  60. return page
  61. .populate([
  62. { path: 'lastUpdateUser', select: userPublicFields },
  63. { path: 'creator', select: userPublicFields },
  64. { path: 'deleteUser', select: userPublicFields },
  65. { path: 'grantedGroups.item' },
  66. { path: 'revision', select: shouldExcludeBody ? '-body' : undefined, populate: {
  67. path: 'author', select: userPublicFields,
  68. } },
  69. ]);
  70. };
  71. /* eslint-enable object-curly-newline, object-property-newline */
  72. export const getPageSchema = (crowi) => {
  73. let pageEvent;
  74. // init event
  75. if (crowi != null) {
  76. pageEvent = crowi.event('page');
  77. pageEvent.on('create', pageEvent.onCreate);
  78. pageEvent.on('update', pageEvent.onUpdate);
  79. pageEvent.on('createMany', pageEvent.onCreateMany);
  80. pageEvent.on('addSeenUsers', pageEvent.onAddSeenUsers);
  81. }
  82. function validateCrowi() {
  83. if (crowi == null) {
  84. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  85. }
  86. }
  87. pageSchema.methods.isDeleted = function() {
  88. return isTrashPage(this.path);
  89. };
  90. pageSchema.methods.isPublic = function() {
  91. if (!this.grant || this.grant === GRANT_PUBLIC) {
  92. return true;
  93. }
  94. return false;
  95. };
  96. pageSchema.methods.isTopPage = function() {
  97. return isTopPage(this.path);
  98. };
  99. pageSchema.methods.isTemplate = function() {
  100. return checkTemplatePath(this.path);
  101. };
  102. pageSchema.methods.isLatestRevision = function() {
  103. // populate されていなくて判断できない
  104. if (!this.latestRevision || !this.revision) {
  105. return true;
  106. }
  107. // comparing ObjectId with string
  108. // eslint-disable-next-line eqeqeq
  109. return (this.latestRevision == this.revision._id.toString());
  110. };
  111. pageSchema.methods.findRelatedTagsById = async function() {
  112. const PageTagRelation = mongoose.model('PageTagRelation');
  113. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  114. return relations.map((relation) => { return relation.relatedTag.name });
  115. };
  116. pageSchema.methods.isUpdatable = async function(previousRevision, origin) {
  117. const populatedPageDataWithRevisionOrigin = await this.populate('revision', 'origin');
  118. const latestRevisionOrigin = populatedPageDataWithRevisionOrigin.revision.origin;
  119. const ignoreLatestRevision = origin === Origin.Editor && (latestRevisionOrigin === Origin.Editor || latestRevisionOrigin === Origin.View);
  120. if (ignoreLatestRevision) {
  121. return true;
  122. }
  123. const revision = this.latestRevision || this.revision._id;
  124. // comparing ObjectId with string
  125. // eslint-disable-next-line eqeqeq
  126. if (revision != previousRevision) {
  127. return false;
  128. }
  129. return true;
  130. };
  131. pageSchema.methods.isLiked = function(user) {
  132. if (user == null || user._id == null) {
  133. return false;
  134. }
  135. return this.liker.some((likedUserId) => {
  136. return likedUserId.toString() === user._id.toString();
  137. });
  138. };
  139. pageSchema.methods.like = function(userData) {
  140. const self = this;
  141. return new Promise(((resolve, reject) => {
  142. const added = self.liker.addToSet(userData._id);
  143. if (added.length > 0) {
  144. self.save((err, data) => {
  145. if (err) {
  146. return reject(err);
  147. }
  148. logger.debug('liker updated!', added);
  149. return resolve(data);
  150. });
  151. }
  152. else {
  153. logger.debug('liker not updated');
  154. return reject(new Error('Already liked'));
  155. }
  156. }));
  157. };
  158. pageSchema.methods.unlike = function(userData, callback) {
  159. const self = this;
  160. return new Promise(((resolve, reject) => {
  161. const beforeCount = self.liker.length;
  162. self.liker.pull(userData._id);
  163. if (self.liker.length !== beforeCount) {
  164. self.save((err, data) => {
  165. if (err) {
  166. return reject(err);
  167. }
  168. return resolve(data);
  169. });
  170. }
  171. else {
  172. logger.debug('liker not updated');
  173. return reject(new Error('Already unliked'));
  174. }
  175. }));
  176. };
  177. pageSchema.methods.isSeenUser = function(userData) {
  178. return this.seenUsers.includes(userData._id);
  179. };
  180. pageSchema.methods.seen = async function(userData) {
  181. if (this.isSeenUser(userData)) {
  182. debug('seenUsers not updated');
  183. return this;
  184. }
  185. if (!userData || !userData._id) {
  186. throw new Error('User data is not valid');
  187. }
  188. const added = this.seenUsers.addToSet(userData._id);
  189. const saved = await this.save();
  190. debug('seenUsers updated!', added);
  191. pageEvent.emit('addSeenUsers', saved);
  192. return saved;
  193. };
  194. pageSchema.methods.updateSlackChannels = function(slackChannels) {
  195. this.slackChannels = slackChannels;
  196. return this.save();
  197. };
  198. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  199. this.latestRevision = this.revision;
  200. if (revisionId != null) {
  201. this.revision = revisionId;
  202. }
  203. };
  204. pageSchema.methods.populateDataToShowRevision = async function(shouldExcludeBody) {
  205. validateCrowi();
  206. const User = crowi.model('User');
  207. return populateDataToShowRevision(this, User.USER_FIELDS_EXCEPT_CONFIDENTIAL, shouldExcludeBody);
  208. };
  209. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  210. this.latestRevision = this.revision;
  211. if (revisionId != null) {
  212. this.revision = revisionId;
  213. }
  214. return this.populate('revision');
  215. };
  216. pageSchema.methods.applyScope = function(user, grant, grantUserGroupIds) {
  217. // Reset
  218. this.grantedUsers = [];
  219. this.grantedGroups = [];
  220. this.grant = grant || GRANT_PUBLIC;
  221. if (grant === GRANT_OWNER) {
  222. this.grantedUsers.push(user?._id ?? user);
  223. }
  224. if (grant === GRANT_USER_GROUP) {
  225. this.grantedGroups = grantUserGroupIds;
  226. }
  227. };
  228. pageSchema.methods.getContentAge = function() {
  229. return differenceInYears(new Date(), this.updatedAt);
  230. };
  231. pageSchema.statics.updateCommentCount = function(pageId) {
  232. validateCrowi();
  233. const self = this;
  234. return Comment.countCommentByPageId(pageId)
  235. .then((count) => {
  236. self.update({ _id: pageId }, { commentCount: count }, {}, (err, data) => {
  237. if (err) {
  238. debug('Update commentCount Error', err);
  239. throw err;
  240. }
  241. return data;
  242. });
  243. });
  244. };
  245. pageSchema.statics.getDeletedPageName = function(path) {
  246. if (path.match('/')) {
  247. // eslint-disable-next-line no-param-reassign
  248. path = path.substr(1);
  249. }
  250. return `/trash/${path}`;
  251. };
  252. pageSchema.statics.getRevertDeletedPageName = function(path) {
  253. return path.replace('/trash', '');
  254. };
  255. pageSchema.statics.fixToCreatableName = function(path) {
  256. return path
  257. .replace(/\/\//g, '/');
  258. };
  259. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  260. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  261. cb(err, data);
  262. });
  263. };
  264. /**
  265. * return whether the user is accessible to the page
  266. * @param {string} id ObjectId
  267. * @param {User} user
  268. */
  269. pageSchema.statics.isAccessiblePageByViewer = async function(id, user) {
  270. const baseQuery = this.count({ _id: id });
  271. const userGroups = user != null ? [
  272. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  273. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  274. ] : [];
  275. const queryBuilder = new this.PageQueryBuilder(baseQuery);
  276. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  277. const count = await queryBuilder.query.exec();
  278. return count > 0;
  279. };
  280. /**
  281. * @param {string} id ObjectId
  282. * @param {User} user User instance
  283. * @param {UserGroup[]} userGroups List of UserGroup instances
  284. */
  285. pageSchema.statics.findByIdAndViewer = async function(id, user, userGroups, includeEmpty = false) {
  286. const baseQuery = this.findOne({ _id: id });
  287. const relatedUserGroups = (user != null && userGroups == null) ? [
  288. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  289. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  290. ] : userGroups;
  291. const queryBuilder = new this.PageQueryBuilder(baseQuery, includeEmpty);
  292. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  293. return queryBuilder.query.exec();
  294. };
  295. // find page by path
  296. pageSchema.statics.findByPath = function(path, includeEmpty = false) {
  297. if (path == null) {
  298. return null;
  299. }
  300. const builder = new this.PageQueryBuilder(this.findOne({ path }), includeEmpty);
  301. return builder.query.exec();
  302. };
  303. /**
  304. * @param {string} path Page path
  305. * @param {User} user User instance
  306. * @param {UserGroup[]} userGroups List of UserGroup instances
  307. */
  308. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups, includeEmpty = false) {
  309. if (path == null) {
  310. throw new Error('path is required.');
  311. }
  312. if (path === '/') {
  313. return null;
  314. }
  315. const ancestorsPaths = extractToAncestorsPaths(path);
  316. // pick the longest one
  317. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  318. const relatedUserGroups = (user != null && userGroups == null) ? [
  319. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  320. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  321. ] : userGroups;
  322. const queryBuilder = new this.PageQueryBuilder(baseQuery, includeEmpty);
  323. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  324. return queryBuilder.query.exec();
  325. };
  326. /**
  327. * find pages that is match with `path` and its descendants
  328. */
  329. pageSchema.statics.findListWithDescendants = async function(path, user, option = {}, includeEmpty = false) {
  330. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  331. builder.addConditionToListWithDescendants(path, option);
  332. return findListFromBuilderAndViewer(builder, user, false, option);
  333. };
  334. /**
  335. * find pages that is match with `path` and its descendants which user is able to manage
  336. */
  337. pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}, includeEmpty = false) {
  338. if (user == null) {
  339. return null;
  340. }
  341. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  342. builder.addConditionToListWithDescendants(page.path, option);
  343. // add grant conditions
  344. await addConditionToFilteringByViewerToEdit(builder, user);
  345. const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
  346. // add page if 'grant' is GRANT_RESTRICTED
  347. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  348. if (page.grant === GRANT_RESTRICTED) {
  349. pages.push(page);
  350. }
  351. return pages;
  352. };
  353. /**
  354. * find pages that start with `path`
  355. */
  356. pageSchema.statics.findListByStartWith = async function(path, user, option, includeEmpty = false) {
  357. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  358. builder.addConditionToListByStartWith(path, option);
  359. return findListFromBuilderAndViewer(builder, user, false, option);
  360. };
  361. /**
  362. * find pages that is created by targetUser
  363. *
  364. * @param {User} targetUser
  365. * @param {User} currentUser
  366. * @param {any} option
  367. */
  368. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  369. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  370. const builder = new this.PageQueryBuilder(this.find({ creator: targetUser._id }));
  371. let showAnyoneKnowsLink = null;
  372. if (targetUser != null && currentUser != null) {
  373. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  374. }
  375. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  376. };
  377. /**
  378. * find pages by PageQueryBuilder
  379. * @param {PageQueryBuilder} builder
  380. * @param {User} user
  381. * @param {boolean} showAnyoneKnowsLink
  382. * @param {any} option
  383. */
  384. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  385. validateCrowi();
  386. const User = crowi.model('User');
  387. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  388. const sortOpt = {};
  389. sortOpt[opt.sort] = opt.desc;
  390. // exclude trashed pages
  391. if (!opt.includeTrashed) {
  392. builder.addConditionToExcludeTrashed();
  393. }
  394. // add grant conditions
  395. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  396. // count
  397. const totalCount = await builder.query.exec('count');
  398. // find
  399. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  400. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  401. const pages = await builder.query.lean().clone().exec('find');
  402. const result = {
  403. pages, totalCount, offset: opt.offset, limit: opt.limit,
  404. };
  405. return result;
  406. }
  407. /**
  408. * Add condition that filter pages by viewer
  409. * by considering Config
  410. *
  411. * @param {PageQueryBuilder} builder
  412. * @param {User} user
  413. * @param {boolean} showAnyoneKnowsLink
  414. */
  415. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  416. validateCrowi();
  417. // determine User condition
  418. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  419. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  420. // determine UserGroup condition
  421. const userGroups = user != null ? [
  422. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  423. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  424. ] : null;
  425. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  426. }
  427. /**
  428. * Add condition that filter pages by viewer
  429. * by considering Config
  430. *
  431. * @param {PageQueryBuilder} builder
  432. * @param {User} user
  433. * @param {boolean} showAnyoneKnowsLink
  434. */
  435. async function addConditionToFilteringByViewerToEdit(builder, user) {
  436. // determine UserGroup condition
  437. const userGroups = user != null ? [
  438. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  439. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  440. ] : null;
  441. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  442. }
  443. /**
  444. * export addConditionToFilteringByViewerForList as static method
  445. */
  446. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  447. /**
  448. * export addConditionToFilteringByViewerToEdit as static method
  449. */
  450. pageSchema.statics.addConditionToFilteringByViewerToEdit = addConditionToFilteringByViewerToEdit;
  451. /**
  452. * Throw error for growi-lsx-plugin (v1.x)
  453. */
  454. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  455. const dummyQuery = this.find();
  456. dummyQuery.exec = async() => {
  457. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  458. };
  459. return dummyQuery;
  460. };
  461. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  462. /**
  463. * find all templates applicable to the new page
  464. */
  465. pageSchema.statics.findTemplate = async function(path) {
  466. const templatePath = nodePath.posix.dirname(path);
  467. const pathList = generatePathsOnTree(path, []);
  468. const regexpList = pathList.map((path) => {
  469. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  470. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  471. });
  472. const templatePages = await this.find({ path: { $in: regexpList } })
  473. .populate({ path: 'revision', model: 'Revision' })
  474. .exec();
  475. return fetchTemplate(templatePages, templatePath);
  476. };
  477. const generatePathsOnTree = (path, pathList) => {
  478. pathList.push(path);
  479. if (path === '/') {
  480. return pathList;
  481. }
  482. const newPath = nodePath.posix.dirname(path);
  483. return generatePathsOnTree(newPath, pathList);
  484. };
  485. const assignTemplateByType = (templates, path, type) => {
  486. const targetTemplatePath = urljoin(path, `${type}template`);
  487. return templates.find((template) => {
  488. return (template.path === targetTemplatePath);
  489. });
  490. };
  491. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  492. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  493. if (decendantsTemplate) {
  494. return decendantsTemplate;
  495. }
  496. if (path === '/') {
  497. return;
  498. }
  499. const newPath = nodePath.posix.dirname(path);
  500. return assignDecendantsTemplate(decendantsTemplates, newPath);
  501. };
  502. const fetchTemplate = async(templates, templatePath) => {
  503. let templateBody;
  504. let templateTags;
  505. /**
  506. * get children template
  507. * __tempate: applicable only to immediate decendants
  508. */
  509. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  510. /**
  511. * get decendants templates
  512. * _tempate: applicable to all pages under
  513. */
  514. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  515. if (childrenTemplate) {
  516. templateBody = childrenTemplate.revision.body;
  517. templateTags = await childrenTemplate.findRelatedTagsById();
  518. }
  519. else if (decendantsTemplate) {
  520. templateBody = decendantsTemplate.revision.body;
  521. templateTags = await decendantsTemplate.findRelatedTagsById();
  522. }
  523. return { templateBody, templateTags };
  524. };
  525. pageSchema.statics.findListByPathsArray = async function(paths, includeEmpty = false) {
  526. const queryBuilder = new this.PageQueryBuilder(this.find(), includeEmpty);
  527. queryBuilder.addConditionToListByPathsArray(paths);
  528. return await queryBuilder.query.exec();
  529. };
  530. /**
  531. * transfer pages grant to specified user group
  532. * @param {Page[]} pages
  533. * @param {IGrantedGroup} transferToUserGroup
  534. */
  535. pageSchema.statics.transferPagesToGroup = async function(pages, transferToUserGroup) {
  536. const userGroupModel = transferToUserGroup.type === GroupType.userGroup ? UserGroup : ExternalUserGroup;
  537. if ((await userGroupModel.count({ _id: transferToUserGroup.item })) === 0) {
  538. throw Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroup.item);
  539. }
  540. await this.updateMany({ _id: { $in: pages.map(p => p._id) } }, { grantedGroups: [transferToUserGroup] });
  541. };
  542. pageSchema.methods.getNotificationTargetUsers = async function() {
  543. const Revision = mongoose.model('Revision');
  544. const [commentCreators, revisionAuthors] = await Promise.all([Comment.findCreatorsByPage(this), Revision.findAuthorsByPage(this)]);
  545. const targetUsers = new Set([this.creator].concat(commentCreators, revisionAuthors));
  546. return Array.from(targetUsers);
  547. };
  548. pageSchema.statics.getHistories = function() {
  549. // TODO
  550. };
  551. pageSchema.statics.STATUS_PUBLISHED = STATUS_PUBLISHED;
  552. pageSchema.statics.STATUS_DELETED = STATUS_DELETED;
  553. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  554. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  555. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  556. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  557. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  558. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  559. return pageSchema;
  560. };