page.js 40 KB

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