page.ts 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302
  1. import { pagePathUtils } from '@growi/core';
  2. import mongoose, { ObjectId, QueryCursor } from 'mongoose';
  3. import escapeStringRegexp from 'escape-string-regexp';
  4. import streamToPromise from 'stream-to-promise';
  5. import pathlib from 'path';
  6. import { Readable, 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, PageDocument, 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 {
  16. IPage, IPageInfo, IPageInfoForEntity,
  17. } from '~/interfaces/page';
  18. import { PageRedirectModel } from '../models/page-redirect';
  19. import { ObjectIdLike } from '../interfaces/mongoose-utils';
  20. import { IUserHasId } from '~/interfaces/user';
  21. import { Ref } from '~/interfaces/common';
  22. import { HasObjectId } from '~/interfaces/has-object-id';
  23. const debug = require('debug')('growi:services:page');
  24. const logger = loggerFactory('growi:services:page');
  25. const {
  26. isCreatablePage, isTrashPage, isTopPage, isDeletablePage, omitDuplicateAreaPathFromPaths, omitDuplicateAreaPageFromPages, isUserPage, isUserNamePage,
  27. } = pagePathUtils;
  28. const BULK_REINDEX_SIZE = 100;
  29. const LIMIT_FOR_MULTIPLE_PAGE_OP = 20;
  30. // TODO: improve type
  31. class PageCursorsForDescendantsFactory {
  32. private user: any; // TODO: Typescriptize model
  33. private rootPage: any; // TODO: wait for mongoose update
  34. private shouldIncludeEmpty: boolean;
  35. private initialCursor: QueryCursor<any>; // TODO: wait for mongoose update
  36. private Page: PageModel;
  37. constructor(user: any, rootPage: any, shouldIncludeEmpty: boolean) {
  38. this.user = user;
  39. this.rootPage = rootPage;
  40. this.shouldIncludeEmpty = shouldIncludeEmpty;
  41. this.Page = mongoose.model('Page') as unknown as PageModel;
  42. }
  43. // prepare initial cursor
  44. private async init() {
  45. const initialCursor = await this.generateCursorToFindChildren(this.rootPage);
  46. this.initialCursor = initialCursor;
  47. }
  48. /**
  49. * Returns Iterable that yields only descendant pages unorderedly
  50. * @returns Promise<AsyncGenerator>
  51. */
  52. async generateIterable(): Promise<AsyncGenerator> {
  53. // initialize cursor
  54. await this.init();
  55. return this.generateOnlyDescendants(this.initialCursor);
  56. }
  57. /**
  58. * Returns Readable that produces only descendant pages unorderedly
  59. * @returns Promise<Readable>
  60. */
  61. async generateReadable(): Promise<Readable> {
  62. return Readable.from(await this.generateIterable());
  63. }
  64. /**
  65. * Generator that unorderedly yields descendant pages
  66. */
  67. private async* generateOnlyDescendants(cursor: QueryCursor<any>) {
  68. for await (const page of cursor) {
  69. const nextCursor = await this.generateCursorToFindChildren(page);
  70. yield* this.generateOnlyDescendants(nextCursor); // recursively yield
  71. yield page;
  72. }
  73. }
  74. private async generateCursorToFindChildren(page: any): Promise<QueryCursor<any>> {
  75. const { PageQueryBuilder } = this.Page;
  76. const builder = new PageQueryBuilder(this.Page.find(), this.shouldIncludeEmpty);
  77. builder.addConditionToFilteringByParentId(page._id);
  78. await this.Page.addConditionToFilteringByViewerToEdit(builder, this.user);
  79. const cursor = builder.query.lean().cursor({ batchSize: BULK_REINDEX_SIZE }) as QueryCursor<any>;
  80. return cursor;
  81. }
  82. }
  83. class PageService {
  84. crowi: any;
  85. pageEvent: any;
  86. tagEvent: any;
  87. constructor(crowi) {
  88. this.crowi = crowi;
  89. this.pageEvent = crowi.event('page');
  90. this.tagEvent = crowi.event('tag');
  91. // init
  92. this.initPageEvent();
  93. }
  94. private initPageEvent() {
  95. // create
  96. this.pageEvent.on('create', this.pageEvent.onCreate);
  97. // createMany
  98. this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
  99. this.pageEvent.on('addSeenUsers', this.pageEvent.onAddSeenUsers);
  100. // update
  101. this.pageEvent.on('update', async(page, user) => {
  102. this.pageEvent.onUpdate();
  103. try {
  104. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_UPDATE);
  105. }
  106. catch (err) {
  107. logger.error(err);
  108. }
  109. });
  110. // rename
  111. this.pageEvent.on('rename', async(page, user) => {
  112. try {
  113. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_RENAME);
  114. }
  115. catch (err) {
  116. logger.error(err);
  117. }
  118. });
  119. // delete
  120. this.pageEvent.on('delete', async(page, user) => {
  121. try {
  122. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_DELETE);
  123. }
  124. catch (err) {
  125. logger.error(err);
  126. }
  127. });
  128. // delete completely
  129. this.pageEvent.on('deleteCompletely', async(page, user) => {
  130. try {
  131. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_DELETE_COMPLETELY);
  132. }
  133. catch (err) {
  134. logger.error(err);
  135. }
  136. });
  137. // likes
  138. this.pageEvent.on('like', async(page, user) => {
  139. try {
  140. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_LIKE);
  141. }
  142. catch (err) {
  143. logger.error(err);
  144. }
  145. });
  146. // bookmark
  147. this.pageEvent.on('bookmark', async(page, user) => {
  148. try {
  149. await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_BOOKMARK);
  150. }
  151. catch (err) {
  152. logger.error(err);
  153. }
  154. });
  155. }
  156. canDeleteCompletely(creatorId, operator) {
  157. const pageCompleteDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageCompleteDeletionAuthority');
  158. if (operator.admin) {
  159. return true;
  160. }
  161. if (pageCompleteDeletionAuthority === 'anyOne' || pageCompleteDeletionAuthority == null) {
  162. return true;
  163. }
  164. if (pageCompleteDeletionAuthority === 'adminAndAuthor') {
  165. const operatorId = operator?._id;
  166. return (operatorId != null && operatorId.equals(creatorId));
  167. }
  168. return false;
  169. }
  170. filterPagesByCanDeleteCompletely(pages, user) {
  171. return pages.filter(p => p.isEmpty || this.canDeleteCompletely(p.creator, user));
  172. }
  173. async findPageAndMetaDataByViewer({ pageId, path, user }) {
  174. const Page = this.crowi.model('Page');
  175. let pagePath = path;
  176. let page;
  177. if (pageId != null) { // prioritized
  178. page = await Page.findByIdAndViewer(pageId, user);
  179. pagePath = page.path;
  180. }
  181. else {
  182. page = await Page.findByPathAndViewer(pagePath, user);
  183. }
  184. const result: any = {};
  185. if (page == null) {
  186. const isExist = await Page.count({ $or: [{ _id: pageId }, { pat: pagePath }] }) > 0;
  187. result.isForbidden = isExist;
  188. result.isNotFound = !isExist;
  189. result.isCreatable = isCreatablePage(pagePath);
  190. result.page = page;
  191. return result;
  192. }
  193. result.page = page;
  194. result.isForbidden = false;
  195. result.isNotFound = false;
  196. result.isCreatable = false;
  197. result.isDeletable = isDeletablePage(pagePath);
  198. result.isDeleted = page.isDeleted();
  199. return result;
  200. }
  201. private shouldUseV4Process(page): boolean {
  202. const Page = mongoose.model('Page') as unknown as PageModel;
  203. const isTrashPage = page.status === Page.STATUS_DELETED;
  204. return !isTrashPage && this.shouldUseV4ProcessForRevert(page);
  205. }
  206. private shouldUseV4ProcessForRevert(page): boolean {
  207. const Page = mongoose.model('Page') as unknown as PageModel;
  208. const isPageMigrated = page.parent != null;
  209. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  210. const isRoot = isTopPage(page.path);
  211. const isPageRestricted = page.grant === Page.GRANT_RESTRICTED;
  212. const shouldUseV4Process = !isRoot && !isPageRestricted && (!isV5Compatible || !isPageMigrated);
  213. return shouldUseV4Process;
  214. }
  215. private shouldNormalizeParent(page): boolean {
  216. const Page = mongoose.model('Page') as unknown as PageModel;
  217. return page.grant !== Page.GRANT_RESTRICTED && page.grant !== Page.GRANT_SPECIFIED;
  218. }
  219. /**
  220. * Remove all empty pages at leaf position by page whose parent will change or which will be deleted.
  221. * @param page Page whose parent will change or which will be deleted
  222. */
  223. async removeLeafEmptyPages(page): Promise<void> {
  224. const Page = mongoose.model('Page') as unknown as PageModel;
  225. // delete leaf empty pages
  226. const shouldDeleteLeafEmptyPages = !(await Page.exists({ parent: page.parent, _id: { $ne: page._id } }));
  227. if (shouldDeleteLeafEmptyPages) {
  228. await Page.removeLeafEmptyPagesById(page.parent);
  229. }
  230. }
  231. /**
  232. * Generate read stream to operate descendants of the specified page path
  233. * @param {string} targetPagePath
  234. * @param {User} viewer
  235. */
  236. private async generateReadStreamToOperateOnlyDescendants(targetPagePath, userToOperate) {
  237. const Page = this.crowi.model('Page');
  238. const { PageQueryBuilder } = Page;
  239. const builder = new PageQueryBuilder(Page.find(), true)
  240. .addConditionAsNotMigrated() // to avoid affecting v5 pages
  241. .addConditionToListOnlyDescendants(targetPagePath);
  242. await Page.addConditionToFilteringByViewerToEdit(builder, userToOperate);
  243. return builder
  244. .query
  245. .lean()
  246. .cursor({ batchSize: BULK_REINDEX_SIZE });
  247. }
  248. async renamePage(page, newPagePath, user, options) {
  249. const Page = this.crowi.model('Page');
  250. if (isTopPage(page.path)) {
  251. throw Error('It is forbidden to rename the top page');
  252. }
  253. // v4 compatible process
  254. const shouldUseV4Process = this.shouldUseV4Process(page);
  255. if (shouldUseV4Process) {
  256. return this.renamePageV4(page, newPagePath, user, options);
  257. }
  258. const updateMetadata = options.updateMetadata || false;
  259. // sanitize path
  260. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  261. // use the parent's grant when target page is an empty page
  262. let grant;
  263. let grantedUserIds;
  264. let grantedGroupId;
  265. if (page.isEmpty) {
  266. const parent = await Page.findOne({ _id: page.parent });
  267. if (parent == null) {
  268. throw Error('parent not found');
  269. }
  270. grant = parent.grant;
  271. grantedUserIds = parent.grantedUsers;
  272. grantedGroupId = parent.grantedGroup;
  273. }
  274. else {
  275. grant = page.grant;
  276. grantedUserIds = page.grantedUsers;
  277. grantedGroupId = page.grantedGroup;
  278. }
  279. /*
  280. * UserGroup & Owner validation
  281. */
  282. if (grant !== Page.GRANT_RESTRICTED) {
  283. let isGrantNormalized = false;
  284. try {
  285. const shouldCheckDescendants = false;
  286. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(newPagePath, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  287. }
  288. catch (err) {
  289. logger.error(`Failed to validate grant of page at "${newPagePath}" when renaming`, err);
  290. throw err;
  291. }
  292. if (!isGrantNormalized) {
  293. throw Error(`This page cannot be renamed to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  294. }
  295. }
  296. /*
  297. * update target
  298. */
  299. const update: Partial<IPage> = {};
  300. // find or create parent
  301. const newParent = await Page.getParentAndFillAncestors(newPagePath);
  302. // update Page
  303. update.path = newPagePath;
  304. update.parent = newParent._id;
  305. if (updateMetadata) {
  306. update.lastUpdateUser = user;
  307. update.updatedAt = new Date();
  308. }
  309. // *************************
  310. // * before rename target page
  311. // *************************
  312. const oldPageParentId = page.parent; // this is used to update descendantCount of old page's ancestors
  313. // *************************
  314. // * rename target page
  315. // *************************
  316. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  317. this.pageEvent.emit('rename', page, user);
  318. // *************************
  319. // * after rename target page
  320. // *************************
  321. // rename descendants and update descendantCount asynchronously
  322. this.resumableRenameDescendants(page, newPagePath, user, options, shouldUseV4Process, renamedPage, oldPageParentId);
  323. return renamedPage;
  324. }
  325. async resumableRenameDescendants(page, newPagePath, user, options, shouldUseV4Process, renamedPage, oldPageParentId) {
  326. // TODO: resume
  327. // update descendants first
  328. await this.renameDescendantsWithStream(page, newPagePath, user, options, shouldUseV4Process);
  329. // reduce ancestore's descendantCount
  330. const nToReduce = -1 * ((page.isEmpty ? 0 : 1) + page.descendantCount);
  331. await this.updateDescendantCountOfAncestors(oldPageParentId, nToReduce, true);
  332. // increase ancestore's descendantCount
  333. const nToIncrease = (renamedPage.isEmpty ? 0 : 1) + page.descendantCount;
  334. await this.updateDescendantCountOfAncestors(renamedPage._id, nToIncrease, false);
  335. }
  336. // !!renaming always include descendant pages!!
  337. private async renamePageV4(page, newPagePath, user, options) {
  338. const Page = this.crowi.model('Page');
  339. const Revision = this.crowi.model('Revision');
  340. const updateMetadata = options.updateMetadata || false;
  341. // sanitize path
  342. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  343. // create descendants first
  344. await this.renameDescendantsWithStream(page, newPagePath, user, options);
  345. const update: any = {};
  346. // update Page
  347. update.path = newPagePath;
  348. if (updateMetadata) {
  349. update.lastUpdateUser = user;
  350. update.updatedAt = Date.now();
  351. }
  352. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  353. // update Rivisions
  354. await Revision.updateRevisionListByPageId(renamedPage._id, { pageId: renamedPage._id });
  355. this.pageEvent.emit('rename', page, user);
  356. return renamedPage;
  357. }
  358. private async renameDescendants(pages, user, options, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = true) {
  359. // v4 compatible process
  360. if (shouldUseV4Process) {
  361. return this.renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix);
  362. }
  363. const Page = mongoose.model('Page') as unknown as PageModel;
  364. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  365. const { updateMetadata, createRedirectPage } = options;
  366. const updatePathOperations: any[] = [];
  367. const insertPageRedirectOperations: any[] = [];
  368. pages.forEach((page) => {
  369. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  370. // increment updatePathOperations
  371. let update;
  372. if (!page.isEmpty && updateMetadata) {
  373. update = {
  374. $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() },
  375. };
  376. }
  377. else {
  378. update = {
  379. $set: { path: newPagePath },
  380. };
  381. }
  382. if (!page.isEmpty && createRedirectPage) {
  383. // insert PageRedirect
  384. insertPageRedirectOperations.push({
  385. insertOne: {
  386. document: {
  387. fromPath: page.path,
  388. toPath: newPagePath,
  389. },
  390. },
  391. });
  392. }
  393. updatePathOperations.push({
  394. updateOne: {
  395. filter: {
  396. _id: page._id,
  397. },
  398. update,
  399. },
  400. });
  401. });
  402. try {
  403. await Page.bulkWrite(updatePathOperations);
  404. }
  405. catch (err) {
  406. if (err.code !== 11000) {
  407. throw new Error(`Failed to rename pages: ${err}`);
  408. }
  409. }
  410. try {
  411. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  412. }
  413. catch (err) {
  414. if (err.code !== 11000) {
  415. throw Error(`Failed to create PageRedirect documents: ${err}`);
  416. }
  417. }
  418. this.pageEvent.emit('updateMany', pages, user);
  419. }
  420. private async renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix) {
  421. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  422. const pageCollection = mongoose.connection.collection('pages');
  423. const { updateMetadata, createRedirectPage } = options;
  424. const unorderedBulkOp = pageCollection.initializeUnorderedBulkOp();
  425. const insertPageRedirectOperations: any[] = [];
  426. pages.forEach((page) => {
  427. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  428. if (updateMetadata) {
  429. unorderedBulkOp
  430. .find({ _id: page._id })
  431. .update({ $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() } });
  432. }
  433. else {
  434. unorderedBulkOp.find({ _id: page._id }).update({ $set: { path: newPagePath } });
  435. }
  436. // insert PageRedirect
  437. if (!page.isEmpty && createRedirectPage) {
  438. insertPageRedirectOperations.push({
  439. insertOne: {
  440. document: {
  441. fromPath: page.path,
  442. toPath: newPagePath,
  443. },
  444. },
  445. });
  446. }
  447. });
  448. try {
  449. await unorderedBulkOp.execute();
  450. }
  451. catch (err) {
  452. if (err.code !== 11000) {
  453. throw new Error(`Failed to rename pages: ${err}`);
  454. }
  455. }
  456. try {
  457. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  458. }
  459. catch (err) {
  460. if (err.code !== 11000) {
  461. throw Error(`Failed to create PageRedirect documents: ${err}`);
  462. }
  463. }
  464. this.pageEvent.emit('updateMany', pages, user);
  465. }
  466. private async renameDescendantsWithStream(targetPage, newPagePath, user, options = {}, shouldUseV4Process = true) {
  467. // v4 compatible process
  468. if (shouldUseV4Process) {
  469. return this.renameDescendantsWithStreamV4(targetPage, newPagePath, user, options);
  470. }
  471. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  472. const readStream = await factory.generateReadable();
  473. const newPagePathPrefix = newPagePath;
  474. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  475. const renameDescendants = this.renameDescendants.bind(this);
  476. const pageEvent = this.pageEvent;
  477. let count = 0;
  478. const writeStream = new Writable({
  479. objectMode: true,
  480. async write(batch, encoding, callback) {
  481. try {
  482. count += batch.length;
  483. await renameDescendants(
  484. batch, user, options, pathRegExp, newPagePathPrefix, shouldUseV4Process,
  485. );
  486. logger.debug(`Renaming pages progressing: (count=${count})`);
  487. }
  488. catch (err) {
  489. logger.error('Renaming error on add anyway: ', err);
  490. }
  491. callback();
  492. },
  493. async final(callback) {
  494. logger.debug(`Renaming pages has completed: (totalCount=${count})`);
  495. // update path
  496. targetPage.path = newPagePath;
  497. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  498. callback();
  499. },
  500. });
  501. readStream
  502. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  503. .pipe(writeStream);
  504. await streamToPromise(writeStream);
  505. }
  506. private async renameDescendantsWithStreamV4(targetPage, newPagePath, user, options = {}) {
  507. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  508. const newPagePathPrefix = newPagePath;
  509. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  510. const renameDescendants = this.renameDescendants.bind(this);
  511. const pageEvent = this.pageEvent;
  512. let count = 0;
  513. const writeStream = new Writable({
  514. objectMode: true,
  515. async write(batch, encoding, callback) {
  516. try {
  517. count += batch.length;
  518. await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
  519. logger.debug(`Renaming pages progressing: (count=${count})`);
  520. }
  521. catch (err) {
  522. logger.error('renameDescendants error on add anyway: ', err);
  523. }
  524. callback();
  525. },
  526. final(callback) {
  527. logger.debug(`Renaming pages has completed: (totalCount=${count})`);
  528. // update path
  529. targetPage.path = newPagePath;
  530. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  531. callback();
  532. },
  533. });
  534. readStream
  535. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  536. .pipe(writeStream);
  537. await streamToPromise(readStream);
  538. }
  539. /*
  540. * Duplicate
  541. */
  542. async duplicate(page, newPagePath, user, isRecursively) {
  543. const Page = mongoose.model('Page') as unknown as PageModel;
  544. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  545. // v4 compatible process
  546. const shouldUseV4Process = this.shouldUseV4Process(page);
  547. if (shouldUseV4Process) {
  548. return this.duplicateV4(page, newPagePath, user, isRecursively);
  549. }
  550. // use the parent's grant when target page is an empty page
  551. let grant;
  552. let grantedUserIds;
  553. let grantedGroupId;
  554. if (page.isEmpty) {
  555. const parent = await Page.findOne({ _id: page.parent });
  556. if (parent == null) {
  557. throw Error('parent not found');
  558. }
  559. grant = parent.grant;
  560. grantedUserIds = parent.grantedUsers;
  561. grantedGroupId = parent.grantedGroup;
  562. }
  563. else {
  564. grant = page.grant;
  565. grantedUserIds = page.grantedUsers;
  566. grantedGroupId = page.grantedGroup;
  567. }
  568. /*
  569. * UserGroup & Owner validation
  570. */
  571. if (grant !== Page.GRANT_RESTRICTED) {
  572. let isGrantNormalized = false;
  573. try {
  574. const shouldCheckDescendants = false;
  575. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(newPagePath, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  576. }
  577. catch (err) {
  578. logger.error(`Failed to validate grant of page at "${newPagePath}" when duplicating`, err);
  579. throw err;
  580. }
  581. if (!isGrantNormalized) {
  582. throw Error(`This page cannot be duplicated to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  583. }
  584. }
  585. // populate
  586. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  587. // create option
  588. const options: PageCreateOptions = {
  589. grant: page.grant,
  590. grantUserGroupId: page.grantedGroup,
  591. };
  592. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  593. let createdPage;
  594. if (page.isEmpty) {
  595. const parent = await Page.getParentAndFillAncestors(newPagePath);
  596. createdPage = await Page.createEmptyPage(newPagePath, parent);
  597. }
  598. else {
  599. createdPage = await (Page.create as CreateMethod)(
  600. newPagePath, page.revision.body, user, options,
  601. );
  602. }
  603. // take over tags
  604. const originTags = await page.findRelatedTagsById();
  605. let savedTags = [];
  606. if (originTags.length !== 0) {
  607. await PageTagRelation.updatePageTags(createdPage._id, originTags);
  608. savedTags = await PageTagRelation.listTagNamesByPage(createdPage._id);
  609. this.tagEvent.emit('update', createdPage, savedTags);
  610. }
  611. const result = serializePageSecurely(createdPage);
  612. result.tags = savedTags;
  613. // TODO: resume
  614. if (isRecursively) {
  615. this.resumableDuplicateDescendants(page, newPagePath, user, shouldUseV4Process, createdPage._id);
  616. }
  617. return result;
  618. }
  619. async resumableDuplicateDescendants(page, newPagePath, user, shouldUseV4Process, createdPageId) {
  620. const descendantCountAppliedToAncestors = await this.duplicateDescendantsWithStream(page, newPagePath, user, shouldUseV4Process);
  621. await this.updateDescendantCountOfAncestors(createdPageId, descendantCountAppliedToAncestors, false);
  622. }
  623. async duplicateV4(page, newPagePath, user, isRecursively) {
  624. const Page = this.crowi.model('Page');
  625. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  626. // populate
  627. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  628. // create option
  629. const options: any = { page };
  630. options.grant = page.grant;
  631. options.grantUserGroupId = page.grantedGroup;
  632. options.grantedUserIds = page.grantedUsers;
  633. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  634. const createdPage = await Page.create(
  635. newPagePath, page.revision.body, user, options,
  636. );
  637. if (isRecursively) {
  638. this.duplicateDescendantsWithStream(page, newPagePath, user);
  639. }
  640. // take over tags
  641. const originTags = await page.findRelatedTagsById();
  642. let savedTags = [];
  643. if (originTags != null) {
  644. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  645. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  646. this.tagEvent.emit('update', createdPage, savedTags);
  647. }
  648. const result = serializePageSecurely(createdPage);
  649. result.tags = savedTags;
  650. return result;
  651. }
  652. /**
  653. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  654. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  655. */
  656. private async duplicateTags(pageIdMapping) {
  657. const PageTagRelation = mongoose.model('PageTagRelation');
  658. // convert pageId from string to ObjectId
  659. const pageIds = Object.keys(pageIdMapping);
  660. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: new mongoose.Types.ObjectId(pageId) } }) };
  661. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  662. {
  663. $match: stage,
  664. },
  665. {
  666. $group: {
  667. _id: '$relatedTag',
  668. relatedPages: { $push: '$relatedPage' },
  669. },
  670. },
  671. ]);
  672. const newPageTagRelation: any[] = [];
  673. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  674. // relatedPages
  675. relatedPages.forEach((pageId) => {
  676. newPageTagRelation.push({
  677. relatedPage: pageIdMapping[pageId], // newPageId
  678. relatedTag: _id,
  679. });
  680. });
  681. });
  682. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  683. }
  684. private async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = true) {
  685. if (shouldUseV4Process) {
  686. return this.duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix);
  687. }
  688. const Page = this.crowi.model('Page');
  689. const Revision = this.crowi.model('Revision');
  690. const pageIds = pages.map(page => page._id);
  691. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  692. // Mapping to set to the body of the new revision
  693. const pageIdRevisionMapping = {};
  694. revisions.forEach((revision) => {
  695. pageIdRevisionMapping[revision.pageId] = revision;
  696. });
  697. // key: oldPageId, value: newPageId
  698. const pageIdMapping = {};
  699. const newPages: any[] = [];
  700. const newRevisions: any[] = [];
  701. // no need to save parent here
  702. pages.forEach((page) => {
  703. const newPageId = new mongoose.Types.ObjectId();
  704. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  705. const revisionId = new mongoose.Types.ObjectId();
  706. pageIdMapping[page._id] = newPageId;
  707. let newPage;
  708. if (!page.isEmpty) {
  709. newPage = {
  710. _id: newPageId,
  711. path: newPagePath,
  712. creator: user._id,
  713. grant: page.grant,
  714. grantedGroup: page.grantedGroup,
  715. grantedUsers: page.grantedUsers,
  716. lastUpdateUser: user._id,
  717. revision: revisionId,
  718. };
  719. newRevisions.push({
  720. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  721. });
  722. }
  723. newPages.push(newPage);
  724. });
  725. await Page.insertMany(newPages, { ordered: false });
  726. await Revision.insertMany(newRevisions, { ordered: false });
  727. await this.duplicateTags(pageIdMapping);
  728. }
  729. private async duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  730. const Page = this.crowi.model('Page');
  731. const Revision = this.crowi.model('Revision');
  732. const pageIds = pages.map(page => page._id);
  733. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  734. // Mapping to set to the body of the new revision
  735. const pageIdRevisionMapping = {};
  736. revisions.forEach((revision) => {
  737. pageIdRevisionMapping[revision.pageId] = revision;
  738. });
  739. // key: oldPageId, value: newPageId
  740. const pageIdMapping = {};
  741. const newPages: any[] = [];
  742. const newRevisions: any[] = [];
  743. pages.forEach((page) => {
  744. const newPageId = new mongoose.Types.ObjectId();
  745. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  746. const revisionId = new mongoose.Types.ObjectId();
  747. pageIdMapping[page._id] = newPageId;
  748. newPages.push({
  749. _id: newPageId,
  750. path: newPagePath,
  751. creator: user._id,
  752. grant: page.grant,
  753. grantedGroup: page.grantedGroup,
  754. grantedUsers: page.grantedUsers,
  755. lastUpdateUser: user._id,
  756. revision: revisionId,
  757. });
  758. newRevisions.push({
  759. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  760. });
  761. });
  762. await Page.insertMany(newPages, { ordered: false });
  763. await Revision.insertMany(newRevisions, { ordered: false });
  764. await this.duplicateTags(pageIdMapping);
  765. }
  766. private async duplicateDescendantsWithStream(page, newPagePath, user, shouldUseV4Process = true) {
  767. if (shouldUseV4Process) {
  768. return this.duplicateDescendantsWithStreamV4(page, newPagePath, user);
  769. }
  770. const iterableFactory = new PageCursorsForDescendantsFactory(user, page, true);
  771. const readStream = await iterableFactory.generateReadable();
  772. const newPagePathPrefix = newPagePath;
  773. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  774. const duplicateDescendants = this.duplicateDescendants.bind(this);
  775. const shouldNormalizeParent = this.shouldNormalizeParent.bind(this);
  776. const normalizeParentAndDescendantCountOfDescendants = this.normalizeParentAndDescendantCountOfDescendants.bind(this);
  777. const pageEvent = this.pageEvent;
  778. let count = 0;
  779. let nNonEmptyDuplicatedPages = 0;
  780. const writeStream = new Writable({
  781. objectMode: true,
  782. async write(batch, encoding, callback) {
  783. try {
  784. count += batch.length;
  785. nNonEmptyDuplicatedPages += batch.filter(page => !page.isEmpty).length;
  786. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, shouldUseV4Process);
  787. logger.debug(`Adding pages progressing: (count=${count})`);
  788. }
  789. catch (err) {
  790. logger.error('addAllPages error on add anyway: ', err);
  791. }
  792. callback();
  793. },
  794. async final(callback) {
  795. // normalize parent of descendant pages
  796. const shouldNormalize = shouldNormalizeParent(page);
  797. if (shouldNormalize) {
  798. try {
  799. await normalizeParentAndDescendantCountOfDescendants(newPagePath);
  800. logger.info(`Successfully normalized duplicated descendant pages under "${newPagePath}"`);
  801. }
  802. catch (err) {
  803. logger.error('Failed to normalize descendants afrer duplicate:', err);
  804. throw err;
  805. }
  806. }
  807. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  808. // update path
  809. page.path = newPagePath;
  810. pageEvent.emit('syncDescendantsUpdate', page, user);
  811. callback();
  812. },
  813. });
  814. readStream
  815. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  816. .pipe(writeStream);
  817. await streamToPromise(writeStream);
  818. return nNonEmptyDuplicatedPages;
  819. }
  820. private async duplicateDescendantsWithStreamV4(page, newPagePath, user) {
  821. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  822. const newPagePathPrefix = newPagePath;
  823. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  824. const duplicateDescendants = this.duplicateDescendants.bind(this);
  825. const pageEvent = this.pageEvent;
  826. let count = 0;
  827. const writeStream = new Writable({
  828. objectMode: true,
  829. async write(batch, encoding, callback) {
  830. try {
  831. count += batch.length;
  832. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix);
  833. logger.debug(`Adding pages progressing: (count=${count})`);
  834. }
  835. catch (err) {
  836. logger.error('addAllPages error on add anyway: ', err);
  837. }
  838. callback();
  839. },
  840. final(callback) {
  841. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  842. // update path
  843. page.path = newPagePath;
  844. pageEvent.emit('syncDescendantsUpdate', page, user);
  845. callback();
  846. },
  847. });
  848. readStream
  849. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  850. .pipe(writeStream);
  851. await streamToPromise(writeStream);
  852. return count;
  853. }
  854. /*
  855. * Delete
  856. */
  857. async deletePage(page, user, options = {}, isRecursively = false) {
  858. const Page = mongoose.model('Page') as PageModel;
  859. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  860. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  861. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  862. // v4 compatible process
  863. const shouldUseV4Process = this.shouldUseV4Process(page);
  864. if (shouldUseV4Process) {
  865. return this.deletePageV4(page, user, options, isRecursively);
  866. }
  867. const newPath = Page.getDeletedPageName(page.path);
  868. const isTrashed = isTrashPage(page.path);
  869. if (isTrashed) {
  870. throw new Error('This method does NOT support deleting trashed pages.');
  871. }
  872. if (!Page.isDeletableName(page.path)) {
  873. throw new Error('Page is not deletable.');
  874. }
  875. if (!isRecursively) {
  876. // replace with an empty page
  877. const shouldReplace = await Page.exists({ parent: page._id });
  878. if (shouldReplace) {
  879. await Page.replaceTargetWithPage(page, null, true);
  880. }
  881. // update descendantCount of ancestors'
  882. await this.updateDescendantCountOfAncestors(page.parent, -1, true);
  883. // delete leaf empty pages
  884. await this.removeLeafEmptyPages(page);
  885. }
  886. let deletedPage;
  887. // update Revisions
  888. if (!page.isEmpty) {
  889. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  890. deletedPage = await Page.findByIdAndUpdate(page._id, {
  891. $set: {
  892. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  893. },
  894. }, { new: true });
  895. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  896. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  897. this.pageEvent.emit('delete', page, user);
  898. this.pageEvent.emit('create', deletedPage, user);
  899. }
  900. // TODO: resume
  901. // no await for deleteDescendantsWithStream and updateDescendantCountOfAncestors
  902. if (isRecursively) {
  903. (async() => {
  904. const deletedDescendantCount = await this.deleteDescendantsWithStream(page, user, shouldUseV4Process); // use the same process in both version v4 and v5
  905. // update descendantCount of ancestors'
  906. if (page.parent != null) {
  907. await this.updateDescendantCountOfAncestors(page.parent, (deletedDescendantCount + 1) * -1, true);
  908. // delete leaf empty pages
  909. await this.removeLeafEmptyPages(page);
  910. }
  911. })();
  912. }
  913. return deletedPage;
  914. }
  915. private async deletePageV4(page, user, options = {}, isRecursively = false) {
  916. const Page = mongoose.model('Page') as PageModel;
  917. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  918. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  919. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  920. const newPath = Page.getDeletedPageName(page.path);
  921. const isTrashed = isTrashPage(page.path);
  922. if (isTrashed) {
  923. throw new Error('This method does NOT support deleting trashed pages.');
  924. }
  925. if (!Page.isDeletableName(page.path)) {
  926. throw new Error('Page is not deletable.');
  927. }
  928. if (isRecursively) {
  929. this.deleteDescendantsWithStream(page, user);
  930. }
  931. // update Revisions
  932. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  933. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  934. $set: {
  935. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  936. },
  937. }, { new: true });
  938. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  939. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  940. this.pageEvent.emit('delete', page, user);
  941. this.pageEvent.emit('create', deletedPage, user);
  942. return deletedPage;
  943. }
  944. private async deleteDescendants(pages, user) {
  945. const Page = mongoose.model('Page') as unknown as PageModel;
  946. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  947. const deletePageOperations: any[] = [];
  948. const insertPageRedirectOperations: any[] = [];
  949. pages.forEach((page) => {
  950. const newPath = Page.getDeletedPageName(page.path);
  951. let operation;
  952. // if empty, delete completely
  953. if (page.isEmpty) {
  954. operation = {
  955. deleteOne: {
  956. filter: { _id: page._id },
  957. },
  958. };
  959. }
  960. // if not empty, set parent to null and update to trash
  961. else {
  962. operation = {
  963. updateOne: {
  964. filter: { _id: page._id },
  965. update: {
  966. $set: {
  967. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  968. },
  969. },
  970. },
  971. };
  972. insertPageRedirectOperations.push({
  973. insertOne: {
  974. document: {
  975. fromPath: page.path,
  976. toPath: newPath,
  977. },
  978. },
  979. });
  980. }
  981. deletePageOperations.push(operation);
  982. });
  983. try {
  984. await Page.bulkWrite(deletePageOperations);
  985. }
  986. catch (err) {
  987. if (err.code !== 11000) {
  988. throw new Error(`Failed to delete pages: ${err}`);
  989. }
  990. }
  991. finally {
  992. this.pageEvent.emit('syncDescendantsDelete', pages, user);
  993. }
  994. try {
  995. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  996. }
  997. catch (err) {
  998. if (err.code !== 11000) {
  999. throw Error(`Failed to create PageRedirect documents: ${err}`);
  1000. }
  1001. }
  1002. }
  1003. /**
  1004. * Create delete stream and return deleted document count
  1005. */
  1006. private async deleteDescendantsWithStream(targetPage, user, shouldUseV4Process = true): Promise<number> {
  1007. let readStream;
  1008. if (shouldUseV4Process) {
  1009. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1010. }
  1011. else {
  1012. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1013. readStream = await factory.generateReadable();
  1014. }
  1015. const deleteDescendants = this.deleteDescendants.bind(this);
  1016. let count = 0;
  1017. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1018. const writeStream = new Writable({
  1019. objectMode: true,
  1020. async write(batch, encoding, callback) {
  1021. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1022. try {
  1023. count += batch.length;
  1024. await deleteDescendants(batch, user);
  1025. logger.debug(`Deleting pages progressing: (count=${count})`);
  1026. }
  1027. catch (err) {
  1028. logger.error('deleteDescendants error on add anyway: ', err);
  1029. }
  1030. callback();
  1031. },
  1032. final(callback) {
  1033. logger.debug(`Deleting pages has completed: (totalCount=${count})`);
  1034. callback();
  1035. },
  1036. });
  1037. readStream
  1038. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1039. .pipe(writeStream);
  1040. await streamToPromise(readStream);
  1041. return nDeletedNonEmptyPages;
  1042. }
  1043. private async deleteCompletelyOperation(pageIds, pagePaths) {
  1044. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1045. const Bookmark = this.crowi.model('Bookmark');
  1046. const Comment = this.crowi.model('Comment');
  1047. const Page = this.crowi.model('Page');
  1048. const PageTagRelation = this.crowi.model('PageTagRelation');
  1049. const ShareLink = this.crowi.model('ShareLink');
  1050. const Revision = this.crowi.model('Revision');
  1051. const Attachment = this.crowi.model('Attachment');
  1052. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1053. const { attachmentService } = this.crowi;
  1054. const attachments = await Attachment.find({ page: { $in: pageIds } });
  1055. return Promise.all([
  1056. Bookmark.deleteMany({ page: { $in: pageIds } }),
  1057. Comment.deleteMany({ page: { $in: pageIds } }),
  1058. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  1059. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  1060. Revision.deleteMany({ pageId: { $in: pageIds } }),
  1061. Page.deleteMany({ $or: [{ path: { $in: pagePaths } }, { _id: { $in: pageIds } }] }),
  1062. PageRedirect.deleteMany({ $or: [{ toPath: { $in: pagePaths } }] }),
  1063. attachmentService.removeAllAttachments(attachments),
  1064. ]);
  1065. }
  1066. // delete multiple pages
  1067. private async deleteMultipleCompletely(pages, user, options = {}) {
  1068. const ids = pages.map(page => (page._id));
  1069. const paths = pages.map(page => (page.path));
  1070. logger.debug('Deleting completely', paths);
  1071. await this.deleteCompletelyOperation(ids, paths);
  1072. this.pageEvent.emit('syncDescendantsDelete', pages, user); // update as renamed page
  1073. return;
  1074. }
  1075. async deleteCompletely(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  1076. const Page = mongoose.model('Page') as PageModel;
  1077. if (isTopPage(page.path)) {
  1078. throw Error('It is forbidden to delete the top page');
  1079. }
  1080. // v4 compatible process
  1081. const shouldUseV4Process = this.shouldUseV4Process(page);
  1082. if (shouldUseV4Process) {
  1083. return this.deleteCompletelyV4(page, user, options, isRecursively, preventEmitting);
  1084. }
  1085. const ids = [page._id];
  1086. const paths = [page.path];
  1087. logger.debug('Deleting completely', paths);
  1088. // replace with an empty page
  1089. const shouldReplace = !isRecursively && !isTrashPage(page.path) && await Page.exists({ parent: page._id });
  1090. if (shouldReplace) {
  1091. await Page.replaceTargetWithPage(page);
  1092. }
  1093. await this.deleteCompletelyOperation(ids, paths);
  1094. if (!isRecursively) {
  1095. await this.updateDescendantCountOfAncestors(page.parent, -1, true);
  1096. }
  1097. // delete leaf empty pages
  1098. await this.removeLeafEmptyPages(page);
  1099. if (!page.isEmpty && !preventEmitting) {
  1100. this.pageEvent.emit('deleteCompletely', page, user);
  1101. }
  1102. // TODO: resume
  1103. if (isRecursively) {
  1104. // no await for deleteCompletelyDescendantsWithStream
  1105. (async() => {
  1106. const deletedDescendantCount = await this.deleteCompletelyDescendantsWithStream(page, user, options, shouldUseV4Process);
  1107. // update descendantCount of ancestors'
  1108. if (page.parent != null) {
  1109. await this.updateDescendantCountOfAncestors(page.parent, (deletedDescendantCount + 1) * -1, true);
  1110. }
  1111. })();
  1112. }
  1113. return;
  1114. }
  1115. private async deleteCompletelyV4(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  1116. const ids = [page._id];
  1117. const paths = [page.path];
  1118. logger.debug('Deleting completely', paths);
  1119. await this.deleteCompletelyOperation(ids, paths);
  1120. if (isRecursively) {
  1121. this.deleteCompletelyDescendantsWithStream(page, user, options);
  1122. }
  1123. if (!page.isEmpty && !preventEmitting) {
  1124. this.pageEvent.emit('deleteCompletely', page, user);
  1125. }
  1126. return;
  1127. }
  1128. async emptyTrashPage(user, options = {}) {
  1129. return this.deleteCompletelyDescendantsWithStream({ path: '/trash' }, user, options);
  1130. }
  1131. /**
  1132. * Create delete completely stream
  1133. */
  1134. private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true): Promise<number> {
  1135. let readStream;
  1136. if (shouldUseV4Process) { // pages don't have parents
  1137. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1138. }
  1139. else {
  1140. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1141. readStream = await factory.generateReadable();
  1142. }
  1143. let count = 0;
  1144. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1145. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  1146. const writeStream = new Writable({
  1147. objectMode: true,
  1148. async write(batch, encoding, callback) {
  1149. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1150. try {
  1151. count += batch.length;
  1152. await deleteMultipleCompletely(batch, user, options);
  1153. logger.debug(`Adding pages progressing: (count=${count})`);
  1154. }
  1155. catch (err) {
  1156. logger.error('addAllPages error on add anyway: ', err);
  1157. }
  1158. callback();
  1159. },
  1160. final(callback) {
  1161. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1162. callback();
  1163. },
  1164. });
  1165. readStream
  1166. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1167. .pipe(writeStream);
  1168. await streamToPromise(readStream);
  1169. return nDeletedNonEmptyPages;
  1170. }
  1171. async deleteMultiplePages(pagesToDelete, user, isCompletely: boolean, isRecursively: boolean): Promise<void> {
  1172. if (pagesToDelete.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1173. throw Error(`The maximum number of pages is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1174. }
  1175. // omit duplicate paths if isRecursively true, omit empty pages if isRecursively false
  1176. const pages = isRecursively ? omitDuplicateAreaPageFromPages(pagesToDelete) : pagesToDelete.filter(p => !p.isEmpty);
  1177. // TODO: insertMany PageOperationBlock if isRecursively true
  1178. if (isCompletely) {
  1179. for await (const page of pages) {
  1180. await this.deleteCompletely(page, user, {}, isRecursively);
  1181. }
  1182. }
  1183. else {
  1184. for await (const page of pages) {
  1185. await this.deletePage(page, user, {}, isRecursively);
  1186. }
  1187. }
  1188. }
  1189. // use the same process in both v4 and v5
  1190. private async revertDeletedDescendants(pages, user) {
  1191. const Page = this.crowi.model('Page');
  1192. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1193. const revertPageOperations: any[] = [];
  1194. const fromPathsToDelete: string[] = [];
  1195. pages.forEach((page) => {
  1196. // e.g. page.path = /trash/test, toPath = /test
  1197. const toPath = Page.getRevertDeletedPageName(page.path);
  1198. revertPageOperations.push({
  1199. updateOne: {
  1200. filter: { _id: page._id },
  1201. update: {
  1202. $set: {
  1203. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1204. },
  1205. },
  1206. },
  1207. });
  1208. fromPathsToDelete.push(page.path);
  1209. });
  1210. try {
  1211. await Page.bulkWrite(revertPageOperations);
  1212. await PageRedirect.deleteMany({ fromPath: { $in: fromPathsToDelete } });
  1213. }
  1214. catch (err) {
  1215. if (err.code !== 11000) {
  1216. throw new Error(`Failed to revert pages: ${err}`);
  1217. }
  1218. }
  1219. }
  1220. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  1221. const Page = this.crowi.model('Page');
  1222. const PageTagRelation = this.crowi.model('PageTagRelation');
  1223. // v4 compatible process
  1224. const shouldUseV4Process = this.shouldUseV4ProcessForRevert(page);
  1225. if (shouldUseV4Process) {
  1226. return this.revertDeletedPageV4(page, user, options, isRecursively);
  1227. }
  1228. const newPath = Page.getRevertDeletedPageName(page.path);
  1229. const includeEmpty = true;
  1230. const originPage = await Page.findByPath(newPath, includeEmpty);
  1231. // throw if any page already exists
  1232. if (originPage != null) {
  1233. throw Error(`This page cannot be reverted since a page with path "${originPage.path}" already exists. Rename the existing pages first.`);
  1234. }
  1235. const parent = await Page.getParentAndFillAncestors(newPath);
  1236. page.status = Page.STATUS_PUBLISHED;
  1237. page.lastUpdateUser = user;
  1238. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1239. $set: {
  1240. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null, parent: parent._id, descendantCount: 0,
  1241. },
  1242. }, { new: true });
  1243. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1244. if (isRecursively) {
  1245. await this.updateDescendantCountOfAncestors(parent._id, 1, true);
  1246. }
  1247. // TODO: resume
  1248. if (!isRecursively) {
  1249. // no await for revertDeletedDescendantsWithStream
  1250. (async() => {
  1251. const revertedDescendantCount = await this.revertDeletedDescendantsWithStream(page, user, options, shouldUseV4Process);
  1252. // update descendantCount of ancestors'
  1253. if (page.parent != null) {
  1254. await this.updateDescendantCountOfAncestors(page.parent, revertedDescendantCount + 1, true);
  1255. // delete leaf empty pages
  1256. await this.removeLeafEmptyPages(page);
  1257. }
  1258. })();
  1259. }
  1260. return updatedPage;
  1261. }
  1262. private async revertDeletedPageV4(page, user, options = {}, isRecursively = false) {
  1263. const Page = this.crowi.model('Page');
  1264. const PageTagRelation = this.crowi.model('PageTagRelation');
  1265. const newPath = Page.getRevertDeletedPageName(page.path);
  1266. const originPage = await Page.findByPath(newPath);
  1267. if (originPage != null) {
  1268. throw Error(`This page cannot be reverted since a page with path "${originPage.path}" already exists.`);
  1269. }
  1270. if (isRecursively) {
  1271. this.revertDeletedDescendantsWithStream(page, user, options);
  1272. }
  1273. page.status = Page.STATUS_PUBLISHED;
  1274. page.lastUpdateUser = user;
  1275. debug('Revert deleted the page', page, newPath);
  1276. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1277. $set: {
  1278. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1279. },
  1280. }, { new: true });
  1281. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1282. return updatedPage;
  1283. }
  1284. /**
  1285. * Create revert stream
  1286. */
  1287. private async revertDeletedDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true): Promise<number> {
  1288. if (shouldUseV4Process) {
  1289. return this.revertDeletedDescendantsWithStreamV4(targetPage, user, options);
  1290. }
  1291. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1292. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1293. const normalizeParentAndDescendantCountOfDescendants = this.normalizeParentAndDescendantCountOfDescendants.bind(this);
  1294. const shouldNormalizeParent = this.shouldNormalizeParent.bind(this);
  1295. let count = 0;
  1296. const writeStream = new Writable({
  1297. objectMode: true,
  1298. async write(batch, encoding, callback) {
  1299. try {
  1300. count += batch.length;
  1301. await revertDeletedDescendants(batch, user);
  1302. logger.debug(`Reverting pages progressing: (count=${count})`);
  1303. }
  1304. catch (err) {
  1305. logger.error('revertPages error on add anyway: ', err);
  1306. }
  1307. callback();
  1308. },
  1309. async final(callback) {
  1310. const Page = mongoose.model('Page') as unknown as PageModel;
  1311. // normalize parent of descendant pages
  1312. const shouldNormalize = shouldNormalizeParent(targetPage);
  1313. if (shouldNormalize) {
  1314. try {
  1315. const newPath = Page.getRevertDeletedPageName(targetPage.path);
  1316. await normalizeParentAndDescendantCountOfDescendants(newPath);
  1317. logger.info(`Successfully normalized reverted descendant pages under "${newPath}"`);
  1318. }
  1319. catch (err) {
  1320. logger.error('Failed to normalize descendants afrer revert:', err);
  1321. throw err;
  1322. }
  1323. }
  1324. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1325. callback();
  1326. },
  1327. });
  1328. readStream
  1329. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1330. .pipe(writeStream);
  1331. await streamToPromise(readStream);
  1332. return count;
  1333. }
  1334. private async revertDeletedDescendantsWithStreamV4(targetPage, user, options = {}) {
  1335. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1336. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1337. let count = 0;
  1338. const writeStream = new Writable({
  1339. objectMode: true,
  1340. async write(batch, encoding, callback) {
  1341. try {
  1342. count += batch.length;
  1343. await revertDeletedDescendants(batch, user);
  1344. logger.debug(`Reverting pages progressing: (count=${count})`);
  1345. }
  1346. catch (err) {
  1347. logger.error('revertPages error on add anyway: ', err);
  1348. }
  1349. callback();
  1350. },
  1351. final(callback) {
  1352. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1353. callback();
  1354. },
  1355. });
  1356. readStream
  1357. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1358. .pipe(writeStream);
  1359. await streamToPromise(readStream);
  1360. return count;
  1361. }
  1362. async handlePrivatePagesForGroupsToDelete(groupsToDelete, action, transferToUserGroupId, user) {
  1363. const Page = this.crowi.model('Page');
  1364. const pages = await Page.find({ grantedGroup: { $in: groupsToDelete } });
  1365. switch (action) {
  1366. case 'public':
  1367. await Page.publicizePages(pages);
  1368. break;
  1369. case 'delete':
  1370. return this.deleteMultipleCompletely(pages, user);
  1371. case 'transfer':
  1372. await Page.transferPagesToGroup(pages, transferToUserGroupId);
  1373. break;
  1374. default:
  1375. throw new Error('Unknown action for private pages');
  1376. }
  1377. }
  1378. private extractStringIds(refs: Ref<HasObjectId>[]) {
  1379. return refs.map((ref: Ref<HasObjectId>) => {
  1380. return (typeof ref === 'string') ? ref : ref._id.toString();
  1381. });
  1382. }
  1383. constructBasicPageInfo(page: IPage, isGuestUser?: boolean): IPageInfo | IPageInfoForEntity {
  1384. const isMovable = isGuestUser ? false : !isTopPage(page.path) && !isUserPage(page.path) && !isUserNamePage(page.path);
  1385. if (page.isEmpty) {
  1386. return {
  1387. isEmpty: true,
  1388. isMovable,
  1389. isDeletable: false,
  1390. isAbleToDeleteCompletely: false,
  1391. };
  1392. }
  1393. const likers = page.liker.slice(0, 15) as Ref<IUserHasId>[];
  1394. const seenUsers = page.seenUsers.slice(0, 15) as Ref<IUserHasId>[];
  1395. const Page = this.crowi.model('Page');
  1396. return {
  1397. isEmpty: false,
  1398. sumOfLikers: page.liker.length,
  1399. likerIds: this.extractStringIds(likers),
  1400. seenUserIds: this.extractStringIds(seenUsers),
  1401. sumOfSeenUsers: page.seenUsers.length,
  1402. isMovable,
  1403. isDeletable: Page.isDeletableName(page.path),
  1404. isAbleToDeleteCompletely: false,
  1405. };
  1406. }
  1407. async shortBodiesMapByPageIds(pageIds: ObjectId[] = [], user): Promise<Record<string, string | null>> {
  1408. const Page = mongoose.model('Page');
  1409. const MAX_LENGTH = 350;
  1410. // aggregation options
  1411. const viewerCondition = await generateGrantCondition(user, null);
  1412. const filterByIds = {
  1413. _id: { $in: pageIds },
  1414. };
  1415. let pages;
  1416. try {
  1417. pages = await Page
  1418. .aggregate([
  1419. // filter by pageIds
  1420. {
  1421. $match: filterByIds,
  1422. },
  1423. // filter by viewer
  1424. viewerCondition,
  1425. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  1426. {
  1427. $lookup: {
  1428. from: 'revisions',
  1429. let: { localRevision: '$revision' },
  1430. pipeline: [
  1431. {
  1432. $match: {
  1433. $expr: {
  1434. $eq: ['$_id', '$$localRevision'],
  1435. },
  1436. },
  1437. },
  1438. {
  1439. $project: {
  1440. // What is $substrCP?
  1441. // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
  1442. revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
  1443. },
  1444. },
  1445. ],
  1446. as: 'revisionData',
  1447. },
  1448. },
  1449. // projection
  1450. {
  1451. $project: {
  1452. _id: 1,
  1453. revisionData: 1,
  1454. },
  1455. },
  1456. ]).exec();
  1457. }
  1458. catch (err) {
  1459. logger.error('Error occurred while generating shortBodiesMap');
  1460. throw err;
  1461. }
  1462. const shortBodiesMap = {};
  1463. pages.forEach((page) => {
  1464. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  1465. });
  1466. return shortBodiesMap;
  1467. }
  1468. private async createAndSendNotifications(page, user, action) {
  1469. const { activityService, inAppNotificationService } = this.crowi;
  1470. const snapshot = stringifySnapshot(page);
  1471. // Create activity
  1472. const parameters = {
  1473. user: user._id,
  1474. targetModel: ActivityDefine.MODEL_PAGE,
  1475. target: page,
  1476. action,
  1477. };
  1478. const activity = await activityService.createByParameters(parameters);
  1479. // Get user to be notified
  1480. const targetUsers = await activity.getNotificationTargetUsers();
  1481. // Create and send notifications
  1482. await inAppNotificationService.upsertByActivity(targetUsers, activity, snapshot);
  1483. await inAppNotificationService.emitSocketIo(targetUsers);
  1484. }
  1485. async normalizeParentByPageIds(pageIds: ObjectIdLike[], user): Promise<void> {
  1486. for await (const pageId of pageIds) {
  1487. try {
  1488. const normalizedPage = await this.normalizeParentByPageId(pageId, user);
  1489. if (normalizedPage == null) {
  1490. logger.error(`Failed to update descendantCount of page of id: "${pageId}"`);
  1491. }
  1492. else {
  1493. // update descendantCount of ancestors'
  1494. await this.updateDescendantCountOfAncestors(pageId, normalizedPage.descendantCount, false);
  1495. }
  1496. }
  1497. catch (err) {
  1498. // socket.emit('normalizeParentByPageIds', { error: err.message }); TODO: use socket to tell user
  1499. }
  1500. }
  1501. }
  1502. private async normalizeParentByPageId(pageId: ObjectIdLike, user) {
  1503. const Page = mongoose.model('Page') as unknown as PageModel;
  1504. const target = await Page.findByIdAndViewerToEdit(pageId, user);
  1505. if (target == null) {
  1506. throw Error('target does not exist or forbidden');
  1507. }
  1508. const {
  1509. path, grant, grantedUsers: grantedUserIds, grantedGroup: grantedGroupId,
  1510. } = target;
  1511. // check if any page exists at target path already
  1512. const existingPage = await Page.findOne({ path });
  1513. if (existingPage != null && !existingPage.isEmpty) {
  1514. throw Error('Page already exists. Please rename the page to continue.');
  1515. }
  1516. /*
  1517. * UserGroup & Owner validation
  1518. */
  1519. if (target.grant !== Page.GRANT_RESTRICTED) {
  1520. let isGrantNormalized = false;
  1521. try {
  1522. const shouldCheckDescendants = true;
  1523. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  1524. }
  1525. catch (err) {
  1526. logger.error(`Failed to validate grant of page at "${path}"`, err);
  1527. throw err;
  1528. }
  1529. if (!isGrantNormalized) {
  1530. throw Error('This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.');
  1531. }
  1532. }
  1533. else {
  1534. throw Error('Restricted pages can not be migrated');
  1535. }
  1536. let updatedPage;
  1537. // replace if empty page exists
  1538. if (existingPage != null && existingPage.isEmpty) {
  1539. await Page.replaceTargetWithPage(existingPage, target, true);
  1540. updatedPage = await Page.findById(pageId);
  1541. }
  1542. else {
  1543. // getParentAndFillAncestors
  1544. const parent = await Page.getParentAndFillAncestors(target.path);
  1545. updatedPage = await Page.findOneAndUpdate({ _id: pageId }, { parent: parent._id }, { new: true });
  1546. }
  1547. return updatedPage;
  1548. }
  1549. // TODO: this should be resumable
  1550. async normalizeParentRecursivelyByPageIds(pageIds, user) {
  1551. const Page = mongoose.model('Page') as unknown as PageModel;
  1552. if (pageIds == null || pageIds.length === 0) {
  1553. logger.error('pageIds is null or 0 length.');
  1554. return;
  1555. }
  1556. if (pageIds.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1557. throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1558. }
  1559. let normalizablePages;
  1560. let nonNormalizablePages;
  1561. try {
  1562. [normalizablePages, nonNormalizablePages] = await this.crowi.pageGrantService.separateNormalizableAndNotNormalizablePages(pageIds);
  1563. }
  1564. catch (err) {
  1565. throw err;
  1566. }
  1567. if (normalizablePages.length === 0) {
  1568. // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
  1569. return;
  1570. }
  1571. if (nonNormalizablePages.length !== 0) {
  1572. // TODO: iterate nonNormalizablePages and send socket error to client so that the user can know which path failed to migrate
  1573. // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
  1574. }
  1575. const pagesToNormalize = omitDuplicateAreaPageFromPages(normalizablePages);
  1576. const pageIdsToNormalize = pagesToNormalize.map(p => p._id);
  1577. const pathsToNormalize = Array.from(new Set(pagesToNormalize.map(p => p.path)));
  1578. // TODO: insertMany PageOperationBlock
  1579. // for updating descendantCount
  1580. const pageIdToExDescendantCountMap = new Map<ObjectIdLike, number>();
  1581. // MAIN PROCESS migrate recursively
  1582. const regexps = pathsToNormalize.map(p => new RegExp(`^${escapeStringRegexp(p)}`, 'i'));
  1583. try {
  1584. await this.normalizeParentRecursively(null, regexps);
  1585. // find pages to save descendantCount of normalized pages (only pages in pageIds parameter of this method)
  1586. const pagesBeforeUpdatingDescendantCount = await Page.findByIdsAndViewer(pageIdsToNormalize, user);
  1587. pagesBeforeUpdatingDescendantCount.forEach((p) => {
  1588. pageIdToExDescendantCountMap.set(p._id.toString(), p.descendantCount);
  1589. });
  1590. }
  1591. catch (err) {
  1592. logger.error('V5 initial miration failed.', err);
  1593. // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
  1594. throw err;
  1595. }
  1596. // POST MAIN PROCESS update descendantCount
  1597. try {
  1598. // update descendantCount of self and descendant pages first
  1599. for await (const path of pathsToNormalize) {
  1600. await this.updateDescendantCountOfSelfAndDescendants(path);
  1601. }
  1602. // find pages again to get updated descendantCount
  1603. // then calculate inc
  1604. const pagesAfterUpdatingDescendantCount = await Page.findByIdsAndViewer(pageIdsToNormalize, user);
  1605. for await (const page of pagesAfterUpdatingDescendantCount) {
  1606. const exDescendantCount = pageIdToExDescendantCountMap.get(page._id.toString()) || 0;
  1607. const newDescendantCount = page.descendantCount;
  1608. const inc = newDescendantCount - exDescendantCount;
  1609. await this.updateDescendantCountOfAncestors(page._id, inc, false);
  1610. }
  1611. }
  1612. catch (err) {
  1613. logger.error('Failed to update descendantCount after normalizing parent:', err);
  1614. throw Error(`Failed to update descendantCount after normalizing parent: ${err}`);
  1615. }
  1616. }
  1617. async _isPagePathIndexUnique() {
  1618. const Page = this.crowi.model('Page');
  1619. const now = (new Date()).toString();
  1620. const path = `growi_check_is_path_index_unique_${now}`;
  1621. let isUnique = false;
  1622. try {
  1623. await Page.insertMany([
  1624. { path },
  1625. { path },
  1626. ]);
  1627. }
  1628. catch (err) {
  1629. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  1630. isUnique = true;
  1631. logger.info('Page path index is unique.');
  1632. }
  1633. else {
  1634. throw err;
  1635. }
  1636. }
  1637. finally {
  1638. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  1639. }
  1640. return isUnique;
  1641. }
  1642. // TODO: use socket to send status to the client
  1643. async normalizeAllPublicPages() {
  1644. // const socket = this.crowi.socketIoService.getAdminSocket();
  1645. let isUnique;
  1646. try {
  1647. isUnique = await this._isPagePathIndexUnique();
  1648. }
  1649. catch (err) {
  1650. logger.error('Failed to check path index status', err);
  1651. throw err;
  1652. }
  1653. // drop unique index first
  1654. if (isUnique) {
  1655. try {
  1656. await this._v5NormalizeIndex();
  1657. }
  1658. catch (err) {
  1659. logger.error('V5 index normalization failed.', err);
  1660. // socket.emit('v5IndexNormalizationFailed', { error: err.message });
  1661. throw err;
  1662. }
  1663. }
  1664. // then migrate
  1665. try {
  1666. const Page = mongoose.model('Page') as unknown as PageModel;
  1667. await this.normalizeParentRecursively(Page.GRANT_PUBLIC, null, true);
  1668. }
  1669. catch (err) {
  1670. logger.error('V5 initial miration failed.', err);
  1671. // socket.emit('v5InitialMirationFailed', { error: err.message });
  1672. throw err;
  1673. }
  1674. // update descendantCount of all public pages
  1675. try {
  1676. await this.updateDescendantCountOfSelfAndDescendants('/');
  1677. logger.info('Successfully updated all descendantCount of public pages.');
  1678. }
  1679. catch (err) {
  1680. logger.error('Failed updating descendantCount of public pages.', err);
  1681. throw err;
  1682. }
  1683. await this._setIsV5CompatibleTrue();
  1684. }
  1685. private async _setIsV5CompatibleTrue() {
  1686. try {
  1687. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  1688. 'app:isV5Compatible': true,
  1689. });
  1690. logger.info('Successfully migrated all public pages.');
  1691. }
  1692. catch (err) {
  1693. logger.warn('Failed to update app:isV5Compatible to true.');
  1694. throw err;
  1695. }
  1696. }
  1697. private async normalizeParentAndDescendantCountOfDescendants(path: string): Promise<void> {
  1698. const escapedPath = escapeStringRegexp(path);
  1699. const regexps = [new RegExp(`^${escapedPath}`, 'i')];
  1700. await this.normalizeParentRecursively(null, regexps);
  1701. // update descendantCount of descendant pages
  1702. await this.updateDescendantCountOfSelfAndDescendants(path);
  1703. }
  1704. // TODO: use websocket to show progress
  1705. private async normalizeParentRecursively(grant, regexps, publicOnly = false): Promise<void> {
  1706. const BATCH_SIZE = 100;
  1707. const PAGES_LIMIT = 1000;
  1708. const Page = mongoose.model('Page') as unknown as PageModel;
  1709. const { PageQueryBuilder } = Page;
  1710. // GRANT_RESTRICTED and GRANT_SPECIFIED will never have parent
  1711. const grantFilter: any = {
  1712. $and: [
  1713. { grant: { $ne: Page.GRANT_RESTRICTED } },
  1714. { grant: { $ne: Page.GRANT_SPECIFIED } },
  1715. ],
  1716. };
  1717. if (grant != null) { // add grant condition if not null
  1718. grantFilter.$and = [...grantFilter.$and, { grant }];
  1719. }
  1720. // generate filter
  1721. const filter: any = {
  1722. $and: [
  1723. {
  1724. parent: null,
  1725. status: Page.STATUS_PUBLISHED,
  1726. path: { $ne: '/' },
  1727. },
  1728. ],
  1729. };
  1730. if (regexps != null && regexps.length !== 0) {
  1731. filter.$and.push({
  1732. parent: null,
  1733. status: Page.STATUS_PUBLISHED,
  1734. path: { $in: regexps },
  1735. });
  1736. }
  1737. const total = await Page.countDocuments(filter);
  1738. let baseAggregation = Page
  1739. .aggregate([
  1740. { $match: grantFilter },
  1741. { $match: filter },
  1742. {
  1743. $project: { // minimize data to fetch
  1744. _id: 1,
  1745. path: 1,
  1746. },
  1747. },
  1748. ]);
  1749. // limit pages to get
  1750. if (total > PAGES_LIMIT) {
  1751. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  1752. }
  1753. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  1754. // use batch stream
  1755. const batchStream = createBatchStream(BATCH_SIZE);
  1756. let countPages = 0;
  1757. let shouldContinue = true;
  1758. // migrate all siblings for each page
  1759. const migratePagesStream = new Writable({
  1760. objectMode: true,
  1761. async write(pages, encoding, callback) {
  1762. // make list to create empty pages
  1763. const parentPathsSet = new Set<string>(pages.map(page => pathlib.dirname(page.path)));
  1764. const parentPaths = Array.from(parentPathsSet);
  1765. // fill parents with empty pages
  1766. await Page.createEmptyPagesByPaths(parentPaths, publicOnly);
  1767. // find parents again
  1768. const builder = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }), true);
  1769. const parents = await builder
  1770. .addConditionToListByPathsArray(parentPaths)
  1771. .query
  1772. .lean()
  1773. .exec();
  1774. // bulkWrite to update parent
  1775. const updateManyOperations = parents.map((parent) => {
  1776. const parentId = parent._id;
  1777. // modify to adjust for RegExp
  1778. let parentPath = parent.path === '/' ? '' : parent.path;
  1779. parentPath = escapeStringRegexp(parentPath);
  1780. const filter: any = {
  1781. // regexr.com/6889f
  1782. // ex. /parent/any_child OR /any_level1
  1783. path: { $regex: new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`, 'i') },
  1784. };
  1785. if (grant != null) {
  1786. filter.grant = grant;
  1787. }
  1788. return {
  1789. updateMany: {
  1790. filter,
  1791. update: {
  1792. parent: parentId,
  1793. },
  1794. },
  1795. };
  1796. });
  1797. try {
  1798. const res = await Page.bulkWrite(updateManyOperations);
  1799. countPages += res.result.nModified;
  1800. logger.info(`Page migration processing: (count=${countPages})`);
  1801. // throw
  1802. if (res.result.writeErrors.length > 0) {
  1803. logger.error('Failed to migrate some pages', res.result.writeErrors);
  1804. throw Error('Failed to migrate some pages');
  1805. }
  1806. // finish migration
  1807. if (res.result.nModified === 0 && res.result.nMatched === 0) {
  1808. shouldContinue = false;
  1809. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  1810. }
  1811. }
  1812. catch (err) {
  1813. logger.error('Failed to update page.parent.', err);
  1814. throw err;
  1815. }
  1816. callback();
  1817. },
  1818. final(callback) {
  1819. callback();
  1820. },
  1821. });
  1822. pagesStream
  1823. .pipe(batchStream)
  1824. .pipe(migratePagesStream);
  1825. await streamToPromise(migratePagesStream);
  1826. const existsFilter = { $and: [...grantFilter.$and, ...filter.$and] };
  1827. if (await Page.exists(existsFilter) && shouldContinue) {
  1828. return this.normalizeParentRecursively(grant, regexps, publicOnly);
  1829. }
  1830. }
  1831. private async _v5NormalizeIndex() {
  1832. const collection = mongoose.connection.collection('pages');
  1833. try {
  1834. // drop pages.path_1 indexes
  1835. await collection.dropIndex('path_1');
  1836. logger.info('Succeeded to drop unique indexes from pages.path.');
  1837. }
  1838. catch (err) {
  1839. logger.warn('Failed to drop unique indexes from pages.path.', err);
  1840. throw err;
  1841. }
  1842. try {
  1843. // create indexes without
  1844. await collection.createIndex({ path: 1 }, { unique: false });
  1845. logger.info('Succeeded to create non-unique indexes on pages.path.');
  1846. }
  1847. catch (err) {
  1848. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  1849. throw err;
  1850. }
  1851. }
  1852. async countPagesCanNormalizeParentByUser(user): Promise<number> {
  1853. if (user == null) {
  1854. throw Error('user is required');
  1855. }
  1856. const Page = mongoose.model('Page') as unknown as PageModel;
  1857. const { PageQueryBuilder } = Page;
  1858. const builder = new PageQueryBuilder(Page.count(), false);
  1859. builder.addConditionAsNotMigrated();
  1860. builder.addConditionAsNonRootPage();
  1861. builder.addConditionToExcludeTrashed();
  1862. await builder.addConditionForParentNormalization(user);
  1863. const nMigratablePages = await builder.query.exec();
  1864. return nMigratablePages;
  1865. }
  1866. /**
  1867. * update descendantCount of the following pages
  1868. * - page that has the same path as the provided path
  1869. * - pages that are descendants of the above page
  1870. */
  1871. async updateDescendantCountOfSelfAndDescendants(path: string): Promise<void> {
  1872. const BATCH_SIZE = 200;
  1873. const Page = this.crowi.model('Page');
  1874. const aggregateCondition = Page.getAggrConditionForPageWithProvidedPathAndDescendants(path);
  1875. const aggregatedPages = await Page.aggregate(aggregateCondition).cursor({ batchSize: BATCH_SIZE });
  1876. const recountWriteStream = new Writable({
  1877. objectMode: true,
  1878. async write(pageDocuments, encoding, callback) {
  1879. for await (const document of pageDocuments) {
  1880. const descendantCount = await Page.recountDescendantCount(document._id);
  1881. await Page.findByIdAndUpdate(document._id, { descendantCount });
  1882. }
  1883. callback();
  1884. },
  1885. final(callback) {
  1886. callback();
  1887. },
  1888. });
  1889. aggregatedPages
  1890. .pipe(createBatchStream(BATCH_SIZE))
  1891. .pipe(recountWriteStream);
  1892. await streamToPromise(recountWriteStream);
  1893. }
  1894. // update descendantCount of all pages that are ancestors of a provided pageId by count
  1895. async updateDescendantCountOfAncestors(pageId: ObjectIdLike, inc: number, shouldIncludeTarget: boolean): Promise<void> {
  1896. const Page = this.crowi.model('Page');
  1897. const ancestors = await Page.findAncestorsUsingParentRecursively(pageId, shouldIncludeTarget);
  1898. const ancestorPageIds = ancestors.map(p => p._id);
  1899. await Page.incrementDescendantCountOfPageIds(ancestorPageIds, inc);
  1900. }
  1901. }
  1902. export default PageService;