page.js 24 KB

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