obsolete-page.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. import { templateChecker, pagePathUtils, pathUtils } from '@growi/core';
  2. import escapeStringRegexp from 'escape-string-regexp';
  3. import { PageGrant } from '~/interfaces/page';
  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.getUserPagePath = function(user) {
  236. return `/user/${user.username}`;
  237. };
  238. pageSchema.statics.getDeletedPageName = function(path) {
  239. if (path.match('/')) {
  240. // eslint-disable-next-line no-param-reassign
  241. path = path.substr(1);
  242. }
  243. return `/trash/${path}`;
  244. };
  245. pageSchema.statics.getRevertDeletedPageName = function(path) {
  246. return path.replace('/trash', '');
  247. };
  248. pageSchema.statics.fixToCreatableName = function(path) {
  249. return path
  250. .replace(/\/\//g, '/');
  251. };
  252. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  253. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  254. cb(err, data);
  255. });
  256. };
  257. /**
  258. * return whether the user is accessible to the page
  259. * @param {string} id ObjectId
  260. * @param {User} user
  261. */
  262. pageSchema.statics.isAccessiblePageByViewer = async function(id, user) {
  263. const baseQuery = this.count({ _id: id });
  264. let userGroups = [];
  265. if (user != null) {
  266. validateCrowi();
  267. const UserGroupRelation = crowi.model('UserGroupRelation');
  268. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  269. }
  270. const queryBuilder = new this.PageQueryBuilder(baseQuery);
  271. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  272. const count = await queryBuilder.query.exec();
  273. return count > 0;
  274. };
  275. /**
  276. * @param {string} id ObjectId
  277. * @param {User} user User instance
  278. * @param {UserGroup[]} userGroups List of UserGroup instances
  279. */
  280. pageSchema.statics.findByIdAndViewer = async function(id, user, userGroups, includeEmpty = false) {
  281. const baseQuery = this.findOne({ _id: id });
  282. let relatedUserGroups = userGroups;
  283. if (user != null && relatedUserGroups == null) {
  284. validateCrowi();
  285. const UserGroupRelation = crowi.model('UserGroupRelation');
  286. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  287. }
  288. const queryBuilder = new this.PageQueryBuilder(baseQuery, includeEmpty);
  289. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  290. return queryBuilder.query.exec();
  291. };
  292. // find page by path
  293. pageSchema.statics.findByPath = function(path, includeEmpty = false) {
  294. if (path == null) {
  295. return null;
  296. }
  297. const builder = new this.PageQueryBuilder(this.findOne({ path }), includeEmpty);
  298. return builder.query.exec();
  299. };
  300. /**
  301. * @param {string} path Page path
  302. * @param {User} user User instance
  303. * @param {UserGroup[]} userGroups List of UserGroup instances
  304. */
  305. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups, includeEmpty = false) {
  306. if (path == null) {
  307. throw new Error('path is required.');
  308. }
  309. if (path === '/') {
  310. return null;
  311. }
  312. const ancestorsPaths = extractToAncestorsPaths(path);
  313. // pick the longest one
  314. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  315. let relatedUserGroups = userGroups;
  316. if (user != null && relatedUserGroups == null) {
  317. validateCrowi();
  318. const UserGroupRelation = crowi.model('UserGroupRelation');
  319. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  320. }
  321. const queryBuilder = new this.PageQueryBuilder(baseQuery, includeEmpty);
  322. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  323. return queryBuilder.query.exec();
  324. };
  325. /**
  326. * find pages that is match with `path` and its descendants
  327. */
  328. pageSchema.statics.findListWithDescendants = async function(path, user, option = {}, includeEmpty = false) {
  329. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  330. builder.addConditionToListWithDescendants(path, option);
  331. return findListFromBuilderAndViewer(builder, user, false, option);
  332. };
  333. /**
  334. * find pages that is match with `path` and its descendants which user is able to manage
  335. */
  336. pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}, includeEmpty = false) {
  337. if (user == null) {
  338. return null;
  339. }
  340. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  341. builder.addConditionToListWithDescendants(page.path, option);
  342. // add grant conditions
  343. await addConditionToFilteringByViewerToEdit(builder, user);
  344. const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
  345. // add page if 'grant' is GRANT_RESTRICTED
  346. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  347. if (page.grant === GRANT_RESTRICTED) {
  348. pages.push(page);
  349. }
  350. return pages;
  351. };
  352. /**
  353. * find pages that start with `path`
  354. */
  355. pageSchema.statics.findListByStartWith = async function(path, user, option, includeEmpty = false) {
  356. const builder = new this.PageQueryBuilder(this.find(), includeEmpty);
  357. builder.addConditionToListByStartWith(path, option);
  358. return findListFromBuilderAndViewer(builder, user, false, option);
  359. };
  360. /**
  361. * find pages that is created by targetUser
  362. *
  363. * @param {User} targetUser
  364. * @param {User} currentUser
  365. * @param {any} option
  366. */
  367. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  368. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  369. const builder = new this.PageQueryBuilder(this.find({ creator: targetUser._id }));
  370. let showAnyoneKnowsLink = null;
  371. if (targetUser != null && currentUser != null) {
  372. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  373. }
  374. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  375. };
  376. /**
  377. * find pages by PageQueryBuilder
  378. * @param {PageQueryBuilder} builder
  379. * @param {User} user
  380. * @param {boolean} showAnyoneKnowsLink
  381. * @param {any} option
  382. */
  383. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  384. validateCrowi();
  385. const User = crowi.model('User');
  386. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  387. const sortOpt = {};
  388. sortOpt[opt.sort] = opt.desc;
  389. // exclude trashed pages
  390. if (!opt.includeTrashed) {
  391. builder.addConditionToExcludeTrashed();
  392. }
  393. // add grant conditions
  394. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  395. // count
  396. const totalCount = await builder.query.exec('count');
  397. // find
  398. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  399. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  400. const pages = await builder.query.lean().clone().exec('find');
  401. const result = {
  402. pages, totalCount, offset: opt.offset, limit: opt.limit,
  403. };
  404. return result;
  405. }
  406. /**
  407. * Add condition that filter pages by viewer
  408. * by considering Config
  409. *
  410. * @param {PageQueryBuilder} builder
  411. * @param {User} user
  412. * @param {boolean} showAnyoneKnowsLink
  413. */
  414. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  415. validateCrowi();
  416. // determine User condition
  417. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  418. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  419. // determine UserGroup condition
  420. let userGroups = null;
  421. if (user != null) {
  422. const UserGroupRelation = crowi.model('UserGroupRelation');
  423. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  424. }
  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. validateCrowi();
  437. // determine UserGroup condition
  438. let userGroups = null;
  439. if (user != null) {
  440. const UserGroupRelation = crowi.model('UserGroupRelation');
  441. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  442. }
  443. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  444. }
  445. /**
  446. * export addConditionToFilteringByViewerForList as static method
  447. */
  448. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  449. /**
  450. * export addConditionToFilteringByViewerToEdit as static method
  451. */
  452. pageSchema.statics.addConditionToFilteringByViewerToEdit = addConditionToFilteringByViewerToEdit;
  453. /**
  454. * Throw error for growi-lsx-plugin (v1.x)
  455. */
  456. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  457. const dummyQuery = this.find();
  458. dummyQuery.exec = async() => {
  459. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  460. };
  461. return dummyQuery;
  462. };
  463. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  464. /**
  465. * find all templates applicable to the new page
  466. */
  467. pageSchema.statics.findTemplate = async function(path) {
  468. const templatePath = nodePath.posix.dirname(path);
  469. const pathList = generatePathsOnTree(path, []);
  470. const regexpList = pathList.map((path) => {
  471. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  472. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  473. });
  474. const templatePages = await this.find({ path: { $in: regexpList } })
  475. .populate({ path: 'revision', model: 'Revision' })
  476. .exec();
  477. return fetchTemplate(templatePages, templatePath);
  478. };
  479. const generatePathsOnTree = (path, pathList) => {
  480. pathList.push(path);
  481. if (path === '/') {
  482. return pathList;
  483. }
  484. const newPath = nodePath.posix.dirname(path);
  485. return generatePathsOnTree(newPath, pathList);
  486. };
  487. const assignTemplateByType = (templates, path, type) => {
  488. const targetTemplatePath = urljoin(path, `${type}template`);
  489. return templates.find((template) => {
  490. return (template.path === targetTemplatePath);
  491. });
  492. };
  493. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  494. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  495. if (decendantsTemplate) {
  496. return decendantsTemplate;
  497. }
  498. if (path === '/') {
  499. return;
  500. }
  501. const newPath = nodePath.posix.dirname(path);
  502. return assignDecendantsTemplate(decendantsTemplates, newPath);
  503. };
  504. const fetchTemplate = async(templates, templatePath) => {
  505. let templateBody;
  506. let templateTags;
  507. /**
  508. * get children template
  509. * __tempate: applicable only to immediate decendants
  510. */
  511. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  512. /**
  513. * get decendants templates
  514. * _tempate: applicable to all pages under
  515. */
  516. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  517. if (childrenTemplate) {
  518. templateBody = childrenTemplate.revision.body;
  519. templateTags = await childrenTemplate.findRelatedTagsById();
  520. }
  521. else if (decendantsTemplate) {
  522. templateBody = decendantsTemplate.revision.body;
  523. templateTags = await decendantsTemplate.findRelatedTagsById();
  524. }
  525. return { templateBody, templateTags };
  526. };
  527. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user, isV4 = false) {
  528. const builder = new this.PageQueryBuilder(this.find());
  529. builder.addConditionToListOnlyDescendants(parentPage.path);
  530. if (isV4) {
  531. builder.addConditionAsRootOrNotOnTree();
  532. }
  533. else {
  534. builder.addConditionAsOnTree();
  535. }
  536. // add grant conditions
  537. await addConditionToFilteringByViewerToEdit(builder, user);
  538. const grant = parentPage.grant;
  539. await builder.query.updateMany({}, {
  540. grant,
  541. grantedGroup: grant === PageGrant.GRANT_USER_GROUP ? parentPage.grantedGroup : null,
  542. grantedUsers: grant === PageGrant.GRANT_OWNER ? [user._id] : null,
  543. });
  544. };
  545. pageSchema.statics.removeByPath = function(path) {
  546. if (path == null) {
  547. throw new Error('path is required');
  548. }
  549. return this.findOneAndRemove({ path }).exec();
  550. };
  551. pageSchema.statics.findListByPathsArray = async function(paths, includeEmpty = false) {
  552. const queryBuilder = new this.PageQueryBuilder(this.find(), includeEmpty);
  553. queryBuilder.addConditionToListByPathsArray(paths);
  554. return await queryBuilder.query.exec();
  555. };
  556. pageSchema.statics.publicizePages = async function(pages) {
  557. const operationsToPublicize = pages.map((page) => {
  558. return {
  559. updateOne: {
  560. filter: { _id: page._id },
  561. update: {
  562. grantedGroup: null,
  563. grant: this.GRANT_PUBLIC,
  564. },
  565. },
  566. };
  567. });
  568. await this.bulkWrite(operationsToPublicize);
  569. };
  570. pageSchema.statics.transferPagesToGroup = async function(pages, transferToUserGroupId) {
  571. const UserGroup = mongoose.model('UserGroup');
  572. if ((await UserGroup.count({ _id: transferToUserGroupId })) === 0) {
  573. throw Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  574. }
  575. await this.updateMany({ _id: { $in: pages.map(p => p._id) } }, { grantedGroup: transferToUserGroupId });
  576. };
  577. /**
  578. * associate GROWI page and HackMD page
  579. * @param {Page} pageData
  580. * @param {string} pageIdOnHackmd
  581. */
  582. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  583. pageData.pageIdOnHackmd = pageIdOnHackmd;
  584. return this.syncRevisionToHackmd(pageData);
  585. };
  586. /**
  587. * update revisionHackmdSynced
  588. * @param {Page} pageData
  589. * @param {bool} isSave whether save or not
  590. */
  591. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  592. pageData.revisionHackmdSynced = pageData.revision;
  593. pageData.hasDraftOnHackmd = false;
  594. let returnData = pageData;
  595. if (isSave) {
  596. returnData = pageData.save();
  597. }
  598. return returnData;
  599. };
  600. /**
  601. * update hasDraftOnHackmd
  602. * !! This will be invoked many time from many people !!
  603. *
  604. * @param {Page} pageData
  605. * @param {Boolean} newValue
  606. */
  607. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  608. if (pageData.hasDraftOnHackmd === newValue) {
  609. // do nothing when hasDraftOnHackmd equals to newValue
  610. return;
  611. }
  612. pageData.hasDraftOnHackmd = newValue;
  613. return pageData.save();
  614. };
  615. pageSchema.methods.getNotificationTargetUsers = async function() {
  616. const Comment = mongoose.model('Comment');
  617. const Revision = mongoose.model('Revision');
  618. const [commentCreators, revisionAuthors] = await Promise.all([Comment.findCreatorsByPage(this), Revision.findAuthorsByPage(this)]);
  619. const targetUsers = new Set([this.creator].concat(commentCreators, revisionAuthors));
  620. return Array.from(targetUsers);
  621. };
  622. pageSchema.statics.getHistories = function() {
  623. // TODO
  624. };
  625. pageSchema.statics.STATUS_PUBLISHED = STATUS_PUBLISHED;
  626. pageSchema.statics.STATUS_DELETED = STATUS_DELETED;
  627. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  628. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  629. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  630. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  631. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  632. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  633. return pageSchema;
  634. };