page.js 32 KB

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