2
0

obsolete-page.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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 loggerFactory from '~/utils/logger';
  5. // disable no-return-await for model functions
  6. /* eslint-disable no-return-await */
  7. /* eslint-disable no-use-before-define */
  8. const debug = require('debug')('growi:models:page');
  9. const nodePath = require('path');
  10. const differenceInYears = require('date-fns/differenceInYears');
  11. const mongoose = require('mongoose');
  12. const urljoin = require('url-join');
  13. const { isTopPage, isTrashPage } = pagePathUtils;
  14. const { checkTemplatePath } = templateChecker;
  15. const logger = loggerFactory('growi:models:page');
  16. const GRANT_PUBLIC = 1;
  17. const GRANT_RESTRICTED = 2;
  18. const GRANT_SPECIFIED = 3;
  19. const GRANT_OWNER = 4;
  20. const GRANT_USER_GROUP = 5;
  21. const PAGE_GRANT_ERROR = 1;
  22. const STATUS_PUBLISHED = 'published';
  23. const STATUS_DELETED = 'deleted';
  24. // schema definition has moved to page.ts
  25. const pageSchema = {
  26. statics: {},
  27. methods: {},
  28. };
  29. /**
  30. * return an array of ancestors paths that is extracted from specified pagePath
  31. * e.g.
  32. * when `pagePath` is `/foo/bar/baz`,
  33. * this method returns [`/foo/bar/baz`, `/foo/bar`, `/foo`, `/`]
  34. *
  35. * @param {string} pagePath
  36. * @return {string[]} ancestors paths
  37. */
  38. export const extractToAncestorsPaths = (pagePath) => {
  39. const ancestorsPaths = [];
  40. let parentPath;
  41. while (parentPath !== '/') {
  42. parentPath = nodePath.dirname(parentPath || pagePath);
  43. ancestorsPaths.push(parentPath);
  44. }
  45. return ancestorsPaths;
  46. };
  47. /**
  48. * populate page (Query or Document) to show revision
  49. * @param {any} page Query or Document
  50. * @param {string} userPublicFields string to set to select
  51. * @param {boolean} shouldExcludeBody boolean indicating whether to include 'revision.body' or not
  52. */
  53. /* eslint-disable object-curly-newline, object-property-newline */
  54. export const populateDataToShowRevision = (page, userPublicFields, shouldExcludeBody = false) => {
  55. return page
  56. .populate([
  57. { path: 'lastUpdateUser', model: 'User', select: userPublicFields },
  58. { path: 'creator', model: 'User', select: userPublicFields },
  59. { path: 'deleteUser', model: 'User', select: userPublicFields },
  60. { path: 'grantedGroup', model: 'UserGroup' },
  61. { path: 'revision', model: 'Revision', select: shouldExcludeBody ? '-body' : undefined, populate: {
  62. path: 'author', model: 'User', select: userPublicFields,
  63. } },
  64. ]);
  65. };
  66. /* eslint-enable object-curly-newline, object-property-newline */
  67. export const getPageSchema = (crowi) => {
  68. let pageEvent;
  69. // init event
  70. if (crowi != null) {
  71. pageEvent = crowi.event('page');
  72. pageEvent.on('create', pageEvent.onCreate);
  73. pageEvent.on('update', pageEvent.onUpdate);
  74. pageEvent.on('createMany', pageEvent.onCreateMany);
  75. pageEvent.on('addSeenUsers', pageEvent.onAddSeenUsers);
  76. }
  77. function validateCrowi() {
  78. if (crowi == null) {
  79. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  80. }
  81. }
  82. pageSchema.methods.isDeleted = function() {
  83. return isTrashPage(this.path);
  84. };
  85. pageSchema.methods.isPublic = function() {
  86. if (!this.grant || this.grant === GRANT_PUBLIC) {
  87. return true;
  88. }
  89. return false;
  90. };
  91. pageSchema.methods.isTopPage = function() {
  92. return isTopPage(this.path);
  93. };
  94. pageSchema.methods.isTemplate = function() {
  95. return checkTemplatePath(this.path);
  96. };
  97. pageSchema.methods.isLatestRevision = function() {
  98. // populate されていなくて判断できない
  99. if (!this.latestRevision || !this.revision) {
  100. return true;
  101. }
  102. // comparing ObjectId with string
  103. // eslint-disable-next-line eqeqeq
  104. return (this.latestRevision == this.revision._id.toString());
  105. };
  106. pageSchema.methods.findRelatedTagsById = async function() {
  107. const PageTagRelation = mongoose.model('PageTagRelation');
  108. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  109. return relations.map((relation) => { return relation.relatedTag.name });
  110. };
  111. pageSchema.methods.isUpdatable = function(previousRevision) {
  112. const revision = this.latestRevision || this.revision;
  113. // comparing ObjectId with string
  114. // eslint-disable-next-line eqeqeq
  115. if (revision != previousRevision) {
  116. return false;
  117. }
  118. return true;
  119. };
  120. pageSchema.methods.isLiked = function(user) {
  121. if (user == null || user._id == null) {
  122. return false;
  123. }
  124. return this.liker.some((likedUserId) => {
  125. return likedUserId.toString() === user._id.toString();
  126. });
  127. };
  128. pageSchema.methods.like = function(userData) {
  129. const self = this;
  130. return new Promise(((resolve, reject) => {
  131. const added = self.liker.addToSet(userData._id);
  132. if (added.length > 0) {
  133. self.save((err, data) => {
  134. if (err) {
  135. return reject(err);
  136. }
  137. logger.debug('liker updated!', added);
  138. return resolve(data);
  139. });
  140. }
  141. else {
  142. logger.debug('liker not updated');
  143. return reject(new Error('Already liked'));
  144. }
  145. }));
  146. };
  147. pageSchema.methods.unlike = function(userData, callback) {
  148. const self = this;
  149. return new Promise(((resolve, reject) => {
  150. const beforeCount = self.liker.length;
  151. self.liker.pull(userData._id);
  152. if (self.liker.length !== beforeCount) {
  153. self.save((err, data) => {
  154. if (err) {
  155. return reject(err);
  156. }
  157. return resolve(data);
  158. });
  159. }
  160. else {
  161. logger.debug('liker not updated');
  162. return reject(new Error('Already unliked'));
  163. }
  164. }));
  165. };
  166. pageSchema.methods.isSeenUser = function(userData) {
  167. return this.seenUsers.includes(userData._id);
  168. };
  169. pageSchema.methods.seen = async function(userData) {
  170. if (this.isSeenUser(userData)) {
  171. debug('seenUsers not updated');
  172. return this;
  173. }
  174. if (!userData || !userData._id) {
  175. throw new Error('User data is not valid');
  176. }
  177. const added = this.seenUsers.addToSet(userData._id);
  178. const saved = await this.save();
  179. debug('seenUsers updated!', added);
  180. pageEvent.emit('addSeenUsers', saved);
  181. return saved;
  182. };
  183. pageSchema.methods.updateSlackChannels = function(slackChannels) {
  184. this.slackChannels = slackChannels;
  185. return this.save();
  186. };
  187. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  188. this.latestRevision = this.revision;
  189. if (revisionId != null) {
  190. this.revision = revisionId;
  191. }
  192. };
  193. pageSchema.methods.populateDataToShowRevision = async function(shouldExcludeBody) {
  194. validateCrowi();
  195. const User = crowi.model('User');
  196. return populateDataToShowRevision(this, User.USER_FIELDS_EXCEPT_CONFIDENTIAL, shouldExcludeBody);
  197. };
  198. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  199. this.latestRevision = this.revision;
  200. if (revisionId != null) {
  201. this.revision = revisionId;
  202. }
  203. return this.populate('revision');
  204. };
  205. pageSchema.methods.applyScope = function(user, grant, grantUserGroupId) {
  206. // Reset
  207. this.grantedUsers = [];
  208. this.grantedGroup = null;
  209. this.grant = grant || GRANT_PUBLIC;
  210. if (grant === GRANT_OWNER) {
  211. this.grantedUsers.push(user?._id ?? user);
  212. }
  213. if (grant === GRANT_USER_GROUP) {
  214. this.grantedGroup = grantUserGroupId;
  215. }
  216. };
  217. pageSchema.methods.getContentAge = function() {
  218. return differenceInYears(new Date(), this.updatedAt);
  219. };
  220. pageSchema.statics.updateCommentCount = function(pageId) {
  221. validateCrowi();
  222. const self = this;
  223. const Comment = crowi.model('Comment');
  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. /**
  569. * associate GROWI page and HackMD page
  570. * @param {Page} pageData
  571. * @param {string} pageIdOnHackmd
  572. */
  573. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  574. pageData.pageIdOnHackmd = pageIdOnHackmd;
  575. return this.syncRevisionToHackmd(pageData);
  576. };
  577. /**
  578. * update revisionHackmdSynced
  579. * @param {Page} pageData
  580. * @param {bool} isSave whether save or not
  581. */
  582. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  583. pageData.revisionHackmdSynced = pageData.revision;
  584. pageData.hasDraftOnHackmd = false;
  585. let returnData = pageData;
  586. if (isSave) {
  587. returnData = pageData.save();
  588. }
  589. return returnData;
  590. };
  591. /**
  592. * update hasDraftOnHackmd
  593. * !! This will be invoked many time from many people !!
  594. *
  595. * @param {Page} pageData
  596. * @param {Boolean} newValue
  597. */
  598. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  599. if (pageData.hasDraftOnHackmd === newValue) {
  600. // do nothing when hasDraftOnHackmd equals to newValue
  601. return;
  602. }
  603. pageData.hasDraftOnHackmd = newValue;
  604. return pageData.save();
  605. };
  606. pageSchema.methods.getNotificationTargetUsers = async function() {
  607. const Comment = mongoose.model('Comment');
  608. const Revision = mongoose.model('Revision');
  609. const [commentCreators, revisionAuthors] = await Promise.all([Comment.findCreatorsByPage(this), Revision.findAuthorsByPage(this)]);
  610. const targetUsers = new Set([this.creator].concat(commentCreators, revisionAuthors));
  611. return Array.from(targetUsers);
  612. };
  613. pageSchema.statics.getHistories = function() {
  614. // TODO
  615. };
  616. pageSchema.statics.STATUS_PUBLISHED = STATUS_PUBLISHED;
  617. pageSchema.statics.STATUS_DELETED = STATUS_DELETED;
  618. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  619. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  620. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  621. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  622. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  623. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  624. return pageSchema;
  625. };