page.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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 _setV5IndexNormalizationStatus(status) {
  715. try {
  716. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  717. 'app:v5IndexNormalizationStatus': status,
  718. });
  719. }
  720. catch (err) {
  721. logger.error(`Failed to update app:v5IndexNormalizationStatus to ${status} .`);
  722. throw err;
  723. }
  724. }
  725. async _isPagePathIndexUnique() {
  726. const Page = this.crowi.model('Page');
  727. const now = (new Date()).toString();
  728. const path = `growi_check_is_path_index_unique_${now}`;
  729. let isUnique = false;
  730. try {
  731. await Page.insertMany([
  732. { path },
  733. { path },
  734. ]);
  735. }
  736. catch (err) {
  737. if (err?.code === 11000) {
  738. isUnique = true;
  739. logger.info('Page path index is unique.');
  740. }
  741. else {
  742. logger.error('Error occurred while checking index uniqueness.', err);
  743. throw err;
  744. }
  745. }
  746. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  747. return isUnique;
  748. }
  749. async v5InitialMigration(grant) {
  750. // const socket = this.crowi.socketIoService.getAdminSocket();
  751. const status = this.crowi.configManager.getConfig('crowi', 'app:v5IndexNormalizationStatus');
  752. // avoid re-running many times
  753. const isProcessing = status === 'processing';
  754. if (isProcessing) {
  755. return;
  756. }
  757. const isUnique = await this._isPagePathIndexUnique();
  758. const isProcessable = status === 'processable' || status == null;
  759. // drop unique index first
  760. if (isUnique && isProcessable) {
  761. await this._setV5IndexNormalizationStatus('processing');
  762. try {
  763. await this._v5NormalizeIndex();
  764. await this._setV5IndexNormalizationStatus('processable');
  765. }
  766. catch (err) {
  767. logger.error('V5 index normalization failed.', err);
  768. // socket.emit('v5IndexNormalizationFailed', { error: err.message });
  769. await this._setV5IndexNormalizationStatus('processable');
  770. throw err;
  771. }
  772. }
  773. // then migrate
  774. try {
  775. await this._v5RecursiveMigration(grant, null, true);
  776. }
  777. catch (err) {
  778. logger.error('V5 initial miration failed.', err);
  779. // socket.emit('v5InitialMirationFailed', { error: err.message });
  780. throw err;
  781. }
  782. await this._setIsV5CompatibleTrue();
  783. }
  784. /*
  785. * returns an array of js RegExp instance instead of RE2 instance for mongo filter
  786. */
  787. async _generateRegExpsByPageIds(pageIds) {
  788. const Page = mongoose.model('Page');
  789. let result;
  790. try {
  791. result = await Page.findListByPageIds(pageIds, null, false);
  792. }
  793. catch (err) {
  794. logger.error('Failed to find pages by ids', err);
  795. throw err;
  796. }
  797. const { pages } = result;
  798. const regexps = pages.map(page => new RegExp(`^${page.path}`));
  799. return regexps;
  800. }
  801. async _setIsV5CompatibleTrue() {
  802. try {
  803. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  804. 'app:isV5Compatible': true,
  805. });
  806. logger.info('Successfully migrated all public pages.');
  807. }
  808. catch (err) {
  809. logger.warn('Failed to update app:isV5Compatible to true.');
  810. throw err;
  811. }
  812. }
  813. // TODO: use websocket to show progress
  814. async _v5RecursiveMigration(grant, regexps, publicOnly = false) {
  815. const BATCH_SIZE = 100;
  816. const PAGES_LIMIT = 1000;
  817. const Page = this.crowi.model('Page');
  818. const { PageQueryBuilder } = Page;
  819. // generate filter
  820. let filter = {
  821. parent: null,
  822. path: { $ne: '/' },
  823. };
  824. if (grant != null) {
  825. filter = {
  826. ...filter,
  827. grant,
  828. };
  829. }
  830. if (regexps != null && regexps.length !== 0) {
  831. filter = {
  832. ...filter,
  833. path: {
  834. $in: regexps,
  835. },
  836. };
  837. }
  838. const total = await Page.countDocuments(filter);
  839. let baseAggregation = Page
  840. .aggregate([
  841. {
  842. $match: filter,
  843. },
  844. {
  845. $project: { // minimize data to fetch
  846. _id: 1,
  847. path: 1,
  848. },
  849. },
  850. ]);
  851. // limit pages to get
  852. if (total > PAGES_LIMIT) {
  853. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  854. }
  855. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  856. // use batch stream
  857. const batchStream = createBatchStream(BATCH_SIZE);
  858. let countPages = 0;
  859. let shouldContinue = true;
  860. // migrate all siblings for each page
  861. const migratePagesStream = new Writable({
  862. objectMode: true,
  863. async write(pages, encoding, callback) {
  864. // make list to create empty pages
  865. const parentPathsSet = new Set(pages.map(page => pathlib.dirname(page.path)));
  866. const parentPaths = Array.from(parentPathsSet);
  867. // fill parents with empty pages
  868. await Page.createEmptyPagesByPaths(parentPaths, publicOnly);
  869. // find parents again
  870. const builder = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }), true);
  871. const parents = await builder
  872. .addConditionToListByPathsArray(parentPaths)
  873. .query
  874. .lean()
  875. .exec();
  876. // bulkWrite to update parent
  877. const updateManyOperations = parents.map((parent) => {
  878. const parentId = parent._id;
  879. // modify to adjust for RegExp
  880. let parentPath = parent.path === '/' ? '' : parent.path;
  881. // inject \ before brackets
  882. ['(', ')', '[', ']', '{', '}'].forEach((bracket) => {
  883. parentPath = parentPath.replace(bracket, `\\${bracket}`);
  884. });
  885. const filter = {
  886. // regexr.com/6889f
  887. // ex. /parent/any_child OR /any_level1
  888. path: { $regex: new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`, 'g') },
  889. };
  890. if (grant != null) {
  891. filter.grant = grant;
  892. }
  893. return {
  894. updateMany: {
  895. filter,
  896. update: {
  897. parent: parentId,
  898. },
  899. },
  900. };
  901. });
  902. try {
  903. const res = await Page.bulkWrite(updateManyOperations);
  904. countPages += res.result.nModified;
  905. logger.info(`Page migration processing: (count=${countPages})`);
  906. // throw
  907. if (res.result.writeErrors.length > 0) {
  908. logger.error('Failed to migrate some pages', res.result.writeErrors);
  909. throw Error('Failed to migrate some pages');
  910. }
  911. // finish migration
  912. if (res.result.nModified === 0) { // TODO: find the best property to count updated documents
  913. shouldContinue = false;
  914. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  915. }
  916. }
  917. catch (err) {
  918. logger.error('Failed to update page.parent.', err);
  919. throw err;
  920. }
  921. callback();
  922. },
  923. final(callback) {
  924. callback();
  925. },
  926. });
  927. pagesStream
  928. .pipe(batchStream)
  929. .pipe(migratePagesStream);
  930. await streamToPromise(migratePagesStream);
  931. if (await Page.exists(filter) && shouldContinue) {
  932. return this._v5RecursiveMigration(grant, regexps, publicOnly);
  933. }
  934. }
  935. async _v5NormalizeIndex() {
  936. const collection = mongoose.connection.collection('pages');
  937. try {
  938. // drop pages.path_1 indexes
  939. await collection.dropIndex('path_1');
  940. logger.info('Succeeded to drop unique indexes from pages.path.');
  941. }
  942. catch (err) {
  943. logger.warn('Failed to drop unique indexes from pages.path.', err);
  944. throw err;
  945. }
  946. try {
  947. // create indexes without
  948. await collection.createIndex({ path: 1 }, { unique: false });
  949. logger.info('Succeeded to create non-unique indexes on pages.path.');
  950. }
  951. catch (err) {
  952. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  953. throw err;
  954. }
  955. }
  956. async v5MigratablePrivatePagesCount(user) {
  957. if (user == null) {
  958. throw Error('user is required');
  959. }
  960. const Page = this.crowi.model('Page');
  961. return Page.count({ parent: null, creator: user, grant: { $ne: Page.GRANT_PUBLIC } });
  962. }
  963. }
  964. module.exports = PageService;