page.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. import { pagePathUtils } from '@growi/core';
  2. import loggerFactory from '~/utils/logger';
  3. const mongoose = require('mongoose');
  4. const escapeStringRegexp = require('escape-string-regexp');
  5. const streamToPromise = require('stream-to-promise');
  6. const pathlib = require('path');
  7. const logger = loggerFactory('growi:models:page');
  8. const debug = require('debug')('growi:models:page');
  9. const { Writable } = require('stream');
  10. const { createBatchStream } = require('~/server/util/batch-stream');
  11. const { isTrashPage } = pagePathUtils;
  12. const { serializePageSecurely } = require('../models/serializers/page-serializer');
  13. const BULK_REINDEX_SIZE = 100;
  14. class PageService {
  15. constructor(crowi) {
  16. this.crowi = crowi;
  17. this.pageEvent = crowi.event('page');
  18. // init
  19. this.pageEvent.on('create', this.pageEvent.onCreate);
  20. this.pageEvent.on('update', this.pageEvent.onUpdate);
  21. this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
  22. }
  23. /**
  24. * go back by using redirectTo and return the paths
  25. * ex: when
  26. * '/page1' redirects to '/page2' and
  27. * '/page2' redirects to '/page3'
  28. * and given '/page3',
  29. * '/page1' and '/page2' will be return
  30. *
  31. * @param {string} redirectTo
  32. * @param {object} redirectToPagePathMapping
  33. * @param {array} pagePaths
  34. */
  35. prepareShoudDeletePagesByRedirectTo(redirectTo, redirectToPagePathMapping, pagePaths = []) {
  36. const pagePath = redirectToPagePathMapping[redirectTo];
  37. if (pagePath == null) {
  38. return pagePaths;
  39. }
  40. pagePaths.push(pagePath);
  41. return this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping, pagePaths);
  42. }
  43. /**
  44. * Generate read stream to operate descendants of the specified page path
  45. * @param {string} targetPagePath
  46. * @param {User} viewer
  47. */
  48. async generateReadStreamToOperateOnlyDescendants(targetPagePath, userToOperate) {
  49. const Page = this.crowi.model('Page');
  50. const { PageQueryBuilder } = Page;
  51. const builder = new PageQueryBuilder(Page.find())
  52. .addConditionToExcludeRedirect()
  53. .addConditionToListOnlyDescendants(targetPagePath);
  54. await Page.addConditionToFilteringByViewerToEdit(builder, userToOperate);
  55. return builder
  56. .query
  57. .lean()
  58. .cursor({ batchSize: BULK_REINDEX_SIZE });
  59. }
  60. async renamePage(page, newPagePath, user, options, isRecursively = false) {
  61. const Page = this.crowi.model('Page');
  62. const Revision = this.crowi.model('Revision');
  63. const path = page.path;
  64. const createRedirectPage = options.createRedirectPage || false;
  65. const updateMetadata = options.updateMetadata || false;
  66. // sanitize path
  67. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  68. // create descendants first
  69. if (isRecursively) {
  70. await this.renameDescendantsWithStream(page, newPagePath, user, options);
  71. }
  72. const update = {};
  73. // update Page
  74. update.path = newPagePath;
  75. if (updateMetadata) {
  76. update.lastUpdateUser = user;
  77. update.updatedAt = Date.now();
  78. }
  79. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  80. // update Rivisions
  81. await Revision.updateRevisionListByPath(path, { path: newPagePath }, {});
  82. if (createRedirectPage) {
  83. const body = `redirect ${newPagePath}`;
  84. await Page.create(path, body, user, { redirectTo: newPagePath });
  85. }
  86. this.pageEvent.emit('delete', page, user);
  87. this.pageEvent.emit('create', renamedPage, user);
  88. return renamedPage;
  89. }
  90. async renameDescendants(pages, user, options, oldPagePathPrefix, newPagePathPrefix) {
  91. const Page = this.crowi.model('Page');
  92. const pageCollection = mongoose.connection.collection('pages');
  93. const revisionCollection = mongoose.connection.collection('revisions');
  94. const { updateMetadata, createRedirectPage } = options;
  95. const unorderedBulkOp = pageCollection.initializeUnorderedBulkOp();
  96. const createRediectPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  97. const revisionUnorderedBulkOp = revisionCollection.initializeUnorderedBulkOp();
  98. const createRediectRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  99. pages.forEach((page) => {
  100. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  101. const revisionId = new mongoose.Types.ObjectId();
  102. if (updateMetadata) {
  103. unorderedBulkOp
  104. .find({ _id: page._id })
  105. .update({ $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() } });
  106. }
  107. else {
  108. unorderedBulkOp.find({ _id: page._id }).update({ $set: { path: newPagePath } });
  109. }
  110. if (createRedirectPage) {
  111. createRediectPageBulkOp.insert({
  112. path: page.path, revision: revisionId, creator: user._id, lastUpdateUser: user._id, status: Page.STATUS_PUBLISHED, redirectTo: newPagePath,
  113. });
  114. createRediectRevisionBulkOp.insert({
  115. _id: revisionId, path: page.path, body: `redirect ${newPagePath}`, author: user._id, format: 'markdown',
  116. });
  117. }
  118. revisionUnorderedBulkOp.find({ path: page.path }).update({ $set: { path: newPagePath } }, { multi: true });
  119. });
  120. try {
  121. await unorderedBulkOp.execute();
  122. await revisionUnorderedBulkOp.execute();
  123. // Execute after unorderedBulkOp to prevent duplication
  124. if (createRedirectPage) {
  125. await createRediectPageBulkOp.execute();
  126. await createRediectRevisionBulkOp.execute();
  127. }
  128. }
  129. catch (err) {
  130. if (err.code !== 11000) {
  131. throw new Error('Failed to rename pages: ', err);
  132. }
  133. }
  134. this.pageEvent.emit('updateMany', pages, user);
  135. }
  136. /**
  137. * Create rename stream
  138. */
  139. async renameDescendantsWithStream(targetPage, newPagePath, user, options = {}) {
  140. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  141. const newPagePathPrefix = newPagePath;
  142. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  143. const renameDescendants = this.renameDescendants.bind(this);
  144. const pageEvent = this.pageEvent;
  145. let count = 0;
  146. const writeStream = new Writable({
  147. objectMode: true,
  148. async write(batch, encoding, callback) {
  149. try {
  150. count += batch.length;
  151. await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
  152. logger.debug(`Reverting pages progressing: (count=${count})`);
  153. }
  154. catch (err) {
  155. logger.error('revertPages error on add anyway: ', err);
  156. }
  157. callback();
  158. },
  159. final(callback) {
  160. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  161. // update path
  162. targetPage.path = newPagePath;
  163. pageEvent.emit('syncDescendants', targetPage, user);
  164. callback();
  165. },
  166. });
  167. readStream
  168. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  169. .pipe(writeStream);
  170. await streamToPromise(readStream);
  171. }
  172. async deleteCompletelyOperation(pageIds, pagePaths) {
  173. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  174. const Bookmark = this.crowi.model('Bookmark');
  175. const Comment = this.crowi.model('Comment');
  176. const Page = this.crowi.model('Page');
  177. const PageTagRelation = this.crowi.model('PageTagRelation');
  178. const ShareLink = this.crowi.model('ShareLink');
  179. const Revision = this.crowi.model('Revision');
  180. const Attachment = this.crowi.model('Attachment');
  181. const { attachmentService } = this.crowi;
  182. const attachments = await Attachment.find({ page: { $in: pageIds } });
  183. const pages = await Page.find({ redirectTo: { $ne: null } });
  184. const redirectToPagePathMapping = {};
  185. pages.forEach((page) => {
  186. redirectToPagePathMapping[page.redirectTo] = page.path;
  187. });
  188. const redirectedFromPagePaths = [];
  189. pagePaths.forEach((pagePath) => {
  190. redirectedFromPagePaths.push(...this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping));
  191. });
  192. return Promise.all([
  193. Bookmark.deleteMany({ page: { $in: pageIds } }),
  194. Comment.deleteMany({ page: { $in: pageIds } }),
  195. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  196. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  197. Revision.deleteMany({ path: { $in: pagePaths } }),
  198. Page.deleteMany({ $or: [{ path: { $in: pagePaths } }, { path: { $in: redirectedFromPagePaths } }, { _id: { $in: pageIds } }] }),
  199. attachmentService.removeAllAttachments(attachments),
  200. ]);
  201. }
  202. async duplicate(page, newPagePath, user, isRecursively) {
  203. const Page = this.crowi.model('Page');
  204. const PageTagRelation = mongoose.model('PageTagRelation');
  205. // populate
  206. await page.populate({ path: 'revision', model: 'Revision', select: 'body' }).execPopulate();
  207. // create option
  208. const options = { page };
  209. options.grant = page.grant;
  210. options.grantUserGroupId = page.grantedGroup;
  211. options.grantedUsers = page.grantedUsers;
  212. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  213. const createdPage = await Page.create(
  214. newPagePath, page.revision.body, user, options,
  215. );
  216. if (isRecursively) {
  217. this.duplicateDescendantsWithStream(page, newPagePath, user);
  218. }
  219. // take over tags
  220. const originTags = await page.findRelatedTagsById();
  221. let savedTags = [];
  222. if (originTags != null) {
  223. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  224. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  225. }
  226. const result = serializePageSecurely(createdPage);
  227. result.tags = savedTags;
  228. return result;
  229. }
  230. /**
  231. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  232. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  233. */
  234. async duplicateTags(pageIdMapping) {
  235. const PageTagRelation = mongoose.model('PageTagRelation');
  236. // convert pageId from string to ObjectId
  237. const pageIds = Object.keys(pageIdMapping);
  238. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: mongoose.Types.ObjectId(pageId) } }) };
  239. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  240. {
  241. $match: stage,
  242. },
  243. {
  244. $group: {
  245. _id: '$relatedTag',
  246. relatedPages: { $push: '$relatedPage' },
  247. },
  248. },
  249. ]);
  250. const newPageTagRelation = [];
  251. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  252. // relatedPages
  253. relatedPages.forEach((pageId) => {
  254. newPageTagRelation.push({
  255. relatedPage: pageIdMapping[pageId], // newPageId
  256. relatedTag: _id,
  257. });
  258. });
  259. });
  260. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  261. }
  262. async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  263. const Page = this.crowi.model('Page');
  264. const Revision = this.crowi.model('Revision');
  265. const paths = pages.map(page => (page.path));
  266. const revisions = await Revision.find({ path: { $in: paths } });
  267. // Mapping to set to the body of the new revision
  268. const pathRevisionMapping = {};
  269. revisions.forEach((revision) => {
  270. pathRevisionMapping[revision.path] = revision;
  271. });
  272. // key: oldPageId, value: newPageId
  273. const pageIdMapping = {};
  274. const newPages = [];
  275. const newRevisions = [];
  276. pages.forEach((page) => {
  277. const newPageId = new mongoose.Types.ObjectId();
  278. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  279. const revisionId = new mongoose.Types.ObjectId();
  280. pageIdMapping[page._id] = newPageId;
  281. newPages.push({
  282. _id: newPageId,
  283. path: newPagePath,
  284. creator: user._id,
  285. grant: page.grant,
  286. grantedGroup: page.grantedGroup,
  287. grantedUsers: page.grantedUsers,
  288. lastUpdateUser: user._id,
  289. redirectTo: null,
  290. revision: revisionId,
  291. });
  292. newRevisions.push({
  293. _id: revisionId, path: newPagePath, body: pathRevisionMapping[page.path].body, author: user._id, format: 'markdown',
  294. });
  295. });
  296. await Page.insertMany(newPages, { ordered: false });
  297. await Revision.insertMany(newRevisions, { ordered: false });
  298. await this.duplicateTags(pageIdMapping);
  299. }
  300. async duplicateDescendantsWithStream(page, newPagePath, user) {
  301. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  302. const newPagePathPrefix = newPagePath;
  303. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  304. const duplicateDescendants = this.duplicateDescendants.bind(this);
  305. const pageEvent = this.pageEvent;
  306. let count = 0;
  307. const writeStream = new Writable({
  308. objectMode: true,
  309. async write(batch, encoding, callback) {
  310. try {
  311. count += batch.length;
  312. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix);
  313. logger.debug(`Adding pages progressing: (count=${count})`);
  314. }
  315. catch (err) {
  316. logger.error('addAllPages error on add anyway: ', err);
  317. }
  318. callback();
  319. },
  320. final(callback) {
  321. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  322. // update path
  323. page.path = newPagePath;
  324. pageEvent.emit('syncDescendants', page, user);
  325. callback();
  326. },
  327. });
  328. readStream
  329. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  330. .pipe(writeStream);
  331. }
  332. async deletePage(page, user, options = {}, isRecursively = false) {
  333. const Page = this.crowi.model('Page');
  334. const Revision = this.crowi.model('Revision');
  335. const newPath = Page.getDeletedPageName(page.path);
  336. const isTrashed = isTrashPage(page.path);
  337. if (isTrashed) {
  338. throw new Error('This method does NOT support deleting trashed pages.');
  339. }
  340. if (!Page.isDeletableName(page.path)) {
  341. throw new Error('Page is not deletable.');
  342. }
  343. if (isRecursively) {
  344. this.deleteDescendantsWithStream(page, user, options);
  345. }
  346. // update Rivisions
  347. await Revision.updateRevisionListByPath(page.path, { path: newPath }, {});
  348. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  349. $set: {
  350. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  351. },
  352. }, { new: true });
  353. const body = `redirect ${newPath}`;
  354. await Page.create(page.path, body, user, { redirectTo: newPath });
  355. this.pageEvent.emit('delete', page, user);
  356. this.pageEvent.emit('create', deletedPage, user);
  357. return deletedPage;
  358. }
  359. async deleteDescendants(pages, user) {
  360. const Page = this.crowi.model('Page');
  361. const pageCollection = mongoose.connection.collection('pages');
  362. const revisionCollection = mongoose.connection.collection('revisions');
  363. const deletePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  364. const updateRevisionListOp = revisionCollection.initializeUnorderedBulkOp();
  365. const createRediectRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  366. const newPagesForRedirect = [];
  367. pages.forEach((page) => {
  368. const newPath = Page.getDeletedPageName(page.path);
  369. const revisionId = new mongoose.Types.ObjectId();
  370. const body = `redirect ${newPath}`;
  371. deletePageBulkOp.find({ _id: page._id }).update({
  372. $set: {
  373. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  374. },
  375. });
  376. updateRevisionListOp.find({ path: page.path }).update({ $set: { path: newPath } });
  377. createRediectRevisionBulkOp.insert({
  378. _id: revisionId, path: page.path, body, author: user._id, format: 'markdown',
  379. });
  380. newPagesForRedirect.push({
  381. path: page.path,
  382. creator: user._id,
  383. grant: page.grant,
  384. grantedGroup: page.grantedGroup,
  385. grantedUsers: page.grantedUsers,
  386. lastUpdateUser: user._id,
  387. redirectTo: newPath,
  388. revision: revisionId,
  389. });
  390. });
  391. try {
  392. await deletePageBulkOp.execute();
  393. await updateRevisionListOp.execute();
  394. await createRediectRevisionBulkOp.execute();
  395. await Page.insertMany(newPagesForRedirect, { ordered: false });
  396. }
  397. catch (err) {
  398. if (err.code !== 11000) {
  399. throw new Error('Failed to revert pages: ', err);
  400. }
  401. }
  402. }
  403. /**
  404. * Create delete stream
  405. */
  406. async deleteDescendantsWithStream(targetPage, user, options = {}) {
  407. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  408. const deleteDescendants = this.deleteDescendants.bind(this);
  409. let count = 0;
  410. const writeStream = new Writable({
  411. objectMode: true,
  412. async write(batch, encoding, callback) {
  413. try {
  414. count += batch.length;
  415. deleteDescendants(batch, user);
  416. logger.debug(`Reverting pages progressing: (count=${count})`);
  417. }
  418. catch (err) {
  419. logger.error('revertPages error on add anyway: ', err);
  420. }
  421. callback();
  422. },
  423. final(callback) {
  424. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  425. callback();
  426. },
  427. });
  428. readStream
  429. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  430. .pipe(writeStream);
  431. }
  432. // delete multiple pages
  433. async deleteMultipleCompletely(pages, user, options = {}) {
  434. const ids = pages.map(page => (page._id));
  435. const paths = pages.map(page => (page.path));
  436. logger.debug('Deleting completely', paths);
  437. await this.deleteCompletelyOperation(ids, paths);
  438. this.pageEvent.emit('deleteCompletely', pages, user); // update as renamed page
  439. return;
  440. }
  441. async deleteCompletely(page, user, options = {}, isRecursively = false) {
  442. const ids = [page._id];
  443. const paths = [page.path];
  444. logger.debug('Deleting completely', paths);
  445. await this.deleteCompletelyOperation(ids, paths);
  446. if (isRecursively) {
  447. this.deleteCompletelyDescendantsWithStream(page, user, options);
  448. }
  449. this.pageEvent.emit('delete', page, user); // update as renamed page
  450. return;
  451. }
  452. /**
  453. * Create delete completely stream
  454. */
  455. async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}) {
  456. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  457. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  458. let count = 0;
  459. const writeStream = new Writable({
  460. objectMode: true,
  461. async write(batch, encoding, callback) {
  462. try {
  463. count += batch.length;
  464. await deleteMultipleCompletely(batch, user, options);
  465. logger.debug(`Adding pages progressing: (count=${count})`);
  466. }
  467. catch (err) {
  468. logger.error('addAllPages error on add anyway: ', err);
  469. }
  470. callback();
  471. },
  472. final(callback) {
  473. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  474. callback();
  475. },
  476. });
  477. readStream
  478. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  479. .pipe(writeStream);
  480. }
  481. async revertDeletedDescendants(pages, user) {
  482. const Page = this.crowi.model('Page');
  483. const pageCollection = mongoose.connection.collection('pages');
  484. const revisionCollection = mongoose.connection.collection('revisions');
  485. const removePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  486. const revertPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  487. const revertRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  488. // e.g. key: '/test'
  489. const pathToPageMapping = {};
  490. const toPaths = pages.map(page => Page.getRevertDeletedPageName(page.path));
  491. const toPages = await Page.find({ path: { $in: toPaths } });
  492. toPages.forEach((toPage) => {
  493. pathToPageMapping[toPage.path] = toPage;
  494. });
  495. pages.forEach((page) => {
  496. // e.g. page.path = /trash/test, toPath = /test
  497. const toPath = Page.getRevertDeletedPageName(page.path);
  498. if (pathToPageMapping[toPath] != null) {
  499. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  500. // So, it's ok to delete the page
  501. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  502. if (pathToPageMapping[toPath].redirectTo === page.path) {
  503. removePageBulkOp.find({ path: toPath }).remove();
  504. }
  505. }
  506. revertPageBulkOp.find({ _id: page._id }).update({
  507. $set: {
  508. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  509. },
  510. });
  511. revertRevisionBulkOp.find({ path: page.path }).update({ $set: { path: toPath } }, { multi: true });
  512. });
  513. try {
  514. await removePageBulkOp.execute();
  515. await revertPageBulkOp.execute();
  516. await revertRevisionBulkOp.execute();
  517. }
  518. catch (err) {
  519. if (err.code !== 11000) {
  520. throw new Error('Failed to revert pages: ', err);
  521. }
  522. }
  523. }
  524. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  525. const Page = this.crowi.model('Page');
  526. const Revision = this.crowi.model('Revision');
  527. const newPath = Page.getRevertDeletedPageName(page.path);
  528. const originPage = await Page.findByPath(newPath);
  529. if (originPage != null) {
  530. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  531. // So, it's ok to delete the page
  532. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  533. if (originPage.redirectTo !== page.path) {
  534. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  535. }
  536. await this.deleteCompletely(originPage, options);
  537. }
  538. if (isRecursively) {
  539. this.revertDeletedDescendantsWithStream(page, user, options);
  540. }
  541. page.status = Page.STATUS_PUBLISHED;
  542. page.lastUpdateUser = user;
  543. debug('Revert deleted the page', page, newPath);
  544. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  545. $set: {
  546. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  547. },
  548. }, { new: true });
  549. await Revision.updateMany({ path: page.path }, { $set: { path: newPath } });
  550. return updatedPage;
  551. }
  552. /**
  553. * Create revert stream
  554. */
  555. async revertDeletedDescendantsWithStream(targetPage, user, options = {}) {
  556. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  557. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  558. let count = 0;
  559. const writeStream = new Writable({
  560. objectMode: true,
  561. async write(batch, encoding, callback) {
  562. try {
  563. count += batch.length;
  564. revertDeletedDescendants(batch, user);
  565. logger.debug(`Reverting pages progressing: (count=${count})`);
  566. }
  567. catch (err) {
  568. logger.error('revertPages error on add anyway: ', err);
  569. }
  570. callback();
  571. },
  572. final(callback) {
  573. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  574. callback();
  575. },
  576. });
  577. readStream
  578. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  579. .pipe(writeStream);
  580. }
  581. async handlePrivatePagesForDeletedGroup(deletedGroup, action, transferToUserGroupId, user) {
  582. const Page = this.crowi.model('Page');
  583. const pages = await Page.find({ grantedGroup: deletedGroup });
  584. switch (action) {
  585. case 'public':
  586. await Promise.all(pages.map((page) => {
  587. return Page.publicizePage(page);
  588. }));
  589. break;
  590. case 'delete':
  591. return this.deleteMultipleCompletely(pages, user);
  592. case 'transfer':
  593. await Promise.all(pages.map((page) => {
  594. return Page.transferPageToGroup(page, transferToUserGroupId);
  595. }));
  596. break;
  597. default:
  598. throw new Error('Unknown action for private pages');
  599. }
  600. }
  601. validateCrowi() {
  602. if (this.crowi == null) {
  603. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  604. }
  605. }
  606. async v5Migration(grant, rootPath = null) {
  607. const socket = this.crowicrowi.socketIoService.getAdminSocket();
  608. try {
  609. await this._v5RecursiveMigration(grant, rootPath);
  610. }
  611. catch (err) {
  612. logger.error('V5 miration failed.', err);
  613. socket.emit('v5MirationFailed', { error: err.message });
  614. throw err;
  615. }
  616. }
  617. // TODO: use websocket to show progress
  618. async _v5RecursiveMigration(grant, rootPath) {
  619. const BATCH_SIZE = 100;
  620. const PAGES_LIMIT = 1000;
  621. const Page = this.crowi.model('Page');
  622. const { PageQueryBuilder } = Page;
  623. const total = await Page.countDocuments({ grant, parent: null });
  624. let baseAggregation = Page
  625. .aggregate([
  626. {
  627. $match: {
  628. grant,
  629. parent: null,
  630. },
  631. },
  632. {
  633. $project: { // minimize data to fetch
  634. _id: 1,
  635. path: 1,
  636. },
  637. },
  638. ]);
  639. // limit pages to get
  640. if (total > PAGES_LIMIT) {
  641. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  642. }
  643. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE }).exec();
  644. // use batch stream
  645. const batchStream = createBatchStream(BATCH_SIZE);
  646. let countPages = 0;
  647. // migrate all siblings for each page
  648. const migratePagesStream = new Writable({
  649. objectMode: true,
  650. async write(pages, encoding, callback) {
  651. // make list to create empty pages
  652. const parentPathsSet = new Set(pages.map(page => pathlib.dirname(page.path)));
  653. const parentPaths = Array.from(parentPathsSet);
  654. // find existing parents
  655. const builder1 = new PageQueryBuilder(Page.find({}, { _id: 0, path: 1 }));
  656. const existingParents = await builder1
  657. .addConditionToListByPathsArray(parentPaths)
  658. .query
  659. .lean()
  660. .exec();
  661. const existingParentPaths = existingParents.map(parent => parent.path);
  662. // paths to create empty pages
  663. const notExistingParentPaths = parentPaths.filter(path => !existingParentPaths.includes(path));
  664. // insertMany empty pages
  665. try {
  666. await Page.insertMany(notExistingParentPaths.map(path => ({ path, isEmpty: true })));
  667. }
  668. catch (err) {
  669. logger.error('Failed to insert empty pages.', err);
  670. throw err;
  671. }
  672. // find parents again
  673. const builder2 = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }));
  674. const parents = await builder2
  675. .addConditionToListByPathsArray(parentPaths)
  676. .query
  677. .lean()
  678. .exec();
  679. // bulkWrite to update parent
  680. const updateManyOperations = parents.map((parent) => {
  681. const parentId = parent._id;
  682. // modify to adjust for RegExp
  683. const parentPath = parent.path === '/' ? '' : parent.path;
  684. return {
  685. updateMany: {
  686. filter: {
  687. // regexr.com/6889f
  688. // ex. /parent/any_child OR /any_level1
  689. path: { $regex: new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`, 'g') },
  690. },
  691. update: {
  692. parent: parentId,
  693. },
  694. },
  695. };
  696. });
  697. try {
  698. const res = await Page.bulkWrite(updateManyOperations);
  699. countPages += (res.items || []).length;
  700. logger.info(`Page migration processing: (count=${countPages}, errors=${res.errors}, took=${res.took}ms)`);
  701. }
  702. catch (err) {
  703. logger.error('Failed to update page.parent.', err);
  704. throw err;
  705. }
  706. callback();
  707. },
  708. final(callback) {
  709. callback();
  710. },
  711. });
  712. pagesStream
  713. .pipe(batchStream)
  714. .pipe(migratePagesStream);
  715. await streamToPromise(migratePagesStream);
  716. if (await Page.exists({ grant, parent: null, path: { $ne: '/' } })) {
  717. return this.v5RecursiveMigration(grant, rootPath);
  718. }
  719. /*
  720. * After completed migration
  721. */
  722. if (grant !== Page.GRANT_PUBLIC) {
  723. return;
  724. }
  725. const collection = mongoose.connection.collection('pages');
  726. const indexStatus = await Page.aggregate([{ $indexStats: {} }]);
  727. const pathIndexStatus = indexStatus.filter(status => status.name === 'path_1')?.[0]?.spec?.unique;
  728. // skip index modification if path is unique
  729. if (pathIndexStatus == null || pathIndexStatus === true) {
  730. // drop only when true. this condition is for in case createIndex failed but dropIndex succeeded before
  731. if (pathIndexStatus) {
  732. try {
  733. // drop pages.path_1 indexes
  734. await collection.dropIndex('path_1');
  735. logger.info('Succeeded to drop unique indexes from pages.path.');
  736. }
  737. catch (err) {
  738. logger.warn('Failed to drop unique indexes from pages.path.', err);
  739. throw err;
  740. }
  741. }
  742. try {
  743. // create indexes without
  744. await collection.createIndex({ path: 1 }, { unique: false });
  745. logger.info('Succeeded to create non-unique indexes on pages.path.');
  746. }
  747. catch (err) {
  748. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  749. throw err;
  750. }
  751. }
  752. try {
  753. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  754. 'app:isV5Compatible': true,
  755. });
  756. logger.info('Successfully migrated all public pages.');
  757. }
  758. catch (err) {
  759. logger.warn('Failed to update app:isV5Compatible to true.');
  760. throw err;
  761. }
  762. }
  763. }
  764. module.exports = PageService;