page.js 34 KB

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