page.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import { pagePathUtils } from '@growi/core';
  2. import isThisHour from 'date-fns/isThisHour/index.js';
  3. import loggerFactory from '~/utils/logger';
  4. import ActivityDefine from '../util/activityDefine';
  5. const mongoose = require('mongoose');
  6. const escapeStringRegexp = require('escape-string-regexp');
  7. const streamToPromise = require('stream-to-promise');
  8. const logger = loggerFactory('growi:service:page');
  9. const debug = require('debug')('growi:service:page');
  10. const { Writable } = require('stream');
  11. const { createBatchStream } = require('~/server/util/batch-stream');
  12. const { isTrashPage } = pagePathUtils;
  13. const { serializePageSecurely } = require('../models/serializers/page-serializer');
  14. const BULK_REINDEX_SIZE = 100;
  15. class PageService {
  16. constructor(crowi) {
  17. this.crowi = crowi;
  18. this.pageEvent = crowi.event('page');
  19. // init
  20. this.initPageEvent();
  21. }
  22. initPageEvent() {
  23. // create
  24. this.pageEvent.on('create', this.pageEvent.onCreate);
  25. // createMany
  26. this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
  27. // update
  28. this.pageEvent.on('update', async(page, user) => {
  29. this.pageEvent.onUpdate();
  30. try {
  31. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_UPDATE);
  32. }
  33. catch (err) {
  34. logger.error(err);
  35. }
  36. });
  37. // rename
  38. this.pageEvent.on('rename', async(page, user) => {
  39. try {
  40. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_RENAME);
  41. }
  42. catch (err) {
  43. logger.error(err);
  44. }
  45. });
  46. // delete
  47. this.pageEvent.on('delete', async(page, user) => {
  48. try {
  49. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_DELETE);
  50. }
  51. catch (err) {
  52. logger.error(err);
  53. }
  54. });
  55. // likes
  56. this.pageEvent.on('likes', async(page, user) => {
  57. try {
  58. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_LIKE);
  59. }
  60. catch (err) {
  61. logger.error(err);
  62. }
  63. });
  64. // bookmark
  65. this.pageEvent.on('bookmark', async(page, user) => {
  66. try {
  67. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_BOOKMARK);
  68. }
  69. catch (err) {
  70. logger.error(err);
  71. }
  72. });
  73. }
  74. /**
  75. * go back by using redirectTo and return the paths
  76. * ex: when
  77. * '/page1' redirects to '/page2' and
  78. * '/page2' redirects to '/page3'
  79. * and given '/page3',
  80. * '/page1' and '/page2' will be return
  81. *
  82. * @param {string} redirectTo
  83. * @param {object} redirectToPagePathMapping
  84. * @param {array} pagePaths
  85. */
  86. prepareShoudDeletePagesByRedirectTo(redirectTo, redirectToPagePathMapping, pagePaths = []) {
  87. const pagePath = redirectToPagePathMapping[redirectTo];
  88. if (pagePath == null) {
  89. return pagePaths;
  90. }
  91. pagePaths.push(pagePath);
  92. return this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping, pagePaths);
  93. }
  94. /**
  95. * Generate read stream to operate descendants of the specified page path
  96. * @param {string} targetPagePath
  97. * @param {User} viewer
  98. */
  99. async generateReadStreamToOperateOnlyDescendants(targetPagePath, userToOperate) {
  100. const Page = this.crowi.model('Page');
  101. const { PageQueryBuilder } = Page;
  102. const builder = new PageQueryBuilder(Page.find())
  103. .addConditionToExcludeRedirect()
  104. .addConditionToListOnlyDescendants(targetPagePath);
  105. await Page.addConditionToFilteringByViewerToEdit(builder, userToOperate);
  106. return builder
  107. .query
  108. .lean()
  109. .cursor({ batchSize: BULK_REINDEX_SIZE });
  110. }
  111. async renamePage(page, newPagePath, user, options, isRecursively = false) {
  112. const Page = this.crowi.model('Page');
  113. const Revision = this.crowi.model('Revision');
  114. const path = page.path;
  115. const createRedirectPage = options.createRedirectPage || false;
  116. const updateMetadata = options.updateMetadata || false;
  117. // sanitize path
  118. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  119. // create descendants first
  120. if (isRecursively) {
  121. await this.renameDescendantsWithStream(page, newPagePath, user, options);
  122. }
  123. const update = {};
  124. // update Page
  125. update.path = newPagePath;
  126. if (updateMetadata) {
  127. update.lastUpdateUser = user;
  128. update.updatedAt = Date.now();
  129. }
  130. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  131. // update Rivisions
  132. await Revision.updateRevisionListByPath(path, { path: newPagePath }, {});
  133. if (createRedirectPage) {
  134. const body = `redirect ${newPagePath}`;
  135. await Page.create(path, body, user, { redirectTo: newPagePath });
  136. }
  137. this.pageEvent.emit('rename', page, user);
  138. return renamedPage;
  139. }
  140. async renameDescendants(pages, user, options, oldPagePathPrefix, newPagePathPrefix) {
  141. const Page = this.crowi.model('Page');
  142. const pageCollection = mongoose.connection.collection('pages');
  143. const revisionCollection = mongoose.connection.collection('revisions');
  144. const { updateMetadata, createRedirectPage } = options;
  145. const unorderedBulkOp = pageCollection.initializeUnorderedBulkOp();
  146. const createRediectPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  147. const revisionUnorderedBulkOp = revisionCollection.initializeUnorderedBulkOp();
  148. const createRediectRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  149. pages.forEach((page) => {
  150. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  151. const revisionId = new mongoose.Types.ObjectId();
  152. if (updateMetadata) {
  153. unorderedBulkOp
  154. .find({ _id: page._id })
  155. .update({ $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() } });
  156. }
  157. else {
  158. unorderedBulkOp.find({ _id: page._id }).update({ $set: { path: newPagePath } });
  159. }
  160. if (createRedirectPage) {
  161. createRediectPageBulkOp.insert({
  162. path: page.path, revision: revisionId, creator: user._id, lastUpdateUser: user._id, status: Page.STATUS_PUBLISHED, redirectTo: newPagePath,
  163. });
  164. createRediectRevisionBulkOp.insert({
  165. _id: revisionId, path: page.path, body: `redirect ${newPagePath}`, author: user._id, format: 'markdown',
  166. });
  167. }
  168. revisionUnorderedBulkOp.find({ path: page.path }).update({ $set: { path: newPagePath } }, { multi: true });
  169. });
  170. try {
  171. await unorderedBulkOp.execute();
  172. await revisionUnorderedBulkOp.execute();
  173. // Execute after unorderedBulkOp to prevent duplication
  174. if (createRedirectPage) {
  175. await createRediectPageBulkOp.execute();
  176. await createRediectRevisionBulkOp.execute();
  177. }
  178. }
  179. catch (err) {
  180. if (err.code !== 11000) {
  181. throw new Error('Failed to rename pages: ', err);
  182. }
  183. }
  184. this.pageEvent.emit('updateMany', pages, user);
  185. }
  186. /**
  187. * Create rename stream
  188. */
  189. async renameDescendantsWithStream(targetPage, newPagePath, user, options = {}) {
  190. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  191. const newPagePathPrefix = newPagePath;
  192. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  193. const renameDescendants = this.renameDescendants.bind(this);
  194. const pageEvent = this.pageEvent;
  195. let count = 0;
  196. const writeStream = new Writable({
  197. objectMode: true,
  198. async write(batch, encoding, callback) {
  199. try {
  200. count += batch.length;
  201. await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
  202. logger.debug(`Reverting pages progressing: (count=${count})`);
  203. }
  204. catch (err) {
  205. logger.error('revertPages error on add anyway: ', err);
  206. }
  207. callback();
  208. },
  209. final(callback) {
  210. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  211. // update path
  212. targetPage.path = newPagePath;
  213. pageEvent.emit('syncDescendants', targetPage, user);
  214. callback();
  215. },
  216. });
  217. readStream
  218. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  219. .pipe(writeStream);
  220. await streamToPromise(readStream);
  221. }
  222. async deleteCompletelyOperation(pageIds, pagePaths) {
  223. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  224. const Bookmark = this.crowi.model('Bookmark');
  225. const Comment = this.crowi.model('Comment');
  226. const Page = this.crowi.model('Page');
  227. const PageTagRelation = this.crowi.model('PageTagRelation');
  228. const ShareLink = this.crowi.model('ShareLink');
  229. const Revision = this.crowi.model('Revision');
  230. const Attachment = this.crowi.model('Attachment');
  231. const { attachmentService } = this.crowi;
  232. const attachments = await Attachment.find({ page: { $in: pageIds } });
  233. const pages = await Page.find({ redirectTo: { $ne: null } });
  234. const redirectToPagePathMapping = {};
  235. pages.forEach((page) => {
  236. redirectToPagePathMapping[page.redirectTo] = page.path;
  237. });
  238. const redirectedFromPagePaths = [];
  239. pagePaths.forEach((pagePath) => {
  240. redirectedFromPagePaths.push(...this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping));
  241. });
  242. return Promise.all([
  243. Bookmark.deleteMany({ page: { $in: pageIds } }),
  244. Comment.deleteMany({ page: { $in: pageIds } }),
  245. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  246. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  247. Revision.deleteMany({ path: { $in: pagePaths } }),
  248. Page.deleteMany({ $or: [{ path: { $in: pagePaths } }, { path: { $in: redirectedFromPagePaths } }, { _id: { $in: pageIds } }] }),
  249. attachmentService.removeAllAttachments(attachments),
  250. ]);
  251. }
  252. async duplicate(page, newPagePath, user, isRecursively) {
  253. const Page = this.crowi.model('Page');
  254. const PageTagRelation = mongoose.model('PageTagRelation');
  255. // populate
  256. await page.populate({ path: 'revision', model: 'Revision', select: 'body' }).execPopulate();
  257. // create option
  258. const options = { page };
  259. options.grant = page.grant;
  260. options.grantUserGroupId = page.grantedGroup;
  261. options.grantedUsers = page.grantedUsers;
  262. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  263. const createdPage = await Page.create(
  264. newPagePath, page.revision.body, user, options,
  265. );
  266. if (isRecursively) {
  267. this.duplicateDescendantsWithStream(page, newPagePath, user);
  268. }
  269. // take over tags
  270. const originTags = await page.findRelatedTagsById();
  271. let savedTags = [];
  272. if (originTags != null) {
  273. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  274. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  275. }
  276. const result = serializePageSecurely(createdPage);
  277. result.tags = savedTags;
  278. return result;
  279. }
  280. /**
  281. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  282. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  283. */
  284. async duplicateTags(pageIdMapping) {
  285. const PageTagRelation = mongoose.model('PageTagRelation');
  286. // convert pageId from string to ObjectId
  287. const pageIds = Object.keys(pageIdMapping);
  288. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: mongoose.Types.ObjectId(pageId) } }) };
  289. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  290. {
  291. $match: stage,
  292. },
  293. {
  294. $group: {
  295. _id: '$relatedTag',
  296. relatedPages: { $push: '$relatedPage' },
  297. },
  298. },
  299. ]);
  300. const newPageTagRelation = [];
  301. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  302. // relatedPages
  303. relatedPages.forEach((pageId) => {
  304. newPageTagRelation.push({
  305. relatedPage: pageIdMapping[pageId], // newPageId
  306. relatedTag: _id,
  307. });
  308. });
  309. });
  310. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  311. }
  312. async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  313. const Page = this.crowi.model('Page');
  314. const Revision = this.crowi.model('Revision');
  315. const paths = pages.map(page => (page.path));
  316. const revisions = await Revision.find({ path: { $in: paths } });
  317. // Mapping to set to the body of the new revision
  318. const pathRevisionMapping = {};
  319. revisions.forEach((revision) => {
  320. pathRevisionMapping[revision.path] = revision;
  321. });
  322. // key: oldPageId, value: newPageId
  323. const pageIdMapping = {};
  324. const newPages = [];
  325. const newRevisions = [];
  326. pages.forEach((page) => {
  327. const newPageId = new mongoose.Types.ObjectId();
  328. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  329. const revisionId = new mongoose.Types.ObjectId();
  330. pageIdMapping[page._id] = newPageId;
  331. newPages.push({
  332. _id: newPageId,
  333. path: newPagePath,
  334. creator: user._id,
  335. grant: page.grant,
  336. grantedGroup: page.grantedGroup,
  337. grantedUsers: page.grantedUsers,
  338. lastUpdateUser: user._id,
  339. redirectTo: null,
  340. revision: revisionId,
  341. });
  342. newRevisions.push({
  343. _id: revisionId, path: newPagePath, body: pathRevisionMapping[page.path].body, author: user._id, format: 'markdown',
  344. });
  345. });
  346. await Page.insertMany(newPages, { ordered: false });
  347. await Revision.insertMany(newRevisions, { ordered: false });
  348. await this.duplicateTags(pageIdMapping);
  349. }
  350. async duplicateDescendantsWithStream(page, newPagePath, user) {
  351. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  352. const newPagePathPrefix = newPagePath;
  353. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  354. const duplicateDescendants = this.duplicateDescendants.bind(this);
  355. const pageEvent = this.pageEvent;
  356. let count = 0;
  357. const writeStream = new Writable({
  358. objectMode: true,
  359. async write(batch, encoding, callback) {
  360. try {
  361. count += batch.length;
  362. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix);
  363. logger.debug(`Adding pages progressing: (count=${count})`);
  364. }
  365. catch (err) {
  366. logger.error('addAllPages error on add anyway: ', err);
  367. }
  368. callback();
  369. },
  370. final(callback) {
  371. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  372. // update path
  373. page.path = newPagePath;
  374. pageEvent.emit('syncDescendants', page, user);
  375. callback();
  376. },
  377. });
  378. readStream
  379. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  380. .pipe(writeStream);
  381. }
  382. async deletePage(page, user, options = {}, isRecursively = false) {
  383. const Page = this.crowi.model('Page');
  384. const Revision = this.crowi.model('Revision');
  385. const newPath = Page.getDeletedPageName(page.path);
  386. const isTrashed = isTrashPage(page.path);
  387. if (isTrashed) {
  388. throw new Error('This method does NOT support deleting trashed pages.');
  389. }
  390. if (!Page.isDeletableName(page.path)) {
  391. throw new Error('Page is not deletable.');
  392. }
  393. if (isRecursively) {
  394. this.deleteDescendantsWithStream(page, user, options);
  395. }
  396. // update Rivisions
  397. await Revision.updateRevisionListByPath(page.path, { path: newPath }, {});
  398. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  399. $set: {
  400. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  401. },
  402. }, { new: true });
  403. const body = `redirect ${newPath}`;
  404. await Page.create(page.path, body, user, { redirectTo: newPath });
  405. this.pageEvent.emit('delete', page, user);
  406. this.pageEvent.emit('create', deletedPage, user);
  407. return deletedPage;
  408. }
  409. async deleteDescendants(pages, user) {
  410. const Page = this.crowi.model('Page');
  411. const pageCollection = mongoose.connection.collection('pages');
  412. const revisionCollection = mongoose.connection.collection('revisions');
  413. const deletePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  414. const updateRevisionListOp = revisionCollection.initializeUnorderedBulkOp();
  415. const createRediectRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  416. const newPagesForRedirect = [];
  417. pages.forEach((page) => {
  418. const newPath = Page.getDeletedPageName(page.path);
  419. const revisionId = new mongoose.Types.ObjectId();
  420. const body = `redirect ${newPath}`;
  421. deletePageBulkOp.find({ _id: page._id }).update({
  422. $set: {
  423. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  424. },
  425. });
  426. updateRevisionListOp.find({ path: page.path }).update({ $set: { path: newPath } });
  427. createRediectRevisionBulkOp.insert({
  428. _id: revisionId, path: page.path, body, author: user._id, format: 'markdown',
  429. });
  430. newPagesForRedirect.push({
  431. path: page.path,
  432. creator: user._id,
  433. grant: page.grant,
  434. grantedGroup: page.grantedGroup,
  435. grantedUsers: page.grantedUsers,
  436. lastUpdateUser: user._id,
  437. redirectTo: newPath,
  438. revision: revisionId,
  439. });
  440. });
  441. try {
  442. await deletePageBulkOp.execute();
  443. await updateRevisionListOp.execute();
  444. await createRediectRevisionBulkOp.execute();
  445. await Page.insertMany(newPagesForRedirect, { ordered: false });
  446. }
  447. catch (err) {
  448. if (err.code !== 11000) {
  449. throw new Error('Failed to revert pages: ', err);
  450. }
  451. }
  452. }
  453. /**
  454. * Create delete stream
  455. */
  456. async deleteDescendantsWithStream(targetPage, user, options = {}) {
  457. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  458. const deleteDescendants = this.deleteDescendants.bind(this);
  459. let count = 0;
  460. const writeStream = new Writable({
  461. objectMode: true,
  462. async write(batch, encoding, callback) {
  463. try {
  464. count += batch.length;
  465. deleteDescendants(batch, user);
  466. logger.debug(`Reverting pages progressing: (count=${count})`);
  467. }
  468. catch (err) {
  469. logger.error('revertPages error on add anyway: ', err);
  470. }
  471. callback();
  472. },
  473. final(callback) {
  474. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  475. callback();
  476. },
  477. });
  478. readStream
  479. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  480. .pipe(writeStream);
  481. }
  482. // delete multiple pages
  483. async deleteMultipleCompletely(pages, user, options = {}) {
  484. const ids = pages.map(page => (page._id));
  485. const paths = pages.map(page => (page.path));
  486. logger.debug('Deleting completely', paths);
  487. await this.deleteCompletelyOperation(ids, paths);
  488. this.pageEvent.emit('deleteCompletely', pages, user); // update as renamed page
  489. return;
  490. }
  491. async deleteCompletely(page, user, options = {}, isRecursively = false) {
  492. const ids = [page._id];
  493. const paths = [page.path];
  494. logger.debug('Deleting completely', paths);
  495. await this.deleteCompletelyOperation(ids, paths);
  496. if (isRecursively) {
  497. this.deleteCompletelyDescendantsWithStream(page, user, options);
  498. }
  499. this.pageEvent.emit('delete', page, user); // update as renamed page
  500. return;
  501. }
  502. /**
  503. * Create delete completely stream
  504. */
  505. async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}) {
  506. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  507. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  508. let count = 0;
  509. const writeStream = new Writable({
  510. objectMode: true,
  511. async write(batch, encoding, callback) {
  512. try {
  513. count += batch.length;
  514. await deleteMultipleCompletely(batch, user, options);
  515. logger.debug(`Adding pages progressing: (count=${count})`);
  516. }
  517. catch (err) {
  518. logger.error('addAllPages error on add anyway: ', err);
  519. }
  520. callback();
  521. },
  522. final(callback) {
  523. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  524. callback();
  525. },
  526. });
  527. readStream
  528. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  529. .pipe(writeStream);
  530. }
  531. async revertDeletedDescendants(pages, user) {
  532. const Page = this.crowi.model('Page');
  533. const pageCollection = mongoose.connection.collection('pages');
  534. const revisionCollection = mongoose.connection.collection('revisions');
  535. const removePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  536. const revertPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  537. const revertRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  538. // e.g. key: '/test'
  539. const pathToPageMapping = {};
  540. const toPaths = pages.map(page => Page.getRevertDeletedPageName(page.path));
  541. const toPages = await Page.find({ path: { $in: toPaths } });
  542. toPages.forEach((toPage) => {
  543. pathToPageMapping[toPage.path] = toPage;
  544. });
  545. pages.forEach((page) => {
  546. // e.g. page.path = /trash/test, toPath = /test
  547. const toPath = Page.getRevertDeletedPageName(page.path);
  548. if (pathToPageMapping[toPath] != null) {
  549. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  550. // So, it's ok to delete the page
  551. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  552. if (pathToPageMapping[toPath].redirectTo === page.path) {
  553. removePageBulkOp.find({ path: toPath }).remove();
  554. }
  555. }
  556. revertPageBulkOp.find({ _id: page._id }).update({
  557. $set: {
  558. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  559. },
  560. });
  561. revertRevisionBulkOp.find({ path: page.path }).update({ $set: { path: toPath } }, { multi: true });
  562. });
  563. try {
  564. await removePageBulkOp.execute();
  565. await revertPageBulkOp.execute();
  566. await revertRevisionBulkOp.execute();
  567. }
  568. catch (err) {
  569. if (err.code !== 11000) {
  570. throw new Error('Failed to revert pages: ', err);
  571. }
  572. }
  573. }
  574. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  575. const Page = this.crowi.model('Page');
  576. const Revision = this.crowi.model('Revision');
  577. const newPath = Page.getRevertDeletedPageName(page.path);
  578. const originPage = await Page.findByPath(newPath);
  579. if (originPage != null) {
  580. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  581. // So, it's ok to delete the page
  582. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  583. if (originPage.redirectTo !== page.path) {
  584. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  585. }
  586. await this.deleteCompletely(originPage, options);
  587. }
  588. if (isRecursively) {
  589. this.revertDeletedDescendantsWithStream(page, user, options);
  590. }
  591. page.status = Page.STATUS_PUBLISHED;
  592. page.lastUpdateUser = user;
  593. debug('Revert deleted the page', page, newPath);
  594. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  595. $set: {
  596. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  597. },
  598. }, { new: true });
  599. await Revision.updateMany({ path: page.path }, { $set: { path: newPath } });
  600. return updatedPage;
  601. }
  602. /**
  603. * Create revert stream
  604. */
  605. async revertDeletedDescendantsWithStream(targetPage, user, options = {}) {
  606. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  607. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  608. let count = 0;
  609. const writeStream = new Writable({
  610. objectMode: true,
  611. async write(batch, encoding, callback) {
  612. try {
  613. count += batch.length;
  614. revertDeletedDescendants(batch, user);
  615. logger.debug(`Reverting pages progressing: (count=${count})`);
  616. }
  617. catch (err) {
  618. logger.error('revertPages error on add anyway: ', err);
  619. }
  620. callback();
  621. },
  622. final(callback) {
  623. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  624. callback();
  625. },
  626. });
  627. readStream
  628. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  629. .pipe(writeStream);
  630. }
  631. async handlePrivatePagesForDeletedGroup(deletedGroup, action, transferToUserGroupId, user) {
  632. const Page = this.crowi.model('Page');
  633. const pages = await Page.find({ grantedGroup: deletedGroup });
  634. switch (action) {
  635. case 'public':
  636. await Promise.all(pages.map((page) => {
  637. return Page.publicizePage(page);
  638. }));
  639. break;
  640. case 'delete':
  641. return this.deleteMultipleCompletely(pages, user);
  642. case 'transfer':
  643. await Promise.all(pages.map((page) => {
  644. return Page.transferPageToGroup(page, transferToUserGroupId);
  645. }));
  646. break;
  647. default:
  648. throw new Error('Unknown action for private pages');
  649. }
  650. }
  651. validateCrowi() {
  652. if (this.crowi == null) {
  653. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  654. }
  655. }
  656. createAndSendNotifications = async function(page, user, action) {
  657. const { activityService, inAppNotificationService } = this.crowi;
  658. // Create activity
  659. const parameters = {
  660. user: user._id,
  661. targetModel: ActivityDefine.MODEL_PAGE,
  662. target: page,
  663. action,
  664. };
  665. const activity = await activityService.createByParameters(parameters);
  666. // Get user to be notified
  667. const targetUsers = await activity.getNotificationTargetUsers();
  668. // Create and send notifications
  669. await inAppNotificationService.upsertByActivity(targetUsers, activity);
  670. await inAppNotificationService.emitSocketIo(targetUsers);
  671. };
  672. }
  673. module.exports = PageService;