obsolete-page.js 22 KB

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