page.js 25 KB

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