page.ts 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. import { pagePathUtils } from '@growi/core';
  2. import mongoose from 'mongoose';
  3. import escapeStringRegexp from 'escape-string-regexp';
  4. import streamToPromise from 'stream-to-promise';
  5. import pathlib from 'path';
  6. import { Writable } from 'stream';
  7. import { serializePageSecurely } from '../models/serializers/page-serializer';
  8. import { createBatchStream } from '~/server/util/batch-stream';
  9. import loggerFactory from '~/utils/logger';
  10. import {
  11. CreateMethod, generateGrantCondition, PageCreateOptions, PageModel,
  12. } from '~/server/models/page';
  13. import { stringifySnapshot } from '~/models/serializers/in-app-notification-snapshot/page';
  14. import ActivityDefine from '../util/activityDefine';
  15. import { IPage } from '~/interfaces/page';
  16. const debug = require('debug')('growi:services:page');
  17. const logger = loggerFactory('growi:services:page');
  18. const {
  19. isCreatablePage, isDeletablePage, isTrashPage, collectAncestorPaths, isTopPage,
  20. } = pagePathUtils;
  21. const BULK_REINDEX_SIZE = 100;
  22. class PageService {
  23. crowi: any;
  24. pageEvent: any;
  25. tagEvent: any;
  26. constructor(crowi) {
  27. this.crowi = crowi;
  28. this.pageEvent = crowi.event('page');
  29. this.tagEvent = crowi.event('tag');
  30. // init
  31. this.initPageEvent();
  32. }
  33. private initPageEvent() {
  34. // create
  35. this.pageEvent.on('create', this.pageEvent.onCreate);
  36. // createMany
  37. this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
  38. this.pageEvent.on('addSeenUsers', this.pageEvent.onAddSeenUsers);
  39. // update
  40. this.pageEvent.on('update', async(page, user) => {
  41. this.pageEvent.onUpdate();
  42. try {
  43. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_UPDATE);
  44. }
  45. catch (err) {
  46. logger.error(err);
  47. }
  48. });
  49. // rename
  50. this.pageEvent.on('rename', async(page, user) => {
  51. try {
  52. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_RENAME);
  53. }
  54. catch (err) {
  55. logger.error(err);
  56. }
  57. });
  58. // delete
  59. this.pageEvent.on('delete', async(page, user) => {
  60. try {
  61. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_DELETE);
  62. }
  63. catch (err) {
  64. logger.error(err);
  65. }
  66. });
  67. // delete completely
  68. this.pageEvent.on('deleteCompletely', async(page, user) => {
  69. try {
  70. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_DELETE_COMPLETELY);
  71. }
  72. catch (err) {
  73. logger.error(err);
  74. }
  75. });
  76. // likes
  77. this.pageEvent.on('like', async(page, user) => {
  78. try {
  79. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_LIKE);
  80. }
  81. catch (err) {
  82. logger.error(err);
  83. }
  84. });
  85. // bookmark
  86. this.pageEvent.on('bookmark', async(page, user) => {
  87. try {
  88. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_BOOKMARK);
  89. }
  90. catch (err) {
  91. logger.error(err);
  92. }
  93. });
  94. }
  95. async findPageAndMetaDataByViewer({ pageId, path, user }) {
  96. const Page = this.crowi.model('Page');
  97. let page;
  98. if (pageId != null) { // prioritized
  99. page = await Page.findByIdAndViewer(pageId, user);
  100. }
  101. else {
  102. page = await Page.findByPathAndViewer(path, user);
  103. }
  104. const result: any = {};
  105. if (page == null) {
  106. const isExist = await Page.count({ $or: [{ _id: pageId }, { path }] }) > 0;
  107. result.isForbidden = isExist;
  108. result.isNotFound = !isExist;
  109. result.isCreatable = isCreatablePage(path);
  110. result.isDeletable = false;
  111. result.canDeleteCompletely = false;
  112. result.page = page;
  113. return result;
  114. }
  115. result.page = page;
  116. result.isForbidden = false;
  117. result.isNotFound = false;
  118. result.isCreatable = false;
  119. result.isDeletable = isDeletablePage(path);
  120. result.isDeleted = page.isDeleted();
  121. result.canDeleteCompletely = user != null && user.canDeleteCompletely(page.creator);
  122. return result;
  123. }
  124. private shouldUseV4Process(page): boolean {
  125. const Page = mongoose.model('Page') as unknown as PageModel;
  126. const isPageMigrated = page.parent != null;
  127. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  128. const isRoot = isTopPage(page.path);
  129. const isPageRestricted = page.grant === Page.GRANT_RESTRICTED;
  130. const shouldUseV4Process = !isRoot && !isPageRestricted && (!isV5Compatible || !isPageMigrated);
  131. return shouldUseV4Process;
  132. }
  133. private shouldNormalizeParent(page) {
  134. const Page = mongoose.model('Page') as unknown as PageModel;
  135. return page.grant !== Page.GRANT_RESTRICTED && page.grant !== Page.GRANT_SPECIFIED;
  136. }
  137. /**
  138. * go back by using redirectTo and return the paths
  139. * ex: when
  140. * '/page1' redirects to '/page2' and
  141. * '/page2' redirects to '/page3'
  142. * and given '/page3',
  143. * '/page1' and '/page2' will be return
  144. *
  145. * @param {string} redirectTo
  146. * @param {object} redirectToPagePathMapping
  147. * @param {array} pagePaths
  148. */
  149. private prepareShoudDeletePagesByRedirectTo(redirectTo, redirectToPagePathMapping, pagePaths: any[] = []) {
  150. const pagePath = redirectToPagePathMapping[redirectTo];
  151. if (pagePath == null) {
  152. return pagePaths;
  153. }
  154. pagePaths.push(pagePath);
  155. return this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping, pagePaths);
  156. }
  157. /**
  158. * Generate read stream to operate descendants of the specified page path
  159. * @param {string} targetPagePath
  160. * @param {User} viewer
  161. */
  162. private async generateReadStreamToOperateOnlyDescendants(targetPagePath, userToOperate) {
  163. const Page = this.crowi.model('Page');
  164. const { PageQueryBuilder } = Page;
  165. const builder = new PageQueryBuilder(Page.find(), true)
  166. .addConditionToExcludeRedirect()
  167. .addConditionToListOnlyDescendants(targetPagePath);
  168. await Page.addConditionToFilteringByViewerToEdit(builder, userToOperate);
  169. return builder
  170. .query
  171. .lean()
  172. .cursor({ batchSize: BULK_REINDEX_SIZE });
  173. }
  174. async renamePage(page, newPagePath, user, options) {
  175. const Page = this.crowi.model('Page');
  176. // v4 compatible process
  177. const shouldUseV4Process = this.shouldUseV4Process(page);
  178. if (shouldUseV4Process) {
  179. return this.renamePageV4(page, newPagePath, user, options);
  180. }
  181. const updateMetadata = options.updateMetadata || false;
  182. // sanitize path
  183. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  184. // use the parent's grant when target page is an empty page
  185. let grant;
  186. let grantedUserIds;
  187. let grantedGroupId;
  188. if (page.isEmpty) {
  189. const parent = await Page.findOne({ _id: page.parent });
  190. if (parent == null) {
  191. throw Error('parent not found');
  192. }
  193. grant = parent.grant;
  194. grantedUserIds = parent.grantedUsers;
  195. grantedGroupId = parent.grantedGroup;
  196. }
  197. else {
  198. grant = page.grant;
  199. grantedUserIds = page.grantedUsers;
  200. grantedGroupId = page.grantedGroup;
  201. }
  202. /*
  203. * UserGroup & Owner validation
  204. */
  205. if (grant !== Page.GRANT_RESTRICTED) {
  206. let isGrantNormalized = false;
  207. try {
  208. const shouldCheckDescendants = false;
  209. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(newPagePath, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  210. }
  211. catch (err) {
  212. logger.error(`Failed to validate grant of page at "${newPagePath}" when renaming`, err);
  213. throw err;
  214. }
  215. if (!isGrantNormalized) {
  216. throw Error(`This page cannot be renamed to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  217. }
  218. }
  219. // update descendants first
  220. await this.renameDescendantsWithStream(page, newPagePath, user, options, shouldUseV4Process);
  221. /*
  222. * TODO: https://redmine.weseek.co.jp/issues/86577
  223. * bulkWrite PageRedirectDocument if createRedirectPage is true
  224. */
  225. /*
  226. * update target
  227. */
  228. const update: Partial<IPage> = {};
  229. // find or create parent
  230. const newParent = await Page.getParentAndFillAncestors(newPagePath);
  231. // update Page
  232. update.path = newPagePath;
  233. update.parent = newParent._id;
  234. if (updateMetadata) {
  235. update.lastUpdateUser = user;
  236. update.updatedAt = new Date();
  237. }
  238. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  239. this.pageEvent.emit('rename', page, user);
  240. return renamedPage;
  241. }
  242. // !!renaming always include descendant pages!!
  243. private async renamePageV4(page, newPagePath, user, options) {
  244. const Page = this.crowi.model('Page');
  245. const Revision = this.crowi.model('Revision');
  246. const updateMetadata = options.updateMetadata || false;
  247. // sanitize path
  248. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  249. // create descendants first
  250. await this.renameDescendantsWithStream(page, newPagePath, user, options);
  251. const update: any = {};
  252. // update Page
  253. update.path = newPagePath;
  254. if (updateMetadata) {
  255. update.lastUpdateUser = user;
  256. update.updatedAt = Date.now();
  257. }
  258. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  259. // update Rivisions
  260. await Revision.updateRevisionListByPageId(renamedPage._id, { pageId: renamedPage._id });
  261. /*
  262. * TODO: https://redmine.weseek.co.jp/issues/86577
  263. * bulkWrite PageRedirectDocument if createRedirectPage is true
  264. */
  265. this.pageEvent.emit('rename', page, user);
  266. return renamedPage;
  267. }
  268. private async renameDescendants(pages, user, options, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = false) {
  269. // v4 compatible process
  270. if (shouldUseV4Process) {
  271. return this.renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix);
  272. }
  273. const Page = this.crowi.model('Page');
  274. const { updateMetadata } = options;
  275. const updatePathOperations: any[] = [];
  276. pages.forEach((page) => {
  277. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  278. // increment updatePathOperations
  279. let update;
  280. if (updateMetadata && !page.isEmpty) {
  281. update = {
  282. $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() },
  283. };
  284. }
  285. else {
  286. update = {
  287. $set: { path: newPagePath },
  288. };
  289. }
  290. updatePathOperations.push({
  291. updateOne: {
  292. filter: {
  293. _id: page._id,
  294. },
  295. update,
  296. },
  297. });
  298. });
  299. try {
  300. await Page.bulkWrite(updatePathOperations);
  301. }
  302. catch (err) {
  303. if (err.code !== 11000) {
  304. throw new Error(`Failed to rename pages: ${err}`);
  305. }
  306. }
  307. this.pageEvent.emit('updateMany', pages, user);
  308. }
  309. private async renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix) {
  310. const pageCollection = mongoose.connection.collection('pages');
  311. const { updateMetadata } = options;
  312. const unorderedBulkOp = pageCollection.initializeUnorderedBulkOp();
  313. pages.forEach((page) => {
  314. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  315. if (updateMetadata) {
  316. unorderedBulkOp
  317. .find({ _id: page._id })
  318. .update({ $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() } });
  319. }
  320. else {
  321. unorderedBulkOp.find({ _id: page._id }).update({ $set: { path: newPagePath } });
  322. }
  323. });
  324. try {
  325. await unorderedBulkOp.execute();
  326. }
  327. catch (err) {
  328. if (err.code !== 11000) {
  329. throw new Error(`Failed to rename pages: ${err}`);
  330. }
  331. }
  332. this.pageEvent.emit('updateMany', pages, user);
  333. }
  334. private async renameDescendantsWithStream(targetPage, newPagePath, user, options = {}, shouldUseV4Process = false) {
  335. // v4 compatible process
  336. if (shouldUseV4Process) {
  337. return this.renameDescendantsWithStreamV4(targetPage, newPagePath, user, options);
  338. }
  339. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  340. const newPagePathPrefix = newPagePath;
  341. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  342. const renameDescendants = this.renameDescendants.bind(this);
  343. const pageEvent = this.pageEvent;
  344. let count = 0;
  345. const writeStream = new Writable({
  346. objectMode: true,
  347. async write(batch, encoding, callback) {
  348. try {
  349. count += batch.length;
  350. await renameDescendants(
  351. batch, user, options, pathRegExp, newPagePathPrefix, shouldUseV4Process,
  352. );
  353. logger.debug(`Renaming pages progressing: (count=${count})`);
  354. }
  355. catch (err) {
  356. logger.error('Renaming error on add anyway: ', err);
  357. }
  358. callback();
  359. },
  360. async final(callback) {
  361. logger.debug(`Renaming pages has completed: (totalCount=${count})`);
  362. // update path
  363. targetPage.path = newPagePath;
  364. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  365. callback();
  366. },
  367. });
  368. readStream
  369. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  370. .pipe(writeStream);
  371. await streamToPromise(readStream);
  372. }
  373. private async renameDescendantsWithStreamV4(targetPage, newPagePath, user, options = {}) {
  374. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  375. const newPagePathPrefix = newPagePath;
  376. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  377. const renameDescendants = this.renameDescendants.bind(this);
  378. const pageEvent = this.pageEvent;
  379. let count = 0;
  380. const writeStream = new Writable({
  381. objectMode: true,
  382. async write(batch, encoding, callback) {
  383. try {
  384. count += batch.length;
  385. await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
  386. logger.debug(`Reverting pages progressing: (count=${count})`);
  387. }
  388. catch (err) {
  389. logger.error('revertPages error on add anyway: ', err);
  390. }
  391. callback();
  392. },
  393. final(callback) {
  394. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  395. // update path
  396. targetPage.path = newPagePath;
  397. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  398. callback();
  399. },
  400. });
  401. readStream
  402. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  403. .pipe(writeStream);
  404. await streamToPromise(readStream);
  405. }
  406. /*
  407. * Duplicate
  408. */
  409. async duplicate(page, newPagePath, user, isRecursively) {
  410. const Page = mongoose.model('Page') as unknown as PageModel;
  411. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  412. // v4 compatible process
  413. const shouldUseV4Process = this.shouldUseV4Process(page);
  414. if (shouldUseV4Process) {
  415. return this.duplicateV4(page, newPagePath, user, isRecursively);
  416. }
  417. // use the parent's grant when target page is an empty page
  418. let grant;
  419. let grantedUserIds;
  420. let grantedGroupId;
  421. if (page.isEmpty) {
  422. const parent = await Page.findOne({ _id: page.parent });
  423. if (parent == null) {
  424. throw Error('parent not found');
  425. }
  426. grant = parent.grant;
  427. grantedUserIds = parent.grantedUsers;
  428. grantedGroupId = parent.grantedGroup;
  429. }
  430. else {
  431. grant = page.grant;
  432. grantedUserIds = page.grantedUsers;
  433. grantedGroupId = page.grantedGroup;
  434. }
  435. /*
  436. * UserGroup & Owner validation
  437. */
  438. if (grant !== Page.GRANT_RESTRICTED) {
  439. let isGrantNormalized = false;
  440. try {
  441. const shouldCheckDescendants = false;
  442. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(newPagePath, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  443. }
  444. catch (err) {
  445. logger.error(`Failed to validate grant of page at "${newPagePath}" when duplicating`, err);
  446. throw err;
  447. }
  448. if (!isGrantNormalized) {
  449. throw Error(`This page cannot be duplicated to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  450. }
  451. }
  452. // populate
  453. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  454. // create option
  455. const options: PageCreateOptions = {
  456. grant: page.grant,
  457. grantUserGroupId: page.grantedGroup,
  458. };
  459. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  460. const createdPage = await (Page.create as CreateMethod)(
  461. newPagePath, page.revision.body, user, options,
  462. );
  463. if (isRecursively) {
  464. this.duplicateDescendantsWithStream(page, newPagePath, user, shouldUseV4Process);
  465. }
  466. // take over tags
  467. const originTags = await page.findRelatedTagsById();
  468. let savedTags = [];
  469. if (originTags.length !== 0) {
  470. await PageTagRelation.updatePageTags(createdPage._id, originTags);
  471. savedTags = await PageTagRelation.listTagNamesByPage(createdPage._id);
  472. this.tagEvent.emit('update', createdPage, savedTags);
  473. }
  474. const result = serializePageSecurely(createdPage);
  475. result.tags = savedTags;
  476. return result;
  477. }
  478. async duplicateV4(page, newPagePath, user, isRecursively) {
  479. const Page = this.crowi.model('Page');
  480. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  481. // populate
  482. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  483. // create option
  484. const options: any = { page };
  485. options.grant = page.grant;
  486. options.grantUserGroupId = page.grantedGroup;
  487. options.grantedUserIds = page.grantedUsers;
  488. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  489. const createdPage = await Page.create(
  490. newPagePath, page.revision.body, user, options,
  491. );
  492. if (isRecursively) {
  493. this.duplicateDescendantsWithStream(page, newPagePath, user);
  494. }
  495. // take over tags
  496. const originTags = await page.findRelatedTagsById();
  497. let savedTags = [];
  498. if (originTags != null) {
  499. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  500. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  501. this.tagEvent.emit('update', createdPage, savedTags);
  502. }
  503. const result = serializePageSecurely(createdPage);
  504. result.tags = savedTags;
  505. return result;
  506. }
  507. /**
  508. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  509. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  510. */
  511. private async duplicateTags(pageIdMapping) {
  512. const PageTagRelation = mongoose.model('PageTagRelation');
  513. // convert pageId from string to ObjectId
  514. const pageIds = Object.keys(pageIdMapping);
  515. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: new mongoose.Types.ObjectId(pageId) } }) };
  516. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  517. {
  518. $match: stage,
  519. },
  520. {
  521. $group: {
  522. _id: '$relatedTag',
  523. relatedPages: { $push: '$relatedPage' },
  524. },
  525. },
  526. ]);
  527. const newPageTagRelation: any[] = [];
  528. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  529. // relatedPages
  530. relatedPages.forEach((pageId) => {
  531. newPageTagRelation.push({
  532. relatedPage: pageIdMapping[pageId], // newPageId
  533. relatedTag: _id,
  534. });
  535. });
  536. });
  537. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  538. }
  539. private async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = false) {
  540. if (shouldUseV4Process) {
  541. return this.duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix);
  542. }
  543. const Page = this.crowi.model('Page');
  544. const Revision = this.crowi.model('Revision');
  545. const pageIds = pages.map(page => page._id);
  546. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  547. // Mapping to set to the body of the new revision
  548. const pageIdRevisionMapping = {};
  549. revisions.forEach((revision) => {
  550. pageIdRevisionMapping[revision.pageId] = revision;
  551. });
  552. // key: oldPageId, value: newPageId
  553. const pageIdMapping = {};
  554. const newPages: any[] = [];
  555. const newRevisions: any[] = [];
  556. // no need to save parent here
  557. pages.forEach((page) => {
  558. const newPageId = new mongoose.Types.ObjectId();
  559. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  560. const revisionId = new mongoose.Types.ObjectId();
  561. pageIdMapping[page._id] = newPageId;
  562. let newPage;
  563. if (page.isEmpty) {
  564. newPage = {
  565. _id: newPageId,
  566. path: newPagePath,
  567. isEmpty: true,
  568. };
  569. }
  570. else {
  571. newPage = {
  572. _id: newPageId,
  573. path: newPagePath,
  574. creator: user._id,
  575. grant: page.grant,
  576. grantedGroup: page.grantedGroup,
  577. grantedUsers: page.grantedUsers,
  578. lastUpdateUser: user._id,
  579. revision: revisionId,
  580. };
  581. }
  582. newPages.push(newPage);
  583. newRevisions.push({
  584. _id: revisionId, path: newPagePath, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  585. });
  586. });
  587. await Page.insertMany(newPages, { ordered: false });
  588. await Revision.insertMany(newRevisions, { ordered: false });
  589. await this.duplicateTags(pageIdMapping);
  590. }
  591. private async duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  592. const Page = this.crowi.model('Page');
  593. const Revision = this.crowi.model('Revision');
  594. const pageIds = pages.map(page => page._id);
  595. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  596. // Mapping to set to the body of the new revision
  597. const pageIdRevisionMapping = {};
  598. revisions.forEach((revision) => {
  599. pageIdRevisionMapping[revision.pageId] = revision;
  600. });
  601. // key: oldPageId, value: newPageId
  602. const pageIdMapping = {};
  603. const newPages: any[] = [];
  604. const newRevisions: any[] = [];
  605. pages.forEach((page) => {
  606. const newPageId = new mongoose.Types.ObjectId();
  607. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  608. const revisionId = new mongoose.Types.ObjectId();
  609. pageIdMapping[page._id] = newPageId;
  610. newPages.push({
  611. _id: newPageId,
  612. path: newPagePath,
  613. creator: user._id,
  614. grant: page.grant,
  615. grantedGroup: page.grantedGroup,
  616. grantedUsers: page.grantedUsers,
  617. lastUpdateUser: user._id,
  618. revision: revisionId,
  619. });
  620. newRevisions.push({
  621. _id: revisionId, path: newPagePath, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  622. });
  623. });
  624. await Page.insertMany(newPages, { ordered: false });
  625. await Revision.insertMany(newRevisions, { ordered: false });
  626. await this.duplicateTags(pageIdMapping);
  627. }
  628. private async duplicateDescendantsWithStream(page, newPagePath, user, shouldUseV4Process = true) {
  629. if (shouldUseV4Process) {
  630. return this.duplicateDescendantsWithStreamV4(page, newPagePath, user);
  631. }
  632. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  633. const newPagePathPrefix = newPagePath;
  634. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  635. const duplicateDescendants = this.duplicateDescendants.bind(this);
  636. const shouldNormalizeParent = this.shouldNormalizeParent.bind(this);
  637. const normalizeParentRecursively = this.normalizeParentRecursively.bind(this);
  638. const pageEvent = this.pageEvent;
  639. let count = 0;
  640. const writeStream = new Writable({
  641. objectMode: true,
  642. async write(batch, encoding, callback) {
  643. try {
  644. count += batch.length;
  645. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, shouldUseV4Process);
  646. logger.debug(`Adding pages progressing: (count=${count})`);
  647. }
  648. catch (err) {
  649. logger.error('addAllPages error on add anyway: ', err);
  650. }
  651. callback();
  652. },
  653. async final(callback) {
  654. const Page = mongoose.model('Page') as unknown as PageModel;
  655. // normalize parent of descendant pages
  656. const shouldNormalize = shouldNormalizeParent(page);
  657. if (shouldNormalize) {
  658. try {
  659. const escapedPath = escapeStringRegexp(newPagePath);
  660. const regexps = [new RegExp(`^${escapedPath}`, 'i')];
  661. await normalizeParentRecursively(null, regexps);
  662. logger.info(`Successfully normalized duplicated descendant pages under "${newPagePath}"`);
  663. }
  664. catch (err) {
  665. logger.error('Failed to normalize descendants afrer duplicate:', err);
  666. throw err;
  667. }
  668. }
  669. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  670. // update path
  671. page.path = newPagePath;
  672. pageEvent.emit('syncDescendantsUpdate', page, user);
  673. callback();
  674. },
  675. });
  676. readStream
  677. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  678. .pipe(writeStream);
  679. }
  680. private async duplicateDescendantsWithStreamV4(page, newPagePath, user) {
  681. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  682. const newPagePathPrefix = newPagePath;
  683. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  684. const duplicateDescendants = this.duplicateDescendants.bind(this);
  685. const pageEvent = this.pageEvent;
  686. let count = 0;
  687. const writeStream = new Writable({
  688. objectMode: true,
  689. async write(batch, encoding, callback) {
  690. try {
  691. count += batch.length;
  692. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix);
  693. logger.debug(`Adding pages progressing: (count=${count})`);
  694. }
  695. catch (err) {
  696. logger.error('addAllPages error on add anyway: ', err);
  697. }
  698. callback();
  699. },
  700. final(callback) {
  701. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  702. // update path
  703. page.path = newPagePath;
  704. pageEvent.emit('syncDescendantsUpdate', page, user);
  705. callback();
  706. },
  707. });
  708. readStream
  709. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  710. .pipe(writeStream);
  711. }
  712. /*
  713. * Delete
  714. */
  715. async deletePage(page, user, options = {}, isRecursively = false) {
  716. const Page = mongoose.model('Page') as PageModel;
  717. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  718. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  719. // v4 compatible process
  720. const shouldUseV4Process = this.shouldUseV4Process(page);
  721. if (shouldUseV4Process) {
  722. return this.deletePageV4(page, user, options, isRecursively);
  723. }
  724. const newPath = Page.getDeletedPageName(page.path);
  725. const isTrashed = isTrashPage(page.path);
  726. if (isTrashed) {
  727. throw new Error('This method does NOT support deleting trashed pages.');
  728. }
  729. if (!Page.isDeletableName(page.path)) {
  730. throw new Error('Page is not deletable.');
  731. }
  732. // replace with an empty page
  733. const shouldReplace = !isRecursively && await Page.exists({ parent: page._id });
  734. if (shouldReplace) {
  735. await Page.replaceTargetWithEmptyPage(page);
  736. }
  737. if (isRecursively) {
  738. this.deleteDescendantsWithStream(page, user); // use the same process in both version v4 and v5
  739. }
  740. let deletedPage;
  741. // update Revisions
  742. if (page.isEmpty) {
  743. await Page.remove({ _id: page._id });
  744. }
  745. else {
  746. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  747. deletedPage = await Page.findByIdAndUpdate(page._id, {
  748. $set: {
  749. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, // set parent as null
  750. },
  751. }, { new: true });
  752. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  753. /*
  754. * TODO: https://redmine.weseek.co.jp/issues/86577
  755. * bulkWrite PageRedirect documents
  756. */
  757. // const body = `redirect ${newPath}`;
  758. // await Page.create(page.path, body, user, { redirectTo: newPath });
  759. this.pageEvent.emit('delete', page, user);
  760. this.pageEvent.emit('create', deletedPage, user);
  761. }
  762. return deletedPage;
  763. }
  764. private async deletePageV4(page, user, options = {}, isRecursively = false) {
  765. const Page = mongoose.model('Page') as PageModel;
  766. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  767. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  768. const newPath = Page.getDeletedPageName(page.path);
  769. const isTrashed = isTrashPage(page.path);
  770. if (isTrashed) {
  771. throw new Error('This method does NOT support deleting trashed pages.');
  772. }
  773. if (!Page.isDeletableName(page.path)) {
  774. throw new Error('Page is not deletable.');
  775. }
  776. if (isRecursively) {
  777. this.deleteDescendantsWithStream(page, user);
  778. }
  779. // update Revisions
  780. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  781. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  782. $set: {
  783. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  784. },
  785. }, { new: true });
  786. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  787. /*
  788. * TODO: https://redmine.weseek.co.jp/issues/86577
  789. * bulkWrite PageRedirect documents
  790. */
  791. // const body = `redirect ${newPath}`;
  792. // await Page.create(page.path, body, user, { redirectTo: newPath });
  793. this.pageEvent.emit('delete', page, user);
  794. this.pageEvent.emit('create', deletedPage, user);
  795. return deletedPage;
  796. }
  797. private async deleteCompletelyOperation(pageIds, pagePaths) {
  798. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  799. const Bookmark = this.crowi.model('Bookmark');
  800. const Comment = this.crowi.model('Comment');
  801. const Page = this.crowi.model('Page');
  802. const PageTagRelation = this.crowi.model('PageTagRelation');
  803. const ShareLink = this.crowi.model('ShareLink');
  804. const Revision = this.crowi.model('Revision');
  805. const Attachment = this.crowi.model('Attachment');
  806. const { attachmentService } = this.crowi;
  807. const attachments = await Attachment.find({ page: { $in: pageIds } });
  808. const pages = await Page.find({ redirectTo: { $ne: null } });
  809. const redirectToPagePathMapping = {};
  810. pages.forEach((page) => {
  811. redirectToPagePathMapping[page.redirectTo] = page.path;
  812. });
  813. const redirectedFromPagePaths: any[] = [];
  814. pagePaths.forEach((pagePath) => {
  815. redirectedFromPagePaths.push(...this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping));
  816. });
  817. return Promise.all([
  818. Bookmark.deleteMany({ page: { $in: pageIds } }),
  819. Comment.deleteMany({ page: { $in: pageIds } }),
  820. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  821. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  822. Revision.deleteMany({ path: { $in: pagePaths } }),
  823. Page.deleteMany({ $or: [{ path: { $in: pagePaths } }, { path: { $in: redirectedFromPagePaths } }, { _id: { $in: pageIds } }] }),
  824. attachmentService.removeAllAttachments(attachments),
  825. ]);
  826. }
  827. private async deleteDescendants(pages, user) {
  828. const Page = mongoose.model('Page') as PageModel;
  829. const deletePageOperations: any[] = [];
  830. pages.forEach((page) => {
  831. const newPath = Page.getDeletedPageName(page.path);
  832. let operation;
  833. // if empty, delete completely
  834. if (page.isEmpty) {
  835. operation = {
  836. deleteOne: {
  837. filter: { _id: page._id },
  838. },
  839. };
  840. }
  841. // if not empty, set parent to null and update to trash
  842. else {
  843. operation = {
  844. updateOne: {
  845. filter: { _id: page._id },
  846. update: {
  847. $set: {
  848. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, // set parent as null
  849. },
  850. },
  851. },
  852. };
  853. }
  854. deletePageOperations.push(operation);
  855. });
  856. try {
  857. await Page.bulkWrite(deletePageOperations);
  858. }
  859. catch (err) {
  860. if (err.code !== 11000) {
  861. throw new Error(`Failed to delete pages: ${err}`);
  862. }
  863. }
  864. finally {
  865. this.pageEvent.emit('syncDescendantsDelete', pages, user);
  866. }
  867. }
  868. /**
  869. * Create delete stream
  870. */
  871. private async deleteDescendantsWithStream(targetPage, user) {
  872. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  873. const deleteDescendants = this.deleteDescendants.bind(this);
  874. let count = 0;
  875. const writeStream = new Writable({
  876. objectMode: true,
  877. async write(batch, encoding, callback) {
  878. try {
  879. count += batch.length;
  880. await deleteDescendants(batch, user);
  881. logger.debug(`Reverting pages progressing: (count=${count})`);
  882. }
  883. catch (err) {
  884. logger.error('revertPages error on add anyway: ', err);
  885. }
  886. callback();
  887. },
  888. final(callback) {
  889. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  890. callback();
  891. },
  892. });
  893. readStream
  894. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  895. .pipe(writeStream);
  896. }
  897. // delete multiple pages
  898. private async deleteMultipleCompletely(pages, user, options = {}) {
  899. const ids = pages.map(page => (page._id));
  900. const paths = pages.map(page => (page.path));
  901. logger.debug('Deleting completely', paths);
  902. await this.deleteCompletelyOperation(ids, paths);
  903. this.pageEvent.emit('syncDescendantsDelete', pages, user); // update as renamed page
  904. return;
  905. }
  906. async deleteCompletely(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  907. const ids = [page._id];
  908. const paths = [page.path];
  909. logger.debug('Deleting completely', paths);
  910. await this.deleteCompletelyOperation(ids, paths);
  911. if (isRecursively) {
  912. this.deleteCompletelyDescendantsWithStream(page, user, options);
  913. }
  914. if (!preventEmitting) {
  915. this.pageEvent.emit('deleteCompletely', page, user);
  916. }
  917. return;
  918. }
  919. async emptyTrashPage(user, options = {}) {
  920. return this.deleteCompletelyDescendantsWithStream({ path: '/trash' }, user, options);
  921. }
  922. /**
  923. * Create delete completely stream
  924. */
  925. private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}) {
  926. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  927. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  928. let count = 0;
  929. const writeStream = new Writable({
  930. objectMode: true,
  931. async write(batch, encoding, callback) {
  932. try {
  933. count += batch.length;
  934. await deleteMultipleCompletely(batch, user, options);
  935. logger.debug(`Adding pages progressing: (count=${count})`);
  936. }
  937. catch (err) {
  938. logger.error('addAllPages error on add anyway: ', err);
  939. }
  940. callback();
  941. },
  942. final(callback) {
  943. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  944. callback();
  945. },
  946. });
  947. readStream
  948. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  949. .pipe(writeStream);
  950. }
  951. private async revertDeletedDescendants(pages, user) {
  952. const Page = this.crowi.model('Page');
  953. const pageCollection = mongoose.connection.collection('pages');
  954. const revisionCollection = mongoose.connection.collection('revisions');
  955. const removePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  956. const revertPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  957. const revertRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  958. // e.g. key: '/test'
  959. const pathToPageMapping = {};
  960. const toPaths = pages.map(page => Page.getRevertDeletedPageName(page.path));
  961. const toPages = await Page.find({ path: { $in: toPaths } });
  962. toPages.forEach((toPage) => {
  963. pathToPageMapping[toPage.path] = toPage;
  964. });
  965. pages.forEach((page) => {
  966. // e.g. page.path = /trash/test, toPath = /test
  967. const toPath = Page.getRevertDeletedPageName(page.path);
  968. if (pathToPageMapping[toPath] != null) {
  969. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  970. // So, it's ok to delete the page
  971. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  972. if (pathToPageMapping[toPath].redirectTo === page.path) {
  973. removePageBulkOp.find({ path: toPath }).delete();
  974. }
  975. }
  976. revertPageBulkOp.find({ _id: page._id }).update({
  977. $set: {
  978. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  979. },
  980. });
  981. revertRevisionBulkOp.find({ path: page.path }).update({ $set: { path: toPath } });
  982. });
  983. try {
  984. await removePageBulkOp.execute();
  985. await revertPageBulkOp.execute();
  986. await revertRevisionBulkOp.execute();
  987. }
  988. catch (err) {
  989. if (err.code !== 11000) {
  990. throw new Error(`Failed to revert pages: ${err}`);
  991. }
  992. }
  993. }
  994. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  995. const Page = this.crowi.model('Page');
  996. const PageTagRelation = this.crowi.model('PageTagRelation');
  997. const Revision = this.crowi.model('Revision');
  998. const newPath = Page.getRevertDeletedPageName(page.path);
  999. const originPage = await Page.findByPath(newPath);
  1000. if (originPage != null) {
  1001. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  1002. // So, it's ok to delete the page
  1003. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  1004. if (originPage.redirectTo !== page.path) {
  1005. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  1006. }
  1007. await this.deleteCompletely(originPage, user, options, false, true);
  1008. this.pageEvent.emit('revert', page, user);
  1009. }
  1010. if (isRecursively) {
  1011. this.revertDeletedDescendantsWithStream(page, user, options);
  1012. }
  1013. page.status = Page.STATUS_PUBLISHED;
  1014. page.lastUpdateUser = user;
  1015. debug('Revert deleted the page', page, newPath);
  1016. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1017. $set: {
  1018. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1019. },
  1020. }, { new: true });
  1021. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1022. await Revision.updateMany({ path: page.path }, { $set: { path: newPath } });
  1023. return updatedPage;
  1024. }
  1025. /**
  1026. * Create revert stream
  1027. */
  1028. private async revertDeletedDescendantsWithStream(targetPage, user, options = {}) {
  1029. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1030. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1031. let count = 0;
  1032. const writeStream = new Writable({
  1033. objectMode: true,
  1034. async write(batch, encoding, callback) {
  1035. try {
  1036. count += batch.length;
  1037. revertDeletedDescendants(batch, user);
  1038. logger.debug(`Reverting pages progressing: (count=${count})`);
  1039. }
  1040. catch (err) {
  1041. logger.error('revertPages error on add anyway: ', err);
  1042. }
  1043. callback();
  1044. },
  1045. final(callback) {
  1046. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1047. callback();
  1048. },
  1049. });
  1050. readStream
  1051. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1052. .pipe(writeStream);
  1053. }
  1054. async handlePrivatePagesForGroupsToDelete(groupsToDelete, action, transferToUserGroupId, user) {
  1055. const Page = this.crowi.model('Page');
  1056. const pages = await Page.find({ grantedGroup: { $in: groupsToDelete } });
  1057. switch (action) {
  1058. case 'public':
  1059. await Page.publicizePages(pages);
  1060. break;
  1061. case 'delete':
  1062. return this.deleteMultipleCompletely(pages, user);
  1063. case 'transfer':
  1064. await Page.transferPagesToGroup(pages, transferToUserGroupId);
  1065. break;
  1066. default:
  1067. throw new Error('Unknown action for private pages');
  1068. }
  1069. }
  1070. async shortBodiesMapByPageIds(pageIds: string[] = [], user) {
  1071. const Page = mongoose.model('Page');
  1072. const MAX_LENGTH = 350;
  1073. // aggregation options
  1074. const viewerCondition = await generateGrantCondition(user, null);
  1075. const filterByIds = {
  1076. _id: { $in: pageIds.map(id => new mongoose.Types.ObjectId(id)) },
  1077. };
  1078. let pages;
  1079. try {
  1080. pages = await Page
  1081. .aggregate([
  1082. // filter by pageIds
  1083. {
  1084. $match: filterByIds,
  1085. },
  1086. // filter by viewer
  1087. viewerCondition,
  1088. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  1089. {
  1090. $lookup: {
  1091. from: 'revisions',
  1092. let: { localRevision: '$revision' },
  1093. pipeline: [
  1094. {
  1095. $match: {
  1096. $expr: {
  1097. $eq: ['$_id', '$$localRevision'],
  1098. },
  1099. },
  1100. },
  1101. {
  1102. $project: {
  1103. // What is $substrCP?
  1104. // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
  1105. revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
  1106. },
  1107. },
  1108. ],
  1109. as: 'revisionData',
  1110. },
  1111. },
  1112. // projection
  1113. {
  1114. $project: {
  1115. _id: 1,
  1116. revisionData: 1,
  1117. },
  1118. },
  1119. ]).exec();
  1120. }
  1121. catch (err) {
  1122. logger.error('Error occurred while generating shortBodiesMap');
  1123. throw err;
  1124. }
  1125. const shortBodiesMap = {};
  1126. pages.forEach((page) => {
  1127. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  1128. });
  1129. return shortBodiesMap;
  1130. }
  1131. private async createAndSendNotifications(page, user, action) {
  1132. const { activityService, inAppNotificationService } = this.crowi;
  1133. const snapshot = stringifySnapshot(page);
  1134. // Create activity
  1135. const parameters = {
  1136. user: user._id,
  1137. targetModel: ActivityDefine.MODEL_PAGE,
  1138. target: page,
  1139. action,
  1140. };
  1141. const activity = await activityService.createByParameters(parameters);
  1142. // Get user to be notified
  1143. const targetUsers = await activity.getNotificationTargetUsers();
  1144. // Create and send notifications
  1145. await inAppNotificationService.upsertByActivity(targetUsers, activity, snapshot);
  1146. await inAppNotificationService.emitSocketIo(targetUsers);
  1147. }
  1148. async v5MigrationByPageIds(pageIds) {
  1149. const Page = mongoose.model('Page');
  1150. if (pageIds == null || pageIds.length === 0) {
  1151. logger.error('pageIds is null or 0 length.');
  1152. return;
  1153. }
  1154. // generate regexps
  1155. const regexps = await this._generateRegExpsByPageIds(pageIds);
  1156. // migrate recursively
  1157. try {
  1158. await this.normalizeParentRecursively(null, regexps);
  1159. }
  1160. catch (err) {
  1161. logger.error('V5 initial miration failed.', err);
  1162. // socket.emit('v5InitialMirationFailed', { error: err.message }); TODO: use socket to tell user
  1163. throw err;
  1164. }
  1165. }
  1166. async _isPagePathIndexUnique() {
  1167. const Page = this.crowi.model('Page');
  1168. const now = (new Date()).toString();
  1169. const path = `growi_check_is_path_index_unique_${now}`;
  1170. let isUnique = false;
  1171. try {
  1172. await Page.insertMany([
  1173. { path },
  1174. { path },
  1175. ]);
  1176. }
  1177. catch (err) {
  1178. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  1179. isUnique = true;
  1180. logger.info('Page path index is unique.');
  1181. }
  1182. else {
  1183. throw err;
  1184. }
  1185. }
  1186. finally {
  1187. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  1188. }
  1189. return isUnique;
  1190. }
  1191. // TODO: use socket to send status to the client
  1192. async v5InitialMigration(grant) {
  1193. // const socket = this.crowi.socketIoService.getAdminSocket();
  1194. let isUnique;
  1195. try {
  1196. isUnique = await this._isPagePathIndexUnique();
  1197. }
  1198. catch (err) {
  1199. logger.error('Failed to check path index status', err);
  1200. throw err;
  1201. }
  1202. // drop unique index first
  1203. if (isUnique) {
  1204. try {
  1205. await this._v5NormalizeIndex();
  1206. }
  1207. catch (err) {
  1208. logger.error('V5 index normalization failed.', err);
  1209. // socket.emit('v5IndexNormalizationFailed', { error: err.message });
  1210. throw err;
  1211. }
  1212. }
  1213. // then migrate
  1214. try {
  1215. await this.normalizeParentRecursively(grant, null, true);
  1216. }
  1217. catch (err) {
  1218. logger.error('V5 initial miration failed.', err);
  1219. // socket.emit('v5InitialMirationFailed', { error: err.message });
  1220. throw err;
  1221. }
  1222. // update descendantCount of all public pages
  1223. try {
  1224. await this.updateDescendantCountOfSelfAndDescendants('/');
  1225. logger.info('Successfully updated all descendantCount of public pages.');
  1226. }
  1227. catch (err) {
  1228. logger.error('Failed updating descendantCount of public pages.', err);
  1229. throw err;
  1230. }
  1231. await this._setIsV5CompatibleTrue();
  1232. }
  1233. /*
  1234. * returns an array of js RegExp instance instead of RE2 instance for mongo filter
  1235. */
  1236. async _generateRegExpsByPageIds(pageIds) {
  1237. const Page = mongoose.model('Page') as unknown as PageModel;
  1238. let result;
  1239. try {
  1240. result = await Page.findListByPageIds(pageIds, null, false);
  1241. }
  1242. catch (err) {
  1243. logger.error('Failed to find pages by ids', err);
  1244. throw err;
  1245. }
  1246. const { pages } = result;
  1247. const regexps = pages.map(page => new RegExp(`^${page.path}`));
  1248. return regexps;
  1249. }
  1250. async _setIsV5CompatibleTrue() {
  1251. try {
  1252. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  1253. 'app:isV5Compatible': true,
  1254. });
  1255. logger.info('Successfully migrated all public pages.');
  1256. }
  1257. catch (err) {
  1258. logger.warn('Failed to update app:isV5Compatible to true.');
  1259. throw err;
  1260. }
  1261. }
  1262. // TODO: use websocket to show progress
  1263. async normalizeParentRecursively(grant, regexps, publicOnly = false): Promise<void> {
  1264. const BATCH_SIZE = 100;
  1265. const PAGES_LIMIT = 1000;
  1266. const Page = this.crowi.model('Page');
  1267. const { PageQueryBuilder } = Page;
  1268. // generate filter
  1269. let filter: any = {
  1270. parent: null,
  1271. path: { $ne: '/' },
  1272. };
  1273. if (grant != null) {
  1274. filter = {
  1275. ...filter,
  1276. grant,
  1277. };
  1278. }
  1279. if (regexps != null && regexps.length !== 0) {
  1280. filter = {
  1281. ...filter,
  1282. path: {
  1283. $in: regexps,
  1284. },
  1285. };
  1286. }
  1287. const total = await Page.countDocuments(filter);
  1288. let baseAggregation = Page
  1289. .aggregate([
  1290. {
  1291. $match: filter,
  1292. },
  1293. {
  1294. $project: { // minimize data to fetch
  1295. _id: 1,
  1296. path: 1,
  1297. },
  1298. },
  1299. ]);
  1300. // limit pages to get
  1301. if (total > PAGES_LIMIT) {
  1302. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  1303. }
  1304. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  1305. // use batch stream
  1306. const batchStream = createBatchStream(BATCH_SIZE);
  1307. let countPages = 0;
  1308. let shouldContinue = true;
  1309. // migrate all siblings for each page
  1310. const migratePagesStream = new Writable({
  1311. objectMode: true,
  1312. async write(pages, encoding, callback) {
  1313. // make list to create empty pages
  1314. const parentPathsSet = new Set(pages.map(page => pathlib.dirname(page.path)));
  1315. const parentPaths = Array.from(parentPathsSet);
  1316. // fill parents with empty pages
  1317. await Page.createEmptyPagesByPaths(parentPaths, publicOnly);
  1318. // find parents again
  1319. const builder = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }), true);
  1320. const parents = await builder
  1321. .addConditionToListByPathsArray(parentPaths)
  1322. .query
  1323. .lean()
  1324. .exec();
  1325. // bulkWrite to update parent
  1326. const updateManyOperations = parents.map((parent) => {
  1327. const parentId = parent._id;
  1328. // modify to adjust for RegExp
  1329. let parentPath = parent.path === '/' ? '' : parent.path;
  1330. parentPath = escapeStringRegexp(parentPath);
  1331. const filter: any = {
  1332. // regexr.com/6889f
  1333. // ex. /parent/any_child OR /any_level1
  1334. path: { $regex: new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`, 'i') },
  1335. };
  1336. if (grant != null) {
  1337. filter.grant = grant;
  1338. }
  1339. return {
  1340. updateMany: {
  1341. filter,
  1342. update: {
  1343. parent: parentId,
  1344. },
  1345. },
  1346. };
  1347. });
  1348. try {
  1349. const res = await Page.bulkWrite(updateManyOperations);
  1350. countPages += res.result.nModified;
  1351. logger.info(`Page migration processing: (count=${countPages})`);
  1352. // throw
  1353. if (res.result.writeErrors.length > 0) {
  1354. logger.error('Failed to migrate some pages', res.result.writeErrors);
  1355. throw Error('Failed to migrate some pages');
  1356. }
  1357. // finish migration
  1358. if (res.result.nModified === 0 && res.result.nMatched === 0) {
  1359. shouldContinue = false;
  1360. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  1361. }
  1362. }
  1363. catch (err) {
  1364. logger.error('Failed to update page.parent.', err);
  1365. throw err;
  1366. }
  1367. callback();
  1368. },
  1369. final(callback) {
  1370. callback();
  1371. },
  1372. });
  1373. pagesStream
  1374. .pipe(batchStream)
  1375. .pipe(migratePagesStream);
  1376. await streamToPromise(migratePagesStream);
  1377. if (await Page.exists(filter) && shouldContinue) {
  1378. return this.normalizeParentRecursively(grant, regexps, publicOnly);
  1379. }
  1380. }
  1381. async _v5NormalizeIndex() {
  1382. const collection = mongoose.connection.collection('pages');
  1383. try {
  1384. // drop pages.path_1 indexes
  1385. await collection.dropIndex('path_1');
  1386. logger.info('Succeeded to drop unique indexes from pages.path.');
  1387. }
  1388. catch (err) {
  1389. logger.warn('Failed to drop unique indexes from pages.path.', err);
  1390. throw err;
  1391. }
  1392. try {
  1393. // create indexes without
  1394. await collection.createIndex({ path: 1 }, { unique: false });
  1395. logger.info('Succeeded to create non-unique indexes on pages.path.');
  1396. }
  1397. catch (err) {
  1398. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  1399. throw err;
  1400. }
  1401. }
  1402. async v5MigratablePrivatePagesCount(user) {
  1403. if (user == null) {
  1404. throw Error('user is required');
  1405. }
  1406. const Page = this.crowi.model('Page');
  1407. return Page.count({ parent: null, creator: user, grant: { $ne: Page.GRANT_PUBLIC } });
  1408. }
  1409. /**
  1410. * update descendantCount of the following pages
  1411. * - page that has the same path as the provided path
  1412. * - pages that are descendants of the above page
  1413. */
  1414. async updateDescendantCountOfSelfAndDescendants(path = '/') {
  1415. const BATCH_SIZE = 200;
  1416. const Page = this.crowi.model('Page');
  1417. const aggregateCondition = Page.getAggrConditionForPageWithProvidedPathAndDescendants(path);
  1418. const aggregatedPages = await Page.aggregate(aggregateCondition).cursor({ batchSize: BATCH_SIZE });
  1419. const recountWriteStream = new Writable({
  1420. objectMode: true,
  1421. async write(pageDocuments, encoding, callback) {
  1422. for (const document of pageDocuments) {
  1423. // eslint-disable-next-line no-await-in-loop
  1424. await Page.recountDescendantCountOfSelfAndDescendants(document._id);
  1425. }
  1426. callback();
  1427. },
  1428. final(callback) {
  1429. callback();
  1430. },
  1431. });
  1432. aggregatedPages
  1433. .pipe(createBatchStream(BATCH_SIZE))
  1434. .pipe(recountWriteStream);
  1435. await streamToPromise(recountWriteStream);
  1436. }
  1437. // update descendantCount of all pages that are ancestors of a provided path by count
  1438. async updateDescendantCountOfAncestors(path = '/', count = 0) {
  1439. const Page = this.crowi.model('Page');
  1440. const ancestors = collectAncestorPaths(path);
  1441. await Page.incrementDescendantCountOfPaths(ancestors, count);
  1442. }
  1443. }
  1444. export default PageService;