page.js 22 KB

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