page.js 39 KB

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