page.js 26 KB

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