page.js 25 KB

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