page.js 24 KB

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