page.ts 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  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. if (isRecursively) {
  733. this.deleteDescendantsWithStream(page, user); // use the same process in both version v4 and v5
  734. }
  735. else {
  736. // replace with an empty page
  737. const shouldReplace = await Page.exists({ parent: page._id });
  738. if (shouldReplace) {
  739. await Page.replaceTargetWithEmptyPage(page);
  740. }
  741. }
  742. let deletedPage;
  743. // update Revisions
  744. if (page.isEmpty) {
  745. await Page.remove({ _id: page._id });
  746. }
  747. else {
  748. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  749. deletedPage = await Page.findByIdAndUpdate(page._id, {
  750. $set: {
  751. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, // set parent as null
  752. },
  753. }, { new: true });
  754. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  755. /*
  756. * TODO: https://redmine.weseek.co.jp/issues/86577
  757. * bulkWrite PageRedirect documents
  758. */
  759. // const body = `redirect ${newPath}`;
  760. // await Page.create(page.path, body, user, { redirectTo: newPath });
  761. this.pageEvent.emit('delete', page, user);
  762. this.pageEvent.emit('create', deletedPage, user);
  763. }
  764. return deletedPage;
  765. }
  766. private async deletePageV4(page, user, options = {}, isRecursively = false) {
  767. const Page = mongoose.model('Page') as PageModel;
  768. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  769. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  770. const newPath = Page.getDeletedPageName(page.path);
  771. const isTrashed = isTrashPage(page.path);
  772. if (isTrashed) {
  773. throw new Error('This method does NOT support deleting trashed pages.');
  774. }
  775. if (!Page.isDeletableName(page.path)) {
  776. throw new Error('Page is not deletable.');
  777. }
  778. if (isRecursively) {
  779. this.deleteDescendantsWithStream(page, user);
  780. }
  781. // update Revisions
  782. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  783. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  784. $set: {
  785. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  786. },
  787. }, { new: true });
  788. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  789. /*
  790. * TODO: https://redmine.weseek.co.jp/issues/86577
  791. * bulkWrite PageRedirect documents
  792. */
  793. // const body = `redirect ${newPath}`;
  794. // await Page.create(page.path, body, user, { redirectTo: newPath });
  795. this.pageEvent.emit('delete', page, user);
  796. this.pageEvent.emit('create', deletedPage, user);
  797. return deletedPage;
  798. }
  799. private async deleteCompletelyOperation(pageIds, pagePaths) {
  800. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  801. const Bookmark = this.crowi.model('Bookmark');
  802. const Comment = this.crowi.model('Comment');
  803. const Page = this.crowi.model('Page');
  804. const PageTagRelation = this.crowi.model('PageTagRelation');
  805. const ShareLink = this.crowi.model('ShareLink');
  806. const Revision = this.crowi.model('Revision');
  807. const Attachment = this.crowi.model('Attachment');
  808. const { attachmentService } = this.crowi;
  809. const attachments = await Attachment.find({ page: { $in: pageIds } });
  810. const pages = await Page.find({ redirectTo: { $ne: null } });
  811. const redirectToPagePathMapping = {};
  812. pages.forEach((page) => {
  813. redirectToPagePathMapping[page.redirectTo] = page.path;
  814. });
  815. const redirectedFromPagePaths: any[] = [];
  816. pagePaths.forEach((pagePath) => {
  817. redirectedFromPagePaths.push(...this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping));
  818. });
  819. return Promise.all([
  820. Bookmark.deleteMany({ page: { $in: pageIds } }),
  821. Comment.deleteMany({ page: { $in: pageIds } }),
  822. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  823. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  824. Revision.deleteMany({ path: { $in: pagePaths } }),
  825. Page.deleteMany({ $or: [{ path: { $in: pagePaths } }, { path: { $in: redirectedFromPagePaths } }, { _id: { $in: pageIds } }] }),
  826. attachmentService.removeAllAttachments(attachments),
  827. ]);
  828. }
  829. private async deleteDescendants(pages, user) {
  830. const Page = mongoose.model('Page') as PageModel;
  831. const deletePageOperations: any[] = [];
  832. pages.forEach((page) => {
  833. const newPath = Page.getDeletedPageName(page.path);
  834. let operation;
  835. // if empty, delete completely
  836. if (page.isEmpty) {
  837. operation = {
  838. deleteOne: {
  839. filter: { _id: page._id },
  840. },
  841. };
  842. }
  843. // if not empty, set parent to null and update to trash
  844. else {
  845. operation = {
  846. updateOne: {
  847. filter: { _id: page._id },
  848. update: {
  849. $set: {
  850. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, // set parent as null
  851. },
  852. },
  853. },
  854. };
  855. }
  856. deletePageOperations.push(operation);
  857. });
  858. try {
  859. await Page.bulkWrite(deletePageOperations);
  860. }
  861. catch (err) {
  862. if (err.code !== 11000) {
  863. throw new Error(`Failed to delete pages: ${err}`);
  864. }
  865. }
  866. finally {
  867. this.pageEvent.emit('syncDescendantsDelete', pages, user);
  868. }
  869. }
  870. /**
  871. * Create delete stream
  872. */
  873. private async deleteDescendantsWithStream(targetPage, user) {
  874. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  875. const deleteDescendants = this.deleteDescendants.bind(this);
  876. let count = 0;
  877. const writeStream = new Writable({
  878. objectMode: true,
  879. async write(batch, encoding, callback) {
  880. try {
  881. count += batch.length;
  882. await deleteDescendants(batch, user);
  883. logger.debug(`Reverting pages progressing: (count=${count})`);
  884. }
  885. catch (err) {
  886. logger.error('revertPages error on add anyway: ', err);
  887. }
  888. callback();
  889. },
  890. final(callback) {
  891. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  892. callback();
  893. },
  894. });
  895. readStream
  896. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  897. .pipe(writeStream);
  898. }
  899. // delete multiple pages
  900. private async deleteMultipleCompletely(pages, user, options = {}) {
  901. const ids = pages.map(page => (page._id));
  902. const paths = pages.map(page => (page.path));
  903. logger.debug('Deleting completely', paths);
  904. await this.deleteCompletelyOperation(ids, paths);
  905. this.pageEvent.emit('syncDescendantsDelete', pages, user); // update as renamed page
  906. return;
  907. }
  908. async deleteCompletely(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  909. const ids = [page._id];
  910. const paths = [page.path];
  911. logger.debug('Deleting completely', paths);
  912. await this.deleteCompletelyOperation(ids, paths);
  913. if (isRecursively) {
  914. this.deleteCompletelyDescendantsWithStream(page, user, options);
  915. }
  916. if (!preventEmitting) {
  917. this.pageEvent.emit('deleteCompletely', page, user);
  918. }
  919. return;
  920. }
  921. async emptyTrashPage(user, options = {}) {
  922. return this.deleteCompletelyDescendantsWithStream({ path: '/trash' }, user, options);
  923. }
  924. /**
  925. * Create delete completely stream
  926. */
  927. private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}) {
  928. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  929. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  930. let count = 0;
  931. const writeStream = new Writable({
  932. objectMode: true,
  933. async write(batch, encoding, callback) {
  934. try {
  935. count += batch.length;
  936. await deleteMultipleCompletely(batch, user, options);
  937. logger.debug(`Adding pages progressing: (count=${count})`);
  938. }
  939. catch (err) {
  940. logger.error('addAllPages error on add anyway: ', err);
  941. }
  942. callback();
  943. },
  944. final(callback) {
  945. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  946. callback();
  947. },
  948. });
  949. readStream
  950. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  951. .pipe(writeStream);
  952. }
  953. private async revertDeletedDescendants(pages, user) {
  954. const Page = this.crowi.model('Page');
  955. const pageCollection = mongoose.connection.collection('pages');
  956. const revisionCollection = mongoose.connection.collection('revisions');
  957. const removePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  958. const revertPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  959. const revertRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  960. // e.g. key: '/test'
  961. const pathToPageMapping = {};
  962. const toPaths = pages.map(page => Page.getRevertDeletedPageName(page.path));
  963. const toPages = await Page.find({ path: { $in: toPaths } });
  964. toPages.forEach((toPage) => {
  965. pathToPageMapping[toPage.path] = toPage;
  966. });
  967. pages.forEach((page) => {
  968. // e.g. page.path = /trash/test, toPath = /test
  969. const toPath = Page.getRevertDeletedPageName(page.path);
  970. if (pathToPageMapping[toPath] != null) {
  971. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  972. // So, it's ok to delete the page
  973. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  974. if (pathToPageMapping[toPath].redirectTo === page.path) {
  975. removePageBulkOp.find({ path: toPath }).delete();
  976. }
  977. }
  978. revertPageBulkOp.find({ _id: page._id }).update({
  979. $set: {
  980. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  981. },
  982. });
  983. revertRevisionBulkOp.find({ path: page.path }).update({ $set: { path: toPath } });
  984. });
  985. try {
  986. await removePageBulkOp.execute();
  987. await revertPageBulkOp.execute();
  988. await revertRevisionBulkOp.execute();
  989. }
  990. catch (err) {
  991. if (err.code !== 11000) {
  992. throw new Error(`Failed to revert pages: ${err}`);
  993. }
  994. }
  995. }
  996. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  997. const Page = this.crowi.model('Page');
  998. const PageTagRelation = this.crowi.model('PageTagRelation');
  999. const Revision = this.crowi.model('Revision');
  1000. const newPath = Page.getRevertDeletedPageName(page.path);
  1001. const originPage = await Page.findByPath(newPath);
  1002. if (originPage != null) {
  1003. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  1004. // So, it's ok to delete the page
  1005. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  1006. if (originPage.redirectTo !== page.path) {
  1007. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  1008. }
  1009. await this.deleteCompletely(originPage, user, options, false, true);
  1010. this.pageEvent.emit('revert', page, user);
  1011. }
  1012. if (isRecursively) {
  1013. this.revertDeletedDescendantsWithStream(page, user, options);
  1014. }
  1015. page.status = Page.STATUS_PUBLISHED;
  1016. page.lastUpdateUser = user;
  1017. debug('Revert deleted the page', page, newPath);
  1018. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1019. $set: {
  1020. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1021. },
  1022. }, { new: true });
  1023. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1024. await Revision.updateMany({ path: page.path }, { $set: { path: newPath } });
  1025. return updatedPage;
  1026. }
  1027. /**
  1028. * Create revert stream
  1029. */
  1030. private async revertDeletedDescendantsWithStream(targetPage, user, options = {}) {
  1031. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1032. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1033. let count = 0;
  1034. const writeStream = new Writable({
  1035. objectMode: true,
  1036. async write(batch, encoding, callback) {
  1037. try {
  1038. count += batch.length;
  1039. revertDeletedDescendants(batch, user);
  1040. logger.debug(`Reverting pages progressing: (count=${count})`);
  1041. }
  1042. catch (err) {
  1043. logger.error('revertPages error on add anyway: ', err);
  1044. }
  1045. callback();
  1046. },
  1047. final(callback) {
  1048. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1049. callback();
  1050. },
  1051. });
  1052. readStream
  1053. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1054. .pipe(writeStream);
  1055. }
  1056. async handlePrivatePagesForGroupsToDelete(groupsToDelete, action, transferToUserGroupId, user) {
  1057. const Page = this.crowi.model('Page');
  1058. const pages = await Page.find({ grantedGroup: { $in: groupsToDelete } });
  1059. switch (action) {
  1060. case 'public':
  1061. await Page.publicizePages(pages);
  1062. break;
  1063. case 'delete':
  1064. return this.deleteMultipleCompletely(pages, user);
  1065. case 'transfer':
  1066. await Page.transferPagesToGroup(pages, transferToUserGroupId);
  1067. break;
  1068. default:
  1069. throw new Error('Unknown action for private pages');
  1070. }
  1071. }
  1072. async shortBodiesMapByPageIds(pageIds: string[] = [], user) {
  1073. const Page = mongoose.model('Page');
  1074. const MAX_LENGTH = 350;
  1075. // aggregation options
  1076. const viewerCondition = await generateGrantCondition(user, null);
  1077. const filterByIds = {
  1078. _id: { $in: pageIds.map(id => new mongoose.Types.ObjectId(id)) },
  1079. };
  1080. let pages;
  1081. try {
  1082. pages = await Page
  1083. .aggregate([
  1084. // filter by pageIds
  1085. {
  1086. $match: filterByIds,
  1087. },
  1088. // filter by viewer
  1089. viewerCondition,
  1090. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  1091. {
  1092. $lookup: {
  1093. from: 'revisions',
  1094. let: { localRevision: '$revision' },
  1095. pipeline: [
  1096. {
  1097. $match: {
  1098. $expr: {
  1099. $eq: ['$_id', '$$localRevision'],
  1100. },
  1101. },
  1102. },
  1103. {
  1104. $project: {
  1105. // What is $substrCP?
  1106. // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
  1107. revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
  1108. },
  1109. },
  1110. ],
  1111. as: 'revisionData',
  1112. },
  1113. },
  1114. // projection
  1115. {
  1116. $project: {
  1117. _id: 1,
  1118. revisionData: 1,
  1119. },
  1120. },
  1121. ]).exec();
  1122. }
  1123. catch (err) {
  1124. logger.error('Error occurred while generating shortBodiesMap');
  1125. throw err;
  1126. }
  1127. const shortBodiesMap = {};
  1128. pages.forEach((page) => {
  1129. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  1130. });
  1131. return shortBodiesMap;
  1132. }
  1133. private async createAndSendNotifications(page, user, action) {
  1134. const { activityService, inAppNotificationService } = this.crowi;
  1135. const snapshot = stringifySnapshot(page);
  1136. // Create activity
  1137. const parameters = {
  1138. user: user._id,
  1139. targetModel: ActivityDefine.MODEL_PAGE,
  1140. target: page,
  1141. action,
  1142. };
  1143. const activity = await activityService.createByParameters(parameters);
  1144. // Get user to be notified
  1145. const targetUsers = await activity.getNotificationTargetUsers();
  1146. // Create and send notifications
  1147. await inAppNotificationService.upsertByActivity(targetUsers, activity, snapshot);
  1148. await inAppNotificationService.emitSocketIo(targetUsers);
  1149. }
  1150. async v5MigrationByPageIds(pageIds) {
  1151. const Page = mongoose.model('Page');
  1152. if (pageIds == null || pageIds.length === 0) {
  1153. logger.error('pageIds is null or 0 length.');
  1154. return;
  1155. }
  1156. // generate regexps
  1157. const regexps = await this._generateRegExpsByPageIds(pageIds);
  1158. // migrate recursively
  1159. try {
  1160. await this.normalizeParentRecursively(null, regexps);
  1161. }
  1162. catch (err) {
  1163. logger.error('V5 initial miration failed.', err);
  1164. // socket.emit('v5InitialMirationFailed', { error: err.message }); TODO: use socket to tell user
  1165. throw err;
  1166. }
  1167. }
  1168. async _isPagePathIndexUnique() {
  1169. const Page = this.crowi.model('Page');
  1170. const now = (new Date()).toString();
  1171. const path = `growi_check_is_path_index_unique_${now}`;
  1172. let isUnique = false;
  1173. try {
  1174. await Page.insertMany([
  1175. { path },
  1176. { path },
  1177. ]);
  1178. }
  1179. catch (err) {
  1180. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  1181. isUnique = true;
  1182. logger.info('Page path index is unique.');
  1183. }
  1184. else {
  1185. throw err;
  1186. }
  1187. }
  1188. finally {
  1189. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  1190. }
  1191. return isUnique;
  1192. }
  1193. // TODO: use socket to send status to the client
  1194. async v5InitialMigration(grant) {
  1195. // const socket = this.crowi.socketIoService.getAdminSocket();
  1196. let isUnique;
  1197. try {
  1198. isUnique = await this._isPagePathIndexUnique();
  1199. }
  1200. catch (err) {
  1201. logger.error('Failed to check path index status', err);
  1202. throw err;
  1203. }
  1204. // drop unique index first
  1205. if (isUnique) {
  1206. try {
  1207. await this._v5NormalizeIndex();
  1208. }
  1209. catch (err) {
  1210. logger.error('V5 index normalization failed.', err);
  1211. // socket.emit('v5IndexNormalizationFailed', { error: err.message });
  1212. throw err;
  1213. }
  1214. }
  1215. // then migrate
  1216. try {
  1217. await this.normalizeParentRecursively(grant, null, true);
  1218. }
  1219. catch (err) {
  1220. logger.error('V5 initial miration failed.', err);
  1221. // socket.emit('v5InitialMirationFailed', { error: err.message });
  1222. throw err;
  1223. }
  1224. // update descendantCount of all public pages
  1225. try {
  1226. await this.updateDescendantCountOfSelfAndDescendants('/');
  1227. logger.info('Successfully updated all descendantCount of public pages.');
  1228. }
  1229. catch (err) {
  1230. logger.error('Failed updating descendantCount of public pages.', err);
  1231. throw err;
  1232. }
  1233. await this._setIsV5CompatibleTrue();
  1234. }
  1235. /*
  1236. * returns an array of js RegExp instance instead of RE2 instance for mongo filter
  1237. */
  1238. async _generateRegExpsByPageIds(pageIds) {
  1239. const Page = mongoose.model('Page') as unknown as PageModel;
  1240. let result;
  1241. try {
  1242. result = await Page.findListByPageIds(pageIds, null, false);
  1243. }
  1244. catch (err) {
  1245. logger.error('Failed to find pages by ids', err);
  1246. throw err;
  1247. }
  1248. const { pages } = result;
  1249. const regexps = pages.map(page => new RegExp(`^${page.path}`));
  1250. return regexps;
  1251. }
  1252. async _setIsV5CompatibleTrue() {
  1253. try {
  1254. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  1255. 'app:isV5Compatible': true,
  1256. });
  1257. logger.info('Successfully migrated all public pages.');
  1258. }
  1259. catch (err) {
  1260. logger.warn('Failed to update app:isV5Compatible to true.');
  1261. throw err;
  1262. }
  1263. }
  1264. // TODO: use websocket to show progress
  1265. async normalizeParentRecursively(grant, regexps, publicOnly = false): Promise<void> {
  1266. const BATCH_SIZE = 100;
  1267. const PAGES_LIMIT = 1000;
  1268. const Page = this.crowi.model('Page');
  1269. const { PageQueryBuilder } = Page;
  1270. // generate filter
  1271. let filter: any = {
  1272. parent: null,
  1273. path: { $ne: '/' },
  1274. };
  1275. if (grant != null) {
  1276. filter = {
  1277. ...filter,
  1278. grant,
  1279. };
  1280. }
  1281. if (regexps != null && regexps.length !== 0) {
  1282. filter = {
  1283. ...filter,
  1284. path: {
  1285. $in: regexps,
  1286. },
  1287. };
  1288. }
  1289. const total = await Page.countDocuments(filter);
  1290. let baseAggregation = Page
  1291. .aggregate([
  1292. {
  1293. $match: filter,
  1294. },
  1295. {
  1296. $project: { // minimize data to fetch
  1297. _id: 1,
  1298. path: 1,
  1299. },
  1300. },
  1301. ]);
  1302. // limit pages to get
  1303. if (total > PAGES_LIMIT) {
  1304. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  1305. }
  1306. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  1307. // use batch stream
  1308. const batchStream = createBatchStream(BATCH_SIZE);
  1309. let countPages = 0;
  1310. let shouldContinue = true;
  1311. // migrate all siblings for each page
  1312. const migratePagesStream = new Writable({
  1313. objectMode: true,
  1314. async write(pages, encoding, callback) {
  1315. // make list to create empty pages
  1316. const parentPathsSet = new Set(pages.map(page => pathlib.dirname(page.path)));
  1317. const parentPaths = Array.from(parentPathsSet);
  1318. // fill parents with empty pages
  1319. await Page.createEmptyPagesByPaths(parentPaths, publicOnly);
  1320. // find parents again
  1321. const builder = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }), true);
  1322. const parents = await builder
  1323. .addConditionToListByPathsArray(parentPaths)
  1324. .query
  1325. .lean()
  1326. .exec();
  1327. // bulkWrite to update parent
  1328. const updateManyOperations = parents.map((parent) => {
  1329. const parentId = parent._id;
  1330. // modify to adjust for RegExp
  1331. let parentPath = parent.path === '/' ? '' : parent.path;
  1332. parentPath = escapeStringRegexp(parentPath);
  1333. const filter: any = {
  1334. // regexr.com/6889f
  1335. // ex. /parent/any_child OR /any_level1
  1336. path: { $regex: new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`, 'i') },
  1337. };
  1338. if (grant != null) {
  1339. filter.grant = grant;
  1340. }
  1341. return {
  1342. updateMany: {
  1343. filter,
  1344. update: {
  1345. parent: parentId,
  1346. },
  1347. },
  1348. };
  1349. });
  1350. try {
  1351. const res = await Page.bulkWrite(updateManyOperations);
  1352. countPages += res.result.nModified;
  1353. logger.info(`Page migration processing: (count=${countPages})`);
  1354. // throw
  1355. if (res.result.writeErrors.length > 0) {
  1356. logger.error('Failed to migrate some pages', res.result.writeErrors);
  1357. throw Error('Failed to migrate some pages');
  1358. }
  1359. // finish migration
  1360. if (res.result.nModified === 0 && res.result.nMatched === 0) {
  1361. shouldContinue = false;
  1362. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  1363. }
  1364. }
  1365. catch (err) {
  1366. logger.error('Failed to update page.parent.', err);
  1367. throw err;
  1368. }
  1369. callback();
  1370. },
  1371. final(callback) {
  1372. callback();
  1373. },
  1374. });
  1375. pagesStream
  1376. .pipe(batchStream)
  1377. .pipe(migratePagesStream);
  1378. await streamToPromise(migratePagesStream);
  1379. if (await Page.exists(filter) && shouldContinue) {
  1380. return this.normalizeParentRecursively(grant, regexps, publicOnly);
  1381. }
  1382. }
  1383. async _v5NormalizeIndex() {
  1384. const collection = mongoose.connection.collection('pages');
  1385. try {
  1386. // drop pages.path_1 indexes
  1387. await collection.dropIndex('path_1');
  1388. logger.info('Succeeded to drop unique indexes from pages.path.');
  1389. }
  1390. catch (err) {
  1391. logger.warn('Failed to drop unique indexes from pages.path.', err);
  1392. throw err;
  1393. }
  1394. try {
  1395. // create indexes without
  1396. await collection.createIndex({ path: 1 }, { unique: false });
  1397. logger.info('Succeeded to create non-unique indexes on pages.path.');
  1398. }
  1399. catch (err) {
  1400. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  1401. throw err;
  1402. }
  1403. }
  1404. async v5MigratablePrivatePagesCount(user) {
  1405. if (user == null) {
  1406. throw Error('user is required');
  1407. }
  1408. const Page = this.crowi.model('Page');
  1409. return Page.count({ parent: null, creator: user, grant: { $ne: Page.GRANT_PUBLIC } });
  1410. }
  1411. /**
  1412. * update descendantCount of the following pages
  1413. * - page that has the same path as the provided path
  1414. * - pages that are descendants of the above page
  1415. */
  1416. async updateDescendantCountOfSelfAndDescendants(path = '/') {
  1417. const BATCH_SIZE = 200;
  1418. const Page = this.crowi.model('Page');
  1419. const aggregateCondition = Page.getAggrConditionForPageWithProvidedPathAndDescendants(path);
  1420. const aggregatedPages = await Page.aggregate(aggregateCondition).cursor({ batchSize: BATCH_SIZE });
  1421. const recountWriteStream = new Writable({
  1422. objectMode: true,
  1423. async write(pageDocuments, encoding, callback) {
  1424. for (const document of pageDocuments) {
  1425. // eslint-disable-next-line no-await-in-loop
  1426. await Page.recountDescendantCountOfSelfAndDescendants(document._id);
  1427. }
  1428. callback();
  1429. },
  1430. final(callback) {
  1431. callback();
  1432. },
  1433. });
  1434. aggregatedPages
  1435. .pipe(createBatchStream(BATCH_SIZE))
  1436. .pipe(recountWriteStream);
  1437. await streamToPromise(recountWriteStream);
  1438. }
  1439. // update descendantCount of all pages that are ancestors of a provided path by count
  1440. async updateDescendantCountOfAncestors(path = '/', count = 0) {
  1441. const Page = this.crowi.model('Page');
  1442. const ancestors = collectAncestorPaths(path);
  1443. await Page.incrementDescendantCountOfPaths(ancestors, count);
  1444. }
  1445. }
  1446. export default PageService;