page.js 26 KB

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