page.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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. validateCrowi() {
  632. if (this.crowi == null) {
  633. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  634. }
  635. }
  636. async v5MigrationByPageIds(pageIds) {
  637. const Page = mongoose.model('Page');
  638. if (pageIds == null || pageIds.length === 0) {
  639. logger.error('pageIds is null or 0 length.');
  640. return;
  641. }
  642. // generate regexps
  643. const regexps = await this._generateRegExpsByPageIds(pageIds);
  644. // migrate recursively
  645. try {
  646. await this._v5RecursiveMigration(null, regexps);
  647. }
  648. catch (err) {
  649. logger.error('V5 initial miration failed.', err);
  650. // socket.emit('v5InitialMirationFailed', { error: err.message }); TODO: use socket to tell user
  651. throw err;
  652. }
  653. }
  654. async v5InitialMigration(grant) {
  655. const socket = this.crowi.socketIoService.getAdminSocket();
  656. try {
  657. await this._v5RecursiveMigration(grant);
  658. }
  659. catch (err) {
  660. logger.error('V5 initial miration failed.', err);
  661. socket.emit('v5InitialMirationFailed', { error: err.message });
  662. throw err;
  663. }
  664. const Page = this.crowi.model('Page');
  665. const indexStatus = await Page.aggregate([{ $indexStats: {} }]);
  666. const pathIndexStatus = indexStatus.filter(status => status.name === 'path_1')?.[0];
  667. const isPathIndexExists = pathIndexStatus != null;
  668. const isUnique = isPathIndexExists && pathIndexStatus.spec?.unique === true;
  669. if (isUnique || !isPathIndexExists) {
  670. try {
  671. await this._v5NormalizeIndex(isPathIndexExists);
  672. }
  673. catch (err) {
  674. logger.error('V5 index normalization failed.', err);
  675. socket.emit('v5IndexNormalizationFailed', { error: err.message });
  676. throw err;
  677. }
  678. }
  679. await this._setIsV5CompatibleTrue();
  680. }
  681. /*
  682. * returns an array of js RegExp instance instead of RE2 instance for mongo filter
  683. */
  684. async _generateRegExpsByPageIds(pageIds) {
  685. const Page = mongoose.model('Page');
  686. let result;
  687. try {
  688. result = await Page.findListByPageIds(pageIds, null, false);
  689. }
  690. catch (err) {
  691. logger.error('Failed to find pages by ids', err);
  692. throw err;
  693. }
  694. const { pages } = result;
  695. const regexps = pages.map(page => new RegExp(`^${page.path}`));
  696. return regexps;
  697. }
  698. async _setIsV5CompatibleTrue() {
  699. try {
  700. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  701. 'app:isV5Compatible': true,
  702. });
  703. logger.info('Successfully migrated all public pages.');
  704. }
  705. catch (err) {
  706. logger.warn('Failed to update app:isV5Compatible to true.');
  707. throw err;
  708. }
  709. }
  710. // TODO: use websocket to show progress
  711. async _v5RecursiveMigration(grant, regexps) {
  712. const BATCH_SIZE = 100;
  713. const PAGES_LIMIT = 1000;
  714. const Page = this.crowi.model('Page');
  715. const { PageQueryBuilder } = Page;
  716. // generate filter
  717. let filter = {
  718. parent: null,
  719. path: { $ne: '/' },
  720. };
  721. if (grant != null) {
  722. filter = {
  723. ...filter,
  724. grant,
  725. };
  726. }
  727. if (regexps != null && regexps.length !== 0) {
  728. filter = {
  729. ...filter,
  730. path: {
  731. $in: regexps,
  732. },
  733. };
  734. }
  735. const total = await Page.countDocuments(filter);
  736. let baseAggregation = Page
  737. .aggregate([
  738. {
  739. $match: filter,
  740. },
  741. {
  742. $project: { // minimize data to fetch
  743. _id: 1,
  744. path: 1,
  745. },
  746. },
  747. ]);
  748. // limit pages to get
  749. if (total > PAGES_LIMIT) {
  750. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  751. }
  752. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  753. // use batch stream
  754. const batchStream = createBatchStream(BATCH_SIZE);
  755. let countPages = 0;
  756. let shouldContinue = true;
  757. // migrate all siblings for each page
  758. const migratePagesStream = new Writable({
  759. objectMode: true,
  760. async write(pages, encoding, callback) {
  761. // make list to create empty pages
  762. const parentPathsSet = new Set(pages.map(page => pathlib.dirname(page.path)));
  763. const parentPaths = Array.from(parentPathsSet);
  764. // fill parents with empty pages
  765. await Page.createEmptyPagesByPaths(parentPaths);
  766. // find parents again
  767. const builder = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }));
  768. const parents = await builder
  769. .addConditionToListByPathsArray(parentPaths)
  770. .query
  771. .lean()
  772. .exec();
  773. // bulkWrite to update parent
  774. const updateManyOperations = parents.map((parent) => {
  775. const parentId = parent._id;
  776. // modify to adjust for RegExp
  777. let parentPath = parent.path === '/' ? '' : parent.path;
  778. // inject \ before brackets
  779. ['(', ')', '[', ']', '{', '}'].forEach((bracket) => {
  780. parentPath = parentPath.replace(bracket, `\\${bracket}`);
  781. });
  782. return {
  783. updateMany: {
  784. filter: {
  785. // regexr.com/6889f
  786. // ex. /parent/any_child OR /any_level1
  787. path: { $regex: new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`, 'g') },
  788. },
  789. update: {
  790. parent: parentId,
  791. },
  792. },
  793. };
  794. });
  795. try {
  796. const res = await Page.bulkWrite(updateManyOperations);
  797. countPages += res.result.nModified;
  798. logger.info(`Page migration processing: (count=${countPages})`);
  799. // throw
  800. if (res.result.writeErrors.length > 0) {
  801. logger.error('Failed to migrate some pages', res.result.writeErrors);
  802. throw Error('Failed to migrate some pages');
  803. }
  804. // finish migration
  805. if (res.result.nModified === 0) { // TODO: find the best property to count updated documents
  806. shouldContinue = false;
  807. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  808. }
  809. }
  810. catch (err) {
  811. logger.error('Failed to update page.parent.', err);
  812. throw err;
  813. }
  814. callback();
  815. },
  816. final(callback) {
  817. callback();
  818. },
  819. });
  820. pagesStream
  821. .pipe(batchStream)
  822. .pipe(migratePagesStream);
  823. await streamToPromise(migratePagesStream);
  824. if (await Page.exists(filter) && shouldContinue) {
  825. return this._v5RecursiveMigration(grant, regexps);
  826. }
  827. }
  828. async _v5NormalizeIndex(isPathIndexExists) {
  829. const collection = mongoose.connection.collection('pages');
  830. if (isPathIndexExists) {
  831. try {
  832. // drop pages.path_1 indexes
  833. await collection.dropIndex('path_1');
  834. logger.info('Succeeded to drop unique indexes from pages.path.');
  835. }
  836. catch (err) {
  837. logger.warn('Failed to drop unique indexes from pages.path.', err);
  838. throw err;
  839. }
  840. }
  841. try {
  842. // create indexes without
  843. await collection.createIndex({ path: 1 }, { unique: false });
  844. logger.info('Succeeded to create non-unique indexes on pages.path.');
  845. }
  846. catch (err) {
  847. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  848. throw err;
  849. }
  850. }
  851. async v5MigratablePrivatePagesCount(user) {
  852. if (user == null) {
  853. throw Error('user is required');
  854. }
  855. const Page = this.crowi.model('Page');
  856. return Page.count({ parent: null, creator: user, grant: { $ne: Page.GRANT_PUBLIC } });
  857. }
  858. }
  859. module.exports = PageService;