page.ts 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736
  1. import pathlib from 'path';
  2. import { Readable, Writable } from 'stream';
  3. import {
  4. pagePathUtils, pathUtils, Ref, HasObjectId,
  5. IUserHasId,
  6. IPage, IPageInfo, IPageInfoAll, IPageInfoForEntity, IPageWithMeta,
  7. } from '@growi/core';
  8. import escapeStringRegexp from 'escape-string-regexp';
  9. import mongoose, { ObjectId, QueryCursor } from 'mongoose';
  10. import streamToPromise from 'stream-to-promise';
  11. import { SupportedAction } from '~/interfaces/activity';
  12. import { V5ConversionErrCode } from '~/interfaces/errors/v5-conversion-error';
  13. import {
  14. PageDeleteConfigValue, IPageDeleteConfigValueToProcessValidation,
  15. } from '~/interfaces/page-delete-config';
  16. import {
  17. IPageOperationProcessInfo, IPageOperationProcessData, PageActionStage, PageActionType,
  18. } from '~/interfaces/page-operation';
  19. import { PageMigrationErrorData, SocketEventName, UpdateDescCountRawData } from '~/interfaces/websocket';
  20. import {
  21. CreateMethod, PageCreateOptions, PageModel, PageDocument, pushRevision, PageQueryBuilder,
  22. } from '~/server/models/page';
  23. import { createBatchStream } from '~/server/util/batch-stream';
  24. import loggerFactory from '~/utils/logger';
  25. import { prepareDeleteConfigValuesForCalc } from '~/utils/page-delete-config';
  26. import { ObjectIdLike } from '../interfaces/mongoose-utils';
  27. import { PathAlreadyExistsError } from '../models/errors';
  28. import PageOperation, { PageOperationDocument } from '../models/page-operation';
  29. import { PageRedirectModel } from '../models/page-redirect';
  30. import { serializePageSecurely } from '../models/serializers/page-serializer';
  31. import Subscription from '../models/subscription';
  32. import { V5ConversionError } from '../models/vo/v5-conversion-error';
  33. const debug = require('debug')('growi:services:page');
  34. const logger = loggerFactory('growi:services:page');
  35. const {
  36. isTrashPage, isTopPage, omitDuplicateAreaPageFromPages,
  37. collectAncestorPaths, isMovablePage, canMoveByPath, isUsersProtectedPages, hasSlash, generateChildrenRegExp,
  38. } = pagePathUtils;
  39. const { addTrailingSlash } = pathUtils;
  40. const BULK_REINDEX_SIZE = 100;
  41. const LIMIT_FOR_MULTIPLE_PAGE_OP = 20;
  42. // TODO: improve type
  43. class PageCursorsForDescendantsFactory {
  44. private user: any; // TODO: Typescriptize model
  45. private rootPage: any; // TODO: wait for mongoose update
  46. private shouldIncludeEmpty: boolean;
  47. private initialCursor: QueryCursor<any> | never[]; // TODO: wait for mongoose update
  48. private Page: PageModel;
  49. constructor(user: any, rootPage: any, shouldIncludeEmpty: boolean) {
  50. this.user = user;
  51. this.rootPage = rootPage;
  52. this.shouldIncludeEmpty = shouldIncludeEmpty;
  53. this.Page = mongoose.model('Page') as unknown as PageModel;
  54. }
  55. // prepare initial cursor
  56. private async init() {
  57. const initialCursor = await this.generateCursorToFindChildren(this.rootPage);
  58. this.initialCursor = initialCursor;
  59. }
  60. /**
  61. * Returns Iterable that yields only descendant pages unorderedly
  62. * @returns Promise<AsyncGenerator>
  63. */
  64. async generateIterable(): Promise<AsyncGenerator | never[]> {
  65. // initialize cursor
  66. await this.init();
  67. return this.isNeverArray(this.initialCursor) ? [] : this.generateOnlyDescendants(this.initialCursor);
  68. }
  69. /**
  70. * Returns Readable that produces only descendant pages unorderedly
  71. * @returns Promise<Readable>
  72. */
  73. async generateReadable(): Promise<Readable> {
  74. return Readable.from(await this.generateIterable());
  75. }
  76. /**
  77. * Generator that unorderedly yields descendant pages
  78. */
  79. private async* generateOnlyDescendants(cursor: QueryCursor<any>) {
  80. for await (const page of cursor) {
  81. const nextCursor = await this.generateCursorToFindChildren(page);
  82. if (!this.isNeverArray(nextCursor)) {
  83. yield* this.generateOnlyDescendants(nextCursor); // recursively yield
  84. }
  85. yield page;
  86. }
  87. }
  88. private async generateCursorToFindChildren(page: any): Promise<QueryCursor<any> | never[]> {
  89. if (page == null) {
  90. return [];
  91. }
  92. const { PageQueryBuilder } = this.Page;
  93. const builder = new PageQueryBuilder(this.Page.find(), this.shouldIncludeEmpty);
  94. builder.addConditionToFilteringByParentId(page._id);
  95. const cursor = builder.query.lean().cursor({ batchSize: BULK_REINDEX_SIZE }) as QueryCursor<any>;
  96. return cursor;
  97. }
  98. private isNeverArray(val: QueryCursor<any> | never[]): val is never[] {
  99. return 'length' in val && val.length === 0;
  100. }
  101. }
  102. class PageService {
  103. crowi: any;
  104. pageEvent: any;
  105. tagEvent: any;
  106. activityEvent: any;
  107. constructor(crowi) {
  108. this.crowi = crowi;
  109. this.pageEvent = crowi.event('page');
  110. this.tagEvent = crowi.event('tag');
  111. this.activityEvent = crowi.event('activity');
  112. // init
  113. this.initPageEvent();
  114. }
  115. private initPageEvent() {
  116. // create
  117. this.pageEvent.on('create', this.pageEvent.onCreate);
  118. // createMany
  119. this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
  120. this.pageEvent.on('addSeenUsers', this.pageEvent.onAddSeenUsers);
  121. }
  122. canDeleteCompletely(path: string, creatorId: ObjectIdLike, operator: any | null, isRecursively: boolean): boolean {
  123. if (operator == null || isTopPage(path) || isUsersProtectedPages(path)) return false;
  124. const pageCompleteDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageCompleteDeletionAuthority');
  125. const pageRecursiveCompleteDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageRecursiveCompleteDeletionAuthority');
  126. const [singleAuthority, recursiveAuthority] = prepareDeleteConfigValuesForCalc(pageCompleteDeletionAuthority, pageRecursiveCompleteDeletionAuthority);
  127. return this.canDeleteLogic(creatorId, operator, isRecursively, singleAuthority, recursiveAuthority);
  128. }
  129. canDelete(path: string, creatorId: ObjectIdLike, operator: any | null, isRecursively: boolean): boolean {
  130. if (operator == null || isUsersProtectedPages(path) || isTopPage(path)) return false;
  131. const pageDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageDeletionAuthority');
  132. const pageRecursiveDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageRecursiveDeletionAuthority');
  133. const [singleAuthority, recursiveAuthority] = prepareDeleteConfigValuesForCalc(pageDeletionAuthority, pageRecursiveDeletionAuthority);
  134. return this.canDeleteLogic(creatorId, operator, isRecursively, singleAuthority, recursiveAuthority);
  135. }
  136. private canDeleteLogic(
  137. creatorId: ObjectIdLike,
  138. operator,
  139. isRecursively: boolean,
  140. authority: IPageDeleteConfigValueToProcessValidation | null,
  141. recursiveAuthority: IPageDeleteConfigValueToProcessValidation | null,
  142. ): boolean {
  143. const isAdmin = operator?.admin ?? false;
  144. const isOperator = operator?._id == null ? false : operator._id.equals(creatorId);
  145. if (isRecursively) {
  146. return this.compareDeleteConfig(isAdmin, isOperator, recursiveAuthority);
  147. }
  148. return this.compareDeleteConfig(isAdmin, isOperator, authority);
  149. }
  150. private compareDeleteConfig(isAdmin: boolean, isOperator: boolean, authority: IPageDeleteConfigValueToProcessValidation | null): boolean {
  151. if (isAdmin) {
  152. return true;
  153. }
  154. if (authority === PageDeleteConfigValue.Anyone || authority == null) {
  155. return true;
  156. }
  157. if (authority === PageDeleteConfigValue.AdminAndAuthor && isOperator) {
  158. return true;
  159. }
  160. return false;
  161. }
  162. filterPagesByCanDeleteCompletely(pages, user, isRecursively: boolean) {
  163. return pages.filter(p => p.isEmpty || this.canDeleteCompletely(p.path, p.creator, user, isRecursively));
  164. }
  165. filterPagesByCanDelete(pages, user, isRecursively: boolean) {
  166. return pages.filter(p => p.isEmpty || this.canDelete(p.path, p.creator, user, isRecursively));
  167. }
  168. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  169. async findPageAndMetaDataByViewer(
  170. pageId: string, path: string, user: IUserHasId, includeEmpty = false, isSharedPage = false,
  171. ): Promise<IPageWithMeta<IPageInfoAll>|null> {
  172. const Page = this.crowi.model('Page') as PageModel;
  173. let page: PageDocument & HasObjectId | null;
  174. if (pageId != null) { // prioritized
  175. page = await Page.findByIdAndViewer(pageId, user, null, includeEmpty);
  176. }
  177. else {
  178. page = await Page.findByPathAndViewer(path, user, null, true, includeEmpty);
  179. }
  180. if (page == null) {
  181. return null;
  182. }
  183. if (isSharedPage) {
  184. return {
  185. data: page,
  186. meta: {
  187. isV5Compatible: isTopPage(page.path) || page.parent != null,
  188. isEmpty: page.isEmpty,
  189. isMovable: false,
  190. isDeletable: false,
  191. isAbleToDeleteCompletely: false,
  192. isRevertible: false,
  193. },
  194. };
  195. }
  196. const isGuestUser = user == null;
  197. const pageInfo = this.constructBasicPageInfo(page, isGuestUser);
  198. const Bookmark = this.crowi.model('Bookmark');
  199. const bookmarkCount = await Bookmark.countByPageId(pageId);
  200. const metadataForGuest = {
  201. ...pageInfo,
  202. bookmarkCount,
  203. };
  204. if (isGuestUser) {
  205. return {
  206. data: page,
  207. meta: metadataForGuest,
  208. };
  209. }
  210. const isBookmarked: boolean = (await Bookmark.findByPageIdAndUserId(pageId, user._id)) != null;
  211. const isLiked: boolean = page.isLiked(user);
  212. const subscription = await Subscription.findByUserIdAndTargetId(user._id, pageId);
  213. let creatorId = page.creator;
  214. if (page.isEmpty) {
  215. // Need non-empty ancestor page to get its creatorId because empty page does NOT have it.
  216. // Use creatorId of ancestor page to determine whether the empty page is deletable
  217. const notEmptyClosestAncestor = await Page.findNonEmptyClosestAncestor(page.path);
  218. creatorId = notEmptyClosestAncestor.creator;
  219. }
  220. const isDeletable = this.canDelete(page.path, creatorId, user, false);
  221. const isAbleToDeleteCompletely = this.canDeleteCompletely(page.path, creatorId, user, false); // use normal delete config
  222. return {
  223. data: page,
  224. meta: {
  225. ...metadataForGuest,
  226. isDeletable,
  227. isAbleToDeleteCompletely,
  228. isBookmarked,
  229. isLiked,
  230. subscriptionStatus: subscription?.status,
  231. },
  232. };
  233. }
  234. private shouldUseV4Process(page): boolean {
  235. const Page = mongoose.model('Page') as unknown as PageModel;
  236. const isTrashPage = page.status === Page.STATUS_DELETED;
  237. const isPageMigrated = page.parent != null;
  238. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  239. const isRoot = isTopPage(page.path);
  240. const isPageRestricted = page.grant === Page.GRANT_RESTRICTED;
  241. const shouldUseV4Process = !isRoot && (!isV5Compatible || !isPageMigrated || isTrashPage || isPageRestricted);
  242. return shouldUseV4Process;
  243. }
  244. private shouldUseV4ProcessForRevert(page): boolean {
  245. const Page = mongoose.model('Page') as unknown as PageModel;
  246. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  247. const isPageRestricted = page.grant === Page.GRANT_RESTRICTED;
  248. const shouldUseV4Process = !isV5Compatible || isPageRestricted;
  249. return shouldUseV4Process;
  250. }
  251. private shouldNormalizeParent(page): boolean {
  252. const Page = mongoose.model('Page') as unknown as PageModel;
  253. return page.grant !== Page.GRANT_RESTRICTED && page.grant !== Page.GRANT_SPECIFIED;
  254. }
  255. /**
  256. * Generate read stream to operate descendants of the specified page path
  257. * @param {string} targetPagePath
  258. * @param {User} viewer
  259. */
  260. private async generateReadStreamToOperateOnlyDescendants(targetPagePath, userToOperate) {
  261. const Page = this.crowi.model('Page');
  262. const { PageQueryBuilder } = Page;
  263. const builder = new PageQueryBuilder(Page.find(), true)
  264. .addConditionAsNotMigrated() // to avoid affecting v5 pages
  265. .addConditionToListOnlyDescendants(targetPagePath);
  266. await Page.addConditionToFilteringByViewerToEdit(builder, userToOperate);
  267. return builder
  268. .query
  269. .lean()
  270. .cursor({ batchSize: BULK_REINDEX_SIZE });
  271. }
  272. async renamePage(page: IPage, newPagePath, user, options, activityParameters): Promise<PageDocument | null> {
  273. /*
  274. * Common Operation
  275. */
  276. const Page = mongoose.model('Page') as unknown as PageModel;
  277. const parameters = {
  278. ip: activityParameters.ip,
  279. endpoint: activityParameters.endpoint,
  280. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_RENAME : SupportedAction.ACTION_PAGE_RENAME,
  281. user,
  282. targetModel: 'Page',
  283. target: page,
  284. snapshot: {
  285. username: user.username,
  286. },
  287. };
  288. const activity = await this.crowi.activityService.createActivity(parameters);
  289. const isExist = await Page.exists({ path: newPagePath });
  290. if (isExist) {
  291. throw Error(`Page already exists at ${newPagePath}`);
  292. }
  293. if (isTopPage(page.path)) {
  294. throw Error('It is forbidden to rename the top page');
  295. }
  296. // Separate v4 & v5 process
  297. const shouldUseV4Process = this.shouldUseV4Process(page);
  298. if (shouldUseV4Process) {
  299. return this.renamePageV4(page, newPagePath, user, options);
  300. }
  301. if (options.isMoveMode) {
  302. const fromPath = page.path;
  303. const toPath = newPagePath;
  304. const canMove = canMoveByPath(fromPath, toPath) && await Page.exists({ path: newPagePath });
  305. if (!canMove) {
  306. throw Error('Cannot move to this path.');
  307. }
  308. }
  309. const canOperate = await this.crowi.pageOperationService.canOperate(true, page.path, newPagePath);
  310. if (!canOperate) {
  311. throw Error(`Cannot operate rename to path "${newPagePath}" right now.`);
  312. }
  313. /*
  314. * Resumable Operation
  315. */
  316. let pageOp;
  317. try {
  318. pageOp = await PageOperation.create({
  319. actionType: PageActionType.Rename,
  320. actionStage: PageActionStage.Main,
  321. page,
  322. user,
  323. fromPath: page.path,
  324. toPath: newPagePath,
  325. options,
  326. });
  327. }
  328. catch (err) {
  329. logger.error('Failed to create PageOperation document.', err);
  330. throw err;
  331. }
  332. let renamedPage: PageDocument | null = null;
  333. try {
  334. renamedPage = await this.renameMainOperation(page, newPagePath, user, options, pageOp._id, activity);
  335. }
  336. catch (err) {
  337. logger.error('Error occurred while running renameMainOperation', err);
  338. // cleanup
  339. await PageOperation.deleteOne({ _id: pageOp._id });
  340. throw err;
  341. }
  342. if (page.descendantCount < 1) {
  343. this.activityEvent.emit('updated', activity, page);
  344. }
  345. return renamedPage;
  346. }
  347. async renameMainOperation(page, newPagePath: string, user, options, pageOpId: ObjectIdLike, activity?): Promise<PageDocument | null> {
  348. const Page = mongoose.model('Page') as unknown as PageModel;
  349. const updateMetadata = options.updateMetadata || false;
  350. // sanitize path
  351. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  352. // UserGroup & Owner validation
  353. // use the parent's grant when target page is an empty page
  354. let grant;
  355. let grantedUserIds;
  356. let grantedGroupId;
  357. if (page.isEmpty) {
  358. const parent = await Page.findOne({ _id: page.parent });
  359. if (parent == null) {
  360. throw Error('parent not found');
  361. }
  362. grant = parent.grant;
  363. grantedUserIds = parent.grantedUsers;
  364. grantedGroupId = parent.grantedGroup;
  365. }
  366. else {
  367. grant = page.grant;
  368. grantedUserIds = page.grantedUsers;
  369. grantedGroupId = page.grantedGroup;
  370. }
  371. if (grant !== Page.GRANT_RESTRICTED) {
  372. let isGrantNormalized = false;
  373. try {
  374. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, newPagePath, grant, grantedUserIds, grantedGroupId, false);
  375. }
  376. catch (err) {
  377. logger.error(`Failed to validate grant of page at "${newPagePath}" when renaming`, err);
  378. throw err;
  379. }
  380. if (!isGrantNormalized) {
  381. throw Error(`This page cannot be renamed to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  382. }
  383. }
  384. // 1. Take target off from tree
  385. await Page.takeOffFromTree(page._id);
  386. // 2. Find new parent
  387. let newParent;
  388. // If renaming to under target, run getParentAndforceCreateEmptyTree to fill new ancestors
  389. if (this.isRenamingToUnderTarget(page.path, newPagePath)) {
  390. newParent = await this.getParentAndforceCreateEmptyTree(page, newPagePath);
  391. }
  392. else {
  393. newParent = await this.getParentAndFillAncestorsByUser(user, newPagePath);
  394. }
  395. // 3. Put back target page to tree (also update the other attrs)
  396. const update: Partial<IPage> = {};
  397. update.path = newPagePath;
  398. update.parent = newParent._id;
  399. if (updateMetadata) {
  400. update.lastUpdateUser = user;
  401. update.updatedAt = new Date();
  402. }
  403. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  404. // 5.increase parent's descendantCount.
  405. // see: https://dev.growi.org/62149d019311629d4ecd91cf#Handling%20of%20descendantCount%20in%20case%20of%20unexpected%20process%20interruption
  406. const nToIncreaseForOperationInterruption = 1;
  407. await Page.incrementDescendantCountOfPageIds([newParent._id], nToIncreaseForOperationInterruption);
  408. // create page redirect
  409. if (options.createRedirectPage) {
  410. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  411. await PageRedirect.create({ fromPath: page.path, toPath: newPagePath });
  412. }
  413. this.pageEvent.emit('rename');
  414. // Set to Sub
  415. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  416. if (pageOp == null) {
  417. throw Error('PageOperation document not found');
  418. }
  419. /*
  420. * Sub Operation
  421. */
  422. this.renameSubOperation(page, newPagePath, user, options, renamedPage, pageOp._id, activity);
  423. return renamedPage;
  424. }
  425. async renameSubOperation(page, newPagePath: string, user, options, renamedPage, pageOpId: ObjectIdLike, activity?): Promise<void> {
  426. const Page = mongoose.model('Page') as unknown as PageModel;
  427. const exParentId = page.parent;
  428. const timerObj = this.crowi.pageOperationService.autoUpdateExpiryDate(pageOpId);
  429. try {
  430. // update descendants first
  431. const descendantsSubscribedSets = new Set();
  432. await this.renameDescendantsWithStream(page, newPagePath, user, options, false, descendantsSubscribedSets);
  433. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets);
  434. this.activityEvent.emit('updated', activity, page, descendantsSubscribedUsers);
  435. }
  436. catch (err) {
  437. logger.warn(err);
  438. throw Error(err);
  439. }
  440. finally {
  441. this.crowi.pageOperationService.clearAutoUpdateInterval(timerObj);
  442. }
  443. // reduce parent's descendantCount
  444. // see: https://dev.growi.org/62149d019311629d4ecd91cf#Handling%20of%20descendantCount%20in%20case%20of%20unexpected%20process%20interruption
  445. const nToReduceForOperationInterruption = -1;
  446. await Page.incrementDescendantCountOfPageIds([renamedPage.parent], nToReduceForOperationInterruption);
  447. const nToReduce = -1 * ((page.isEmpty ? 0 : 1) + page.descendantCount);
  448. await this.updateDescendantCountOfAncestors(exParentId, nToReduce, true);
  449. // increase ancestore's descendantCount
  450. const nToIncrease = (renamedPage.isEmpty ? 0 : 1) + page.descendantCount;
  451. await this.updateDescendantCountOfAncestors(renamedPage._id, nToIncrease, false);
  452. // Remove leaf empty pages if not moving to under the ex-target position
  453. if (!this.isRenamingToUnderTarget(page.path, newPagePath)) {
  454. // remove empty pages at leaf position
  455. await Page.removeLeafEmptyPagesRecursively(page.parent);
  456. }
  457. await PageOperation.findByIdAndDelete(pageOpId);
  458. }
  459. async resumeRenameSubOperation(renamedPage: PageDocument, pageOp: PageOperationDocument, activity?): Promise<void> {
  460. const isProcessable = pageOp.isProcessable();
  461. if (!isProcessable) {
  462. throw Error('This page operation is currently being processed');
  463. }
  464. if (pageOp.toPath == null) {
  465. throw Error(`Property toPath is missing which is needed to resume rename operation(${pageOp._id})`);
  466. }
  467. const {
  468. page, fromPath, toPath, options, user,
  469. } = pageOp;
  470. this.fixPathsAndDescendantCountOfAncestors(page, user, options, renamedPage, pageOp._id, fromPath, toPath, activity);
  471. }
  472. /**
  473. * Renaming paths and fixing descendantCount of ancestors. It shoud be run synchronously.
  474. * `renameSubOperation` to restart rename operation
  475. * `updateDescendantCountOfPagesWithPaths` to fix descendantCount of ancestors
  476. */
  477. private async fixPathsAndDescendantCountOfAncestors(page, user, options, renamedPage, pageOpId, fromPath, toPath, activity?): Promise<void> {
  478. await this.renameSubOperation(page, toPath, user, options, renamedPage, pageOpId, activity);
  479. const ancestorsPaths = this.crowi.pageOperationService.getAncestorsPathsByFromAndToPath(fromPath, toPath);
  480. await this.updateDescendantCountOfPagesWithPaths(ancestorsPaths);
  481. }
  482. private isRenamingToUnderTarget(fromPath: string, toPath: string): boolean {
  483. const pathToTest = escapeStringRegexp(addTrailingSlash(fromPath));
  484. const pathToBeTested = toPath;
  485. return (new RegExp(`^${pathToTest}`, 'i')).test(pathToBeTested);
  486. }
  487. private async getParentAndforceCreateEmptyTree(originalPage, toPath: string) {
  488. const Page = mongoose.model('Page') as unknown as PageModel;
  489. const fromPath = originalPage.path;
  490. const newParentPath = pathlib.dirname(toPath);
  491. // local util
  492. const collectAncestorPathsUntilFromPath = (path: string, paths: string[] = []): string[] => {
  493. if (path === fromPath) return paths;
  494. const parentPath = pathlib.dirname(path);
  495. paths.push(parentPath);
  496. return collectAncestorPathsUntilFromPath(parentPath, paths);
  497. };
  498. const pathsToInsert = collectAncestorPathsUntilFromPath(toPath);
  499. const originalParent = await Page.findById(originalPage.parent);
  500. if (originalParent == null) {
  501. throw Error('Original parent not found');
  502. }
  503. const insertedPages = await Page.insertMany(pathsToInsert.map((path) => {
  504. return {
  505. path,
  506. isEmpty: true,
  507. };
  508. }));
  509. const pages = [...insertedPages, originalParent];
  510. const ancestorsMap = new Map<string, PageDocument & {_id: any}>(pages.map(p => [p.path, p]));
  511. // bulkWrite to update ancestors
  512. const operations = insertedPages.map((page) => {
  513. const parentPath = pathlib.dirname(page.path);
  514. const op = {
  515. updateOne: {
  516. filter: {
  517. _id: page._id,
  518. },
  519. update: {
  520. $set: {
  521. parent: ancestorsMap.get(parentPath)?._id,
  522. descedantCount: originalParent.descendantCount,
  523. },
  524. },
  525. },
  526. };
  527. return op;
  528. });
  529. await Page.bulkWrite(operations);
  530. const newParent = ancestorsMap.get(newParentPath);
  531. return newParent;
  532. }
  533. private async renamePageV4(page, newPagePath, user, options) {
  534. const Page = this.crowi.model('Page');
  535. const Revision = this.crowi.model('Revision');
  536. const {
  537. isRecursively = false,
  538. createRedirectPage = false,
  539. updateMetadata = false,
  540. } = options;
  541. // sanitize path
  542. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  543. // create descendants first
  544. if (isRecursively) {
  545. await this.renameDescendantsWithStream(page, newPagePath, user, options);
  546. }
  547. const update: any = {};
  548. // update Page
  549. update.path = newPagePath;
  550. if (updateMetadata) {
  551. update.lastUpdateUser = user;
  552. update.updatedAt = Date.now();
  553. }
  554. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  555. // update Rivisions
  556. await Revision.updateRevisionListByPageId(renamedPage._id, { pageId: renamedPage._id });
  557. if (createRedirectPage) {
  558. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  559. await PageRedirect.create({ fromPath: page.path, toPath: newPagePath });
  560. }
  561. this.pageEvent.emit('rename');
  562. return renamedPage;
  563. }
  564. private async renameDescendants(pages, user, options, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = true) {
  565. // v4 compatible process
  566. if (shouldUseV4Process) {
  567. return this.renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix);
  568. }
  569. const Page = mongoose.model('Page') as unknown as PageModel;
  570. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  571. const { updateMetadata, createRedirectPage } = options;
  572. const updatePathOperations: any[] = [];
  573. const insertPageRedirectOperations: any[] = [];
  574. pages.forEach((page) => {
  575. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  576. // increment updatePathOperations
  577. let update;
  578. if (!page.isEmpty && updateMetadata) {
  579. update = {
  580. $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() },
  581. };
  582. }
  583. else {
  584. update = {
  585. $set: { path: newPagePath },
  586. };
  587. }
  588. if (!page.isEmpty && createRedirectPage) {
  589. // insert PageRedirect
  590. insertPageRedirectOperations.push({
  591. insertOne: {
  592. document: {
  593. fromPath: page.path,
  594. toPath: newPagePath,
  595. },
  596. },
  597. });
  598. }
  599. updatePathOperations.push({
  600. updateOne: {
  601. filter: {
  602. _id: page._id,
  603. },
  604. update,
  605. },
  606. });
  607. });
  608. try {
  609. await Page.bulkWrite(updatePathOperations);
  610. }
  611. catch (err) {
  612. if (err.code !== 11000) {
  613. throw new Error(`Failed to rename pages: ${err}`);
  614. }
  615. }
  616. try {
  617. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  618. }
  619. catch (err) {
  620. if (err.code !== 11000) {
  621. throw Error(`Failed to create PageRedirect documents: ${err}`);
  622. }
  623. }
  624. this.pageEvent.emit('updateMany', pages, user);
  625. }
  626. private async renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix) {
  627. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  628. const pageCollection = mongoose.connection.collection('pages');
  629. const { updateMetadata, createRedirectPage } = options;
  630. const unorderedBulkOp = pageCollection.initializeUnorderedBulkOp();
  631. const insertPageRedirectOperations: any[] = [];
  632. pages.forEach((page) => {
  633. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  634. if (updateMetadata) {
  635. unorderedBulkOp
  636. .find({ _id: page._id })
  637. .update({ $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() } });
  638. }
  639. else {
  640. unorderedBulkOp.find({ _id: page._id }).update({ $set: { path: newPagePath } });
  641. }
  642. // insert PageRedirect
  643. if (!page.isEmpty && createRedirectPage) {
  644. insertPageRedirectOperations.push({
  645. insertOne: {
  646. document: {
  647. fromPath: page.path,
  648. toPath: newPagePath,
  649. },
  650. },
  651. });
  652. }
  653. });
  654. try {
  655. await unorderedBulkOp.execute();
  656. }
  657. catch (err) {
  658. if (err.code !== 11000) {
  659. throw new Error(`Failed to rename pages: ${err}`);
  660. }
  661. }
  662. try {
  663. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  664. }
  665. catch (err) {
  666. if (err.code !== 11000) {
  667. throw Error(`Failed to create PageRedirect documents: ${err}`);
  668. }
  669. }
  670. this.pageEvent.emit('updateMany', pages, user);
  671. }
  672. private async renameDescendantsWithStream(targetPage, newPagePath, user, options = {}, shouldUseV4Process = true, descendantsSubscribedSets?) {
  673. // v4 compatible process
  674. if (shouldUseV4Process) {
  675. return this.renameDescendantsWithStreamV4(targetPage, newPagePath, user, options);
  676. }
  677. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  678. const readStream = await factory.generateReadable();
  679. const newPagePathPrefix = newPagePath;
  680. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  681. const renameDescendants = this.renameDescendants.bind(this);
  682. const pageEvent = this.pageEvent;
  683. let count = 0;
  684. const writeStream = new Writable({
  685. objectMode: true,
  686. async write(batch, encoding, callback) {
  687. try {
  688. count += batch.length;
  689. await renameDescendants(
  690. batch, user, options, pathRegExp, newPagePathPrefix, shouldUseV4Process,
  691. );
  692. const subscribedUsers = await Subscription.getSubscriptions(batch);
  693. subscribedUsers.forEach((eachUser) => {
  694. descendantsSubscribedSets.add(eachUser);
  695. });
  696. logger.debug(`Renaming pages progressing: (count=${count})`);
  697. }
  698. catch (err) {
  699. logger.error('Renaming error on add anyway: ', err);
  700. }
  701. callback();
  702. },
  703. async final(callback) {
  704. logger.debug(`Renaming pages has completed: (totalCount=${count})`);
  705. // update path
  706. targetPage.path = newPagePath;
  707. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  708. callback();
  709. },
  710. });
  711. readStream
  712. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  713. .pipe(writeStream);
  714. await streamToPromise(writeStream);
  715. }
  716. private async renameDescendantsWithStreamV4(targetPage, newPagePath, user, options = {}) {
  717. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  718. const newPagePathPrefix = newPagePath;
  719. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  720. const renameDescendants = this.renameDescendants.bind(this);
  721. const pageEvent = this.pageEvent;
  722. let count = 0;
  723. const writeStream = new Writable({
  724. objectMode: true,
  725. async write(batch, encoding, callback) {
  726. try {
  727. count += batch.length;
  728. await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
  729. logger.debug(`Renaming pages progressing: (count=${count})`);
  730. }
  731. catch (err) {
  732. logger.error('renameDescendants error on add anyway: ', err);
  733. }
  734. callback();
  735. },
  736. final(callback) {
  737. logger.debug(`Renaming pages has completed: (totalCount=${count})`);
  738. // update path
  739. targetPage.path = newPagePath;
  740. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  741. callback();
  742. },
  743. });
  744. readStream
  745. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  746. .pipe(writeStream);
  747. await streamToPromise(writeStream);
  748. }
  749. /*
  750. * Duplicate
  751. */
  752. async duplicate(page, newPagePath, user, isRecursively) {
  753. /*
  754. * Common Operation
  755. */
  756. const isEmptyAndNotRecursively = page?.isEmpty && !isRecursively;
  757. if (page == null || isEmptyAndNotRecursively) {
  758. throw new Error('Cannot find or duplicate the empty page');
  759. }
  760. const Page = mongoose.model('Page') as unknown as PageModel;
  761. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  762. if (!isRecursively && page.isEmpty) {
  763. throw Error('Page not found.');
  764. }
  765. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  766. // 1. Separate v4 & v5 process
  767. const shouldUseV4Process = this.shouldUseV4Process(page);
  768. if (shouldUseV4Process) {
  769. return this.duplicateV4(page, newPagePath, user, isRecursively);
  770. }
  771. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPagePath);
  772. if (!canOperate) {
  773. throw Error(`Cannot operate duplicate to path "${newPagePath}" right now.`);
  774. }
  775. // 2. UserGroup & Owner validation
  776. // use the parent's grant when target page is an empty page
  777. let grant;
  778. let grantedUserIds;
  779. let grantedGroupId;
  780. if (page.isEmpty) {
  781. const parent = await Page.findOne({ _id: page.parent });
  782. if (parent == null) {
  783. throw Error('parent not found');
  784. }
  785. grant = parent.grant;
  786. grantedUserIds = parent.grantedUsers;
  787. grantedGroupId = parent.grantedGroup;
  788. }
  789. else {
  790. grant = page.grant;
  791. grantedUserIds = page.grantedUsers;
  792. grantedGroupId = page.grantedGroup;
  793. }
  794. if (grant !== Page.GRANT_RESTRICTED) {
  795. let isGrantNormalized = false;
  796. try {
  797. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, newPagePath, grant, grantedUserIds, grantedGroupId, false);
  798. }
  799. catch (err) {
  800. logger.error(`Failed to validate grant of page at "${newPagePath}" when duplicating`, err);
  801. throw err;
  802. }
  803. if (!isGrantNormalized) {
  804. throw Error(`This page cannot be duplicated to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  805. }
  806. }
  807. // copy & populate (reason why copy: SubOperation only allows non-populated page document)
  808. const copyPage = { ...page };
  809. // 3. Duplicate target
  810. const options: PageCreateOptions = {
  811. grant: page.grant,
  812. grantUserGroupId: page.grantedGroup,
  813. };
  814. let duplicatedTarget;
  815. if (page.isEmpty) {
  816. const parent = await this.getParentAndFillAncestorsByUser(user, newPagePath);
  817. duplicatedTarget = await Page.createEmptyPage(newPagePath, parent);
  818. }
  819. else {
  820. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  821. duplicatedTarget = await (this.create as CreateMethod)(
  822. newPagePath, page.revision.body, user, options,
  823. );
  824. }
  825. this.pageEvent.emit('duplicate', page, user);
  826. // 4. Take over tags
  827. const originTags = await page.findRelatedTagsById();
  828. let savedTags = [];
  829. if (originTags.length !== 0) {
  830. await PageTagRelation.updatePageTags(duplicatedTarget._id, originTags);
  831. savedTags = await PageTagRelation.listTagNamesByPage(duplicatedTarget._id);
  832. this.tagEvent.emit('update', duplicatedTarget, savedTags);
  833. }
  834. if (isRecursively) {
  835. /*
  836. * Resumable Operation
  837. */
  838. let pageOp;
  839. try {
  840. pageOp = await PageOperation.create({
  841. actionType: PageActionType.Duplicate,
  842. actionStage: PageActionStage.Main,
  843. page: copyPage,
  844. user,
  845. fromPath: page.path,
  846. toPath: newPagePath,
  847. });
  848. }
  849. catch (err) {
  850. logger.error('Failed to create PageOperation document.', err);
  851. throw err;
  852. }
  853. (async() => {
  854. try {
  855. await this.duplicateRecursivelyMainOperation(page, newPagePath, user, pageOp._id);
  856. }
  857. catch (err) {
  858. logger.error('Error occurred while running duplicateRecursivelyMainOperation.', err);
  859. // cleanup
  860. await PageOperation.deleteOne({ _id: pageOp._id });
  861. throw err;
  862. }
  863. })();
  864. }
  865. const result = serializePageSecurely(duplicatedTarget);
  866. result.tags = savedTags;
  867. return result;
  868. }
  869. async duplicateRecursivelyMainOperation(page, newPagePath: string, user, pageOpId: ObjectIdLike): Promise<void> {
  870. const nDuplicatedPages = await this.duplicateDescendantsWithStream(page, newPagePath, user, false);
  871. // normalize parent of descendant pages
  872. const shouldNormalize = this.shouldNormalizeParent(page);
  873. if (shouldNormalize) {
  874. try {
  875. await this.normalizeParentAndDescendantCountOfDescendants(newPagePath, user);
  876. logger.info(`Successfully normalized duplicated descendant pages under "${newPagePath}"`);
  877. }
  878. catch (err) {
  879. logger.error('Failed to normalize descendants afrer duplicate:', err);
  880. throw err;
  881. }
  882. }
  883. // Set to Sub
  884. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  885. if (pageOp == null) {
  886. throw Error('PageOperation document not found');
  887. }
  888. /*
  889. * Sub Operation
  890. */
  891. await this.duplicateRecursivelySubOperation(newPagePath, nDuplicatedPages, pageOp._id);
  892. }
  893. async duplicateRecursivelySubOperation(newPagePath: string, nDuplicatedPages: number, pageOpId: ObjectIdLike): Promise<void> {
  894. const Page = mongoose.model('Page');
  895. const newTarget = await Page.findOne({ path: newPagePath }); // only one page will be found since duplicating to existing path is forbidden
  896. if (newTarget == null) {
  897. throw Error('No duplicated page found. Something might have gone wrong in duplicateRecursivelyMainOperation.');
  898. }
  899. await this.updateDescendantCountOfAncestors(newTarget._id, nDuplicatedPages, false);
  900. await PageOperation.findByIdAndDelete(pageOpId);
  901. }
  902. async duplicateV4(page, newPagePath, user, isRecursively) {
  903. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  904. // populate
  905. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  906. // create option
  907. const options: any = { page };
  908. options.grant = page.grant;
  909. options.grantUserGroupId = page.grantedGroup;
  910. options.grantedUserIds = page.grantedUsers;
  911. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  912. const createdPage = await this.crowi.pageService.create(
  913. newPagePath, page.revision.body, user, options,
  914. );
  915. this.pageEvent.emit('duplicate', page, user);
  916. if (isRecursively) {
  917. this.duplicateDescendantsWithStream(page, newPagePath, user);
  918. }
  919. // take over tags
  920. const originTags = await page.findRelatedTagsById();
  921. let savedTags = [];
  922. if (originTags != null) {
  923. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  924. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  925. this.tagEvent.emit('update', createdPage, savedTags);
  926. }
  927. const result = serializePageSecurely(createdPage);
  928. result.tags = savedTags;
  929. return result;
  930. }
  931. /**
  932. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  933. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  934. */
  935. private async duplicateTags(pageIdMapping) {
  936. const PageTagRelation = mongoose.model('PageTagRelation');
  937. // convert pageId from string to ObjectId
  938. const pageIds = Object.keys(pageIdMapping);
  939. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: new mongoose.Types.ObjectId(pageId) } }) };
  940. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  941. {
  942. $match: stage,
  943. },
  944. {
  945. $group: {
  946. _id: '$relatedTag',
  947. relatedPages: { $push: '$relatedPage' },
  948. },
  949. },
  950. ]);
  951. const newPageTagRelation: any[] = [];
  952. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  953. // relatedPages
  954. relatedPages.forEach((pageId) => {
  955. newPageTagRelation.push({
  956. relatedPage: pageIdMapping[pageId], // newPageId
  957. relatedTag: _id,
  958. });
  959. });
  960. });
  961. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  962. }
  963. private async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = true) {
  964. if (shouldUseV4Process) {
  965. return this.duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix);
  966. }
  967. const Page = this.crowi.model('Page');
  968. const Revision = this.crowi.model('Revision');
  969. const pageIds = pages.map(page => page._id);
  970. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  971. // Mapping to set to the body of the new revision
  972. const pageIdRevisionMapping = {};
  973. revisions.forEach((revision) => {
  974. pageIdRevisionMapping[revision.pageId] = revision;
  975. });
  976. // key: oldPageId, value: newPageId
  977. const pageIdMapping = {};
  978. const newPages: any[] = [];
  979. const newRevisions: any[] = [];
  980. // no need to save parent here
  981. pages.forEach((page) => {
  982. const newPageId = new mongoose.Types.ObjectId();
  983. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  984. const revisionId = new mongoose.Types.ObjectId();
  985. pageIdMapping[page._id] = newPageId;
  986. let newPage;
  987. if (!page.isEmpty) {
  988. newPage = {
  989. _id: newPageId,
  990. path: newPagePath,
  991. creator: user._id,
  992. grant: page.grant,
  993. grantedGroup: page.grantedGroup,
  994. grantedUsers: page.grantedUsers,
  995. lastUpdateUser: user._id,
  996. revision: revisionId,
  997. };
  998. newRevisions.push({
  999. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  1000. });
  1001. }
  1002. newPages.push(newPage);
  1003. });
  1004. await Page.insertMany(newPages, { ordered: false });
  1005. await Revision.insertMany(newRevisions, { ordered: false });
  1006. await this.duplicateTags(pageIdMapping);
  1007. }
  1008. private async duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  1009. const Page = this.crowi.model('Page');
  1010. const Revision = this.crowi.model('Revision');
  1011. const pageIds = pages.map(page => page._id);
  1012. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  1013. // Mapping to set to the body of the new revision
  1014. const pageIdRevisionMapping = {};
  1015. revisions.forEach((revision) => {
  1016. pageIdRevisionMapping[revision.pageId] = revision;
  1017. });
  1018. // key: oldPageId, value: newPageId
  1019. const pageIdMapping = {};
  1020. const newPages: any[] = [];
  1021. const newRevisions: any[] = [];
  1022. pages.forEach((page) => {
  1023. const newPageId = new mongoose.Types.ObjectId();
  1024. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  1025. const revisionId = new mongoose.Types.ObjectId();
  1026. pageIdMapping[page._id] = newPageId;
  1027. newPages.push({
  1028. _id: newPageId,
  1029. path: newPagePath,
  1030. creator: user._id,
  1031. grant: page.grant,
  1032. grantedGroup: page.grantedGroup,
  1033. grantedUsers: page.grantedUsers,
  1034. lastUpdateUser: user._id,
  1035. revision: revisionId,
  1036. });
  1037. newRevisions.push({
  1038. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  1039. });
  1040. });
  1041. await Page.insertMany(newPages, { ordered: false });
  1042. await Revision.insertMany(newRevisions, { ordered: false });
  1043. await this.duplicateTags(pageIdMapping);
  1044. }
  1045. private async duplicateDescendantsWithStream(page, newPagePath, user, shouldUseV4Process = true) {
  1046. if (shouldUseV4Process) {
  1047. return this.duplicateDescendantsWithStreamV4(page, newPagePath, user);
  1048. }
  1049. const iterableFactory = new PageCursorsForDescendantsFactory(user, page, true);
  1050. const readStream = await iterableFactory.generateReadable();
  1051. const newPagePathPrefix = newPagePath;
  1052. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  1053. const duplicateDescendants = this.duplicateDescendants.bind(this);
  1054. const pageEvent = this.pageEvent;
  1055. let count = 0;
  1056. let nNonEmptyDuplicatedPages = 0;
  1057. const writeStream = new Writable({
  1058. objectMode: true,
  1059. async write(batch, encoding, callback) {
  1060. try {
  1061. count += batch.length;
  1062. nNonEmptyDuplicatedPages += batch.filter(page => !page.isEmpty).length;
  1063. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, shouldUseV4Process);
  1064. logger.debug(`Adding pages progressing: (count=${count})`);
  1065. }
  1066. catch (err) {
  1067. logger.error('addAllPages error on add anyway: ', err);
  1068. }
  1069. callback();
  1070. },
  1071. async final(callback) {
  1072. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1073. // update path
  1074. page.path = newPagePath;
  1075. pageEvent.emit('syncDescendantsUpdate', page, user);
  1076. callback();
  1077. },
  1078. });
  1079. readStream
  1080. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1081. .pipe(writeStream);
  1082. await streamToPromise(writeStream);
  1083. return nNonEmptyDuplicatedPages;
  1084. }
  1085. private async duplicateDescendantsWithStreamV4(page, newPagePath, user) {
  1086. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  1087. const newPagePathPrefix = newPagePath;
  1088. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  1089. const duplicateDescendants = this.duplicateDescendants.bind(this);
  1090. const pageEvent = this.pageEvent;
  1091. let count = 0;
  1092. const writeStream = new Writable({
  1093. objectMode: true,
  1094. async write(batch, encoding, callback) {
  1095. try {
  1096. count += batch.length;
  1097. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix);
  1098. logger.debug(`Adding pages progressing: (count=${count})`);
  1099. }
  1100. catch (err) {
  1101. logger.error('addAllPages error on add anyway: ', err);
  1102. }
  1103. callback();
  1104. },
  1105. final(callback) {
  1106. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1107. // update path
  1108. page.path = newPagePath;
  1109. pageEvent.emit('syncDescendantsUpdate', page, user);
  1110. callback();
  1111. },
  1112. });
  1113. readStream
  1114. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1115. .pipe(writeStream);
  1116. await streamToPromise(writeStream);
  1117. return count;
  1118. }
  1119. /*
  1120. * Delete
  1121. */
  1122. async deletePage(page, user, options = {}, isRecursively = false, activityParameters?) {
  1123. /*
  1124. * Common Operation
  1125. */
  1126. const Page = mongoose.model('Page') as PageModel;
  1127. // Separate v4 & v5 process
  1128. const shouldUseV4Process = this.shouldUseV4Process(page);
  1129. if (shouldUseV4Process) {
  1130. return this.deletePageV4(page, user, options, isRecursively);
  1131. }
  1132. // Validate
  1133. if (page.isEmpty && !isRecursively) {
  1134. throw Error('Page not found.');
  1135. }
  1136. const isTrashed = isTrashPage(page.path);
  1137. if (isTrashed) {
  1138. throw new Error('This method does NOT support deleting trashed pages.');
  1139. }
  1140. if (!isMovablePage(page.path)) {
  1141. throw new Error('Page is not deletable.');
  1142. }
  1143. const newPath = Page.getDeletedPageName(page.path);
  1144. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1145. if (!canOperate) {
  1146. throw Error(`Cannot operate delete to path "${newPath}" right now.`);
  1147. }
  1148. // Replace with an empty page
  1149. const isChildrenExist = await Page.exists({ parent: page._id });
  1150. const shouldReplace = !isRecursively && isChildrenExist;
  1151. if (shouldReplace) {
  1152. await Page.replaceTargetWithPage(page, null, true);
  1153. }
  1154. const parameters = {
  1155. ip: activityParameters.ip,
  1156. endpoint: activityParameters.endpoint,
  1157. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_DELETE : SupportedAction.ACTION_PAGE_DELETE,
  1158. user,
  1159. target: page,
  1160. targetModel: 'Page',
  1161. snapshot: {
  1162. username: user.username,
  1163. },
  1164. };
  1165. const activity = await this.crowi.activityService.createActivity(parameters);
  1166. // Delete target (only updating an existing document's properties )
  1167. let deletedPage;
  1168. if (!page.isEmpty) {
  1169. deletedPage = await this.deleteNonEmptyTarget(page, user);
  1170. }
  1171. else { // always recursive
  1172. deletedPage = page;
  1173. await Page.deleteOne({ _id: page._id, isEmpty: true });
  1174. }
  1175. // 1. Update descendantCount
  1176. if (isRecursively) {
  1177. const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
  1178. await this.updateDescendantCountOfAncestors(page.parent, inc, true);
  1179. }
  1180. else {
  1181. // update descendantCount of ancestors'
  1182. await this.updateDescendantCountOfAncestors(page.parent, -1, true);
  1183. }
  1184. // 2. Delete leaf empty pages
  1185. await Page.removeLeafEmptyPagesRecursively(page.parent);
  1186. if (isRecursively) {
  1187. let pageOp;
  1188. try {
  1189. pageOp = await PageOperation.create({
  1190. actionType: PageActionType.Delete,
  1191. actionStage: PageActionStage.Main,
  1192. page,
  1193. user,
  1194. fromPath: page.path,
  1195. toPath: newPath,
  1196. });
  1197. }
  1198. catch (err) {
  1199. logger.error('Failed to create PageOperation document.', err);
  1200. throw err;
  1201. }
  1202. /*
  1203. * Resumable Operation
  1204. */
  1205. (async() => {
  1206. try {
  1207. await this.deleteRecursivelyMainOperation(page, user, pageOp._id, activity);
  1208. }
  1209. catch (err) {
  1210. logger.error('Error occurred while running deleteRecursivelyMainOperation.', err);
  1211. // cleanup
  1212. await PageOperation.deleteOne({ _id: pageOp._id });
  1213. throw err;
  1214. }
  1215. })();
  1216. }
  1217. else {
  1218. this.activityEvent.emit('updated', activity, page);
  1219. }
  1220. return deletedPage;
  1221. }
  1222. private async deleteNonEmptyTarget(page, user) {
  1223. const Page = mongoose.model('Page') as unknown as PageModel;
  1224. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  1225. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1226. const newPath = Page.getDeletedPageName(page.path);
  1227. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  1228. $set: {
  1229. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  1230. },
  1231. }, { new: true });
  1232. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  1233. try {
  1234. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  1235. }
  1236. catch (err) {
  1237. if (err.code !== 11000) {
  1238. throw err;
  1239. }
  1240. }
  1241. this.pageEvent.emit('delete', page, user);
  1242. this.pageEvent.emit('create', deletedPage, user);
  1243. return deletedPage;
  1244. }
  1245. async deleteRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1246. const descendantsSubscribedSets = new Set();
  1247. await this.deleteDescendantsWithStream(page, user, false, descendantsSubscribedSets);
  1248. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets);
  1249. this.activityEvent.emit('updated', activity, page, descendantsSubscribedUsers);
  1250. await PageOperation.findByIdAndDelete(pageOpId);
  1251. // no sub operation available
  1252. }
  1253. private async deletePageV4(page, user, options = {}, isRecursively = false) {
  1254. const Page = mongoose.model('Page') as PageModel;
  1255. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  1256. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  1257. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1258. const newPath = Page.getDeletedPageName(page.path);
  1259. const isTrashed = isTrashPage(page.path);
  1260. if (isTrashed) {
  1261. throw new Error('This method does NOT support deleting trashed pages.');
  1262. }
  1263. if (!isMovablePage(page.path)) {
  1264. throw new Error('Page is not deletable.');
  1265. }
  1266. if (isRecursively) {
  1267. this.deleteDescendantsWithStream(page, user);
  1268. }
  1269. // update Revisions
  1270. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  1271. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  1272. $set: {
  1273. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  1274. },
  1275. }, { new: true });
  1276. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  1277. try {
  1278. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  1279. }
  1280. catch (err) {
  1281. if (err.code !== 11000) {
  1282. throw err;
  1283. }
  1284. }
  1285. this.pageEvent.emit('delete', page, user);
  1286. this.pageEvent.emit('create', deletedPage, user);
  1287. return deletedPage;
  1288. }
  1289. private async deleteDescendants(pages, user) {
  1290. const Page = mongoose.model('Page') as unknown as PageModel;
  1291. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1292. const deletePageOperations: any[] = [];
  1293. const insertPageRedirectOperations: any[] = [];
  1294. pages.forEach((page) => {
  1295. const newPath = Page.getDeletedPageName(page.path);
  1296. let operation;
  1297. // if empty, delete completely
  1298. if (page.isEmpty) {
  1299. operation = {
  1300. deleteOne: {
  1301. filter: { _id: page._id },
  1302. },
  1303. };
  1304. }
  1305. // if not empty, set parent to null and update to trash
  1306. else {
  1307. operation = {
  1308. updateOne: {
  1309. filter: { _id: page._id },
  1310. update: {
  1311. $set: {
  1312. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  1313. },
  1314. },
  1315. },
  1316. };
  1317. insertPageRedirectOperations.push({
  1318. insertOne: {
  1319. document: {
  1320. fromPath: page.path,
  1321. toPath: newPath,
  1322. },
  1323. },
  1324. });
  1325. }
  1326. deletePageOperations.push(operation);
  1327. });
  1328. try {
  1329. await Page.bulkWrite(deletePageOperations);
  1330. }
  1331. catch (err) {
  1332. if (err.code !== 11000) {
  1333. throw new Error(`Failed to delete pages: ${err}`);
  1334. }
  1335. }
  1336. finally {
  1337. this.pageEvent.emit('syncDescendantsDelete', pages, user);
  1338. }
  1339. try {
  1340. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  1341. }
  1342. catch (err) {
  1343. if (err.code !== 11000) {
  1344. throw Error(`Failed to create PageRedirect documents: ${err}`);
  1345. }
  1346. }
  1347. }
  1348. /**
  1349. * Create delete stream and return deleted document count
  1350. */
  1351. private async deleteDescendantsWithStream(targetPage, user, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  1352. let readStream;
  1353. if (shouldUseV4Process) {
  1354. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1355. }
  1356. else {
  1357. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1358. readStream = await factory.generateReadable();
  1359. }
  1360. const deleteDescendants = this.deleteDescendants.bind(this);
  1361. let count = 0;
  1362. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1363. const writeStream = new Writable({
  1364. objectMode: true,
  1365. async write(batch, encoding, callback) {
  1366. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1367. try {
  1368. count += batch.length;
  1369. await deleteDescendants(batch, user);
  1370. const subscribedUsers = await Subscription.getSubscriptions(batch);
  1371. subscribedUsers.forEach((eachUser) => {
  1372. descendantsSubscribedSets.add(eachUser);
  1373. });
  1374. logger.debug(`Deleting pages progressing: (count=${count})`);
  1375. }
  1376. catch (err) {
  1377. logger.error('deleteDescendants error on add anyway: ', err);
  1378. }
  1379. callback();
  1380. },
  1381. final(callback) {
  1382. logger.debug(`Deleting pages has completed: (totalCount=${count})`);
  1383. callback();
  1384. },
  1385. });
  1386. readStream
  1387. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1388. .pipe(writeStream);
  1389. await streamToPromise(writeStream);
  1390. return nDeletedNonEmptyPages;
  1391. }
  1392. private async deleteCompletelyOperation(pageIds, pagePaths) {
  1393. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1394. const Bookmark = this.crowi.model('Bookmark');
  1395. const Comment = this.crowi.model('Comment');
  1396. const Page = this.crowi.model('Page');
  1397. const PageTagRelation = this.crowi.model('PageTagRelation');
  1398. const ShareLink = this.crowi.model('ShareLink');
  1399. const Revision = this.crowi.model('Revision');
  1400. const Attachment = this.crowi.model('Attachment');
  1401. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1402. const { attachmentService } = this.crowi;
  1403. const attachments = await Attachment.find({ page: { $in: pageIds } });
  1404. return Promise.all([
  1405. Bookmark.deleteMany({ page: { $in: pageIds } }),
  1406. Comment.deleteMany({ page: { $in: pageIds } }),
  1407. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  1408. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  1409. Revision.deleteMany({ pageId: { $in: pageIds } }),
  1410. Page.deleteMany({ _id: { $in: pageIds } }),
  1411. PageRedirect.deleteMany({ $or: [{ fromPath: { $in: pagePaths } }, { toPath: { $in: pagePaths } }] }),
  1412. attachmentService.removeAllAttachments(attachments),
  1413. ]);
  1414. }
  1415. // delete multiple pages
  1416. private async deleteMultipleCompletely(pages, user, options = {}) {
  1417. const ids = pages.map(page => (page._id));
  1418. const paths = pages.map(page => (page.path));
  1419. logger.debug('Deleting completely', paths);
  1420. await this.deleteCompletelyOperation(ids, paths);
  1421. this.pageEvent.emit('syncDescendantsDelete', pages, user); // update as renamed page
  1422. return;
  1423. }
  1424. async deleteCompletely(page, user, options = {}, isRecursively = false, preventEmitting = false, activityParameters?) {
  1425. /*
  1426. * Common Operation
  1427. */
  1428. const Page = mongoose.model('Page') as PageModel;
  1429. if (isTopPage(page.path)) {
  1430. throw Error('It is forbidden to delete the top page');
  1431. }
  1432. if (page.isEmpty && !isRecursively) {
  1433. throw Error('Page not found.');
  1434. }
  1435. // v4 compatible process
  1436. const shouldUseV4Process = this.shouldUseV4Process(page);
  1437. if (shouldUseV4Process) {
  1438. return this.deleteCompletelyV4(page, user, options, isRecursively, preventEmitting);
  1439. }
  1440. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, null);
  1441. if (!canOperate) {
  1442. throw Error(`Cannot operate deleteCompletely from path "${page.path}" right now.`);
  1443. }
  1444. const ids = [page._id];
  1445. const paths = [page.path];
  1446. logger.debug('Deleting completely', paths);
  1447. const parameters = {
  1448. ip: activityParameters.ip,
  1449. endpoint: activityParameters.endpoint,
  1450. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_DELETE_COMPLETELY : SupportedAction.ACTION_PAGE_DELETE_COMPLETELY,
  1451. user,
  1452. target: page,
  1453. targetModel: 'Page',
  1454. snapshot: {
  1455. username: user.username,
  1456. },
  1457. };
  1458. const activity = await this.crowi.activityService.createActivity(parameters);
  1459. // 1. update descendantCount
  1460. if (isRecursively) {
  1461. const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
  1462. await this.updateDescendantCountOfAncestors(page.parent, inc, true);
  1463. }
  1464. else {
  1465. // replace with an empty page
  1466. const shouldReplace = await Page.exists({ parent: page._id });
  1467. let pageToUpdateDescendantCount = page;
  1468. if (shouldReplace) {
  1469. pageToUpdateDescendantCount = await Page.replaceTargetWithPage(page);
  1470. }
  1471. await this.updateDescendantCountOfAncestors(pageToUpdateDescendantCount.parent, -1, true);
  1472. }
  1473. // 2. then delete target completely
  1474. await this.deleteCompletelyOperation(ids, paths);
  1475. // delete leaf empty pages
  1476. await Page.removeLeafEmptyPagesRecursively(page.parent);
  1477. if (!page.isEmpty && !preventEmitting) {
  1478. this.pageEvent.emit('deleteCompletely', page, user);
  1479. }
  1480. if (isRecursively) {
  1481. let pageOp;
  1482. try {
  1483. pageOp = await PageOperation.create({
  1484. actionType: PageActionType.DeleteCompletely,
  1485. actionStage: PageActionStage.Main,
  1486. page,
  1487. user,
  1488. fromPath: page.path,
  1489. options,
  1490. });
  1491. }
  1492. catch (err) {
  1493. logger.error('Failed to create PageOperation document.', err);
  1494. throw err;
  1495. }
  1496. /*
  1497. * Main Operation
  1498. */
  1499. (async() => {
  1500. try {
  1501. await this.deleteCompletelyRecursivelyMainOperation(page, user, options, pageOp._id, activity);
  1502. }
  1503. catch (err) {
  1504. logger.error('Error occurred while running deleteCompletelyRecursivelyMainOperation.', err);
  1505. // cleanup
  1506. await PageOperation.deleteOne({ _id: pageOp._id });
  1507. throw err;
  1508. }
  1509. })();
  1510. }
  1511. else {
  1512. this.activityEvent.emit('updated', activity, page);
  1513. }
  1514. return;
  1515. }
  1516. async deleteCompletelyRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1517. const descendantsSubscribedSets = new Set();
  1518. await this.deleteCompletelyDescendantsWithStream(page, user, options, false, descendantsSubscribedSets);
  1519. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets);
  1520. this.activityEvent.emit('updated', activity, page, descendantsSubscribedUsers);
  1521. await PageOperation.findByIdAndDelete(pageOpId);
  1522. // no sub operation available
  1523. }
  1524. private async deleteCompletelyV4(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  1525. const ids = [page._id];
  1526. const paths = [page.path];
  1527. logger.debug('Deleting completely', paths);
  1528. await this.deleteCompletelyOperation(ids, paths);
  1529. if (isRecursively) {
  1530. this.deleteCompletelyDescendantsWithStream(page, user, options);
  1531. }
  1532. if (!page.isEmpty && !preventEmitting) {
  1533. this.pageEvent.emit('deleteCompletely', page, user);
  1534. }
  1535. return;
  1536. }
  1537. async emptyTrashPage(user, options = {}) {
  1538. return this.deleteCompletelyDescendantsWithStream({ path: '/trash' }, user, options);
  1539. }
  1540. /**
  1541. * Create delete completely stream
  1542. */
  1543. private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  1544. let readStream;
  1545. if (shouldUseV4Process) { // pages don't have parents
  1546. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1547. }
  1548. else {
  1549. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1550. readStream = await factory.generateReadable();
  1551. }
  1552. let count = 0;
  1553. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1554. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  1555. const writeStream = new Writable({
  1556. objectMode: true,
  1557. async write(batch, encoding, callback) {
  1558. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1559. try {
  1560. count += batch.length;
  1561. await deleteMultipleCompletely(batch, user, options);
  1562. const subscribedUsers = await Subscription.getSubscriptions(batch);
  1563. subscribedUsers.forEach((eachUser) => {
  1564. descendantsSubscribedSets.add(eachUser);
  1565. });
  1566. logger.debug(`Adding pages progressing: (count=${count})`);
  1567. }
  1568. catch (err) {
  1569. logger.error('addAllPages error on add anyway: ', err);
  1570. }
  1571. callback();
  1572. },
  1573. final(callback) {
  1574. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1575. callback();
  1576. },
  1577. });
  1578. readStream
  1579. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1580. .pipe(writeStream);
  1581. await streamToPromise(writeStream);
  1582. return nDeletedNonEmptyPages;
  1583. }
  1584. // no need to separate Main Sub since it is devided into single page operations
  1585. async deleteMultiplePages(pagesToDelete, user, options): Promise<void> {
  1586. const { isRecursively, isCompletely } = options;
  1587. if (pagesToDelete.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1588. throw Error(`The maximum number of pages is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1589. }
  1590. // omit duplicate paths if isRecursively true, omit empty pages if isRecursively false
  1591. const pages = isRecursively ? omitDuplicateAreaPageFromPages(pagesToDelete) : pagesToDelete.filter(p => !p.isEmpty);
  1592. if (isCompletely) {
  1593. for await (const page of pages) {
  1594. await this.deleteCompletely(page, user, {}, isRecursively);
  1595. }
  1596. }
  1597. else {
  1598. for await (const page of pages) {
  1599. await this.deletePage(page, user, {}, isRecursively);
  1600. }
  1601. }
  1602. }
  1603. // use the same process in both v4 and v5
  1604. private async revertDeletedDescendants(pages, user) {
  1605. const Page = this.crowi.model('Page');
  1606. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1607. const revertPageOperations: any[] = [];
  1608. const fromPathsToDelete: string[] = [];
  1609. pages.forEach((page) => {
  1610. // e.g. page.path = /trash/test, toPath = /test
  1611. const toPath = Page.getRevertDeletedPageName(page.path);
  1612. revertPageOperations.push({
  1613. updateOne: {
  1614. filter: { _id: page._id },
  1615. update: {
  1616. $set: {
  1617. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1618. },
  1619. },
  1620. },
  1621. });
  1622. fromPathsToDelete.push(page.path);
  1623. });
  1624. try {
  1625. await Page.bulkWrite(revertPageOperations);
  1626. await PageRedirect.deleteMany({ fromPath: { $in: fromPathsToDelete } });
  1627. }
  1628. catch (err) {
  1629. if (err.code !== 11000) {
  1630. throw new Error(`Failed to revert pages: ${err}`);
  1631. }
  1632. }
  1633. }
  1634. async revertDeletedPage(page, user, options = {}, isRecursively = false, activityParameters?) {
  1635. /*
  1636. * Common Operation
  1637. */
  1638. const Page = this.crowi.model('Page');
  1639. const PageTagRelation = this.crowi.model('PageTagRelation');
  1640. const parameters = {
  1641. ip: activityParameters.ip,
  1642. endpoint: activityParameters.endpoint,
  1643. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_REVERT : SupportedAction.ACTION_PAGE_REVERT,
  1644. user,
  1645. target: page,
  1646. targetModel: 'Page',
  1647. snapshot: {
  1648. username: user.username,
  1649. },
  1650. };
  1651. const activity = await this.crowi.activityService.createActivity(parameters);
  1652. // 1. Separate v4 & v5 process
  1653. const shouldUseV4Process = this.shouldUseV4ProcessForRevert(page);
  1654. if (shouldUseV4Process) {
  1655. return this.revertDeletedPageV4(page, user, options, isRecursively);
  1656. }
  1657. const newPath = Page.getRevertDeletedPageName(page.path);
  1658. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1659. if (!canOperate) {
  1660. throw Error(`Cannot operate revert from path "${page.path}" right now.`);
  1661. }
  1662. const includeEmpty = true;
  1663. const originPage = await Page.findByPath(newPath, includeEmpty);
  1664. // throw if any page already exists when recursively operation
  1665. if (originPage != null && (!originPage.isEmpty || isRecursively)) {
  1666. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1667. }
  1668. // 2. Revert target
  1669. const parent = await this.getParentAndFillAncestorsByUser(user, newPath);
  1670. const shouldReplace = originPage != null && originPage.isEmpty;
  1671. let updatedPage = await Page.findByIdAndUpdate(page._id, {
  1672. $set: {
  1673. path: newPath,
  1674. status: Page.STATUS_PUBLISHED,
  1675. lastUpdateUser: user._id,
  1676. deleteUser: null,
  1677. deletedAt: null,
  1678. parent: parent._id,
  1679. descendantCount: shouldReplace ? originPage.descendantCount : 0,
  1680. },
  1681. }, { new: true });
  1682. if (shouldReplace) {
  1683. updatedPage = await Page.replaceTargetWithPage(originPage, updatedPage, true);
  1684. }
  1685. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1686. this.pageEvent.emit('revert', page, user);
  1687. if (!isRecursively) {
  1688. await this.updateDescendantCountOfAncestors(parent._id, 1, true);
  1689. this.activityEvent.emit('updated', activity, page);
  1690. }
  1691. else {
  1692. let pageOp;
  1693. try {
  1694. pageOp = await PageOperation.create({
  1695. actionType: PageActionType.Revert,
  1696. actionStage: PageActionStage.Main,
  1697. page,
  1698. user,
  1699. fromPath: page.path,
  1700. toPath: newPath,
  1701. options,
  1702. });
  1703. }
  1704. catch (err) {
  1705. logger.error('Failed to create PageOperation document.', err);
  1706. throw err;
  1707. }
  1708. /*
  1709. * Resumable Operation
  1710. */
  1711. (async() => {
  1712. try {
  1713. await this.revertRecursivelyMainOperation(page, user, options, pageOp._id, activity);
  1714. }
  1715. catch (err) {
  1716. logger.error('Error occurred while running revertRecursivelyMainOperation.', err);
  1717. // cleanup
  1718. await PageOperation.deleteOne({ _id: pageOp._id });
  1719. throw err;
  1720. }
  1721. })();
  1722. }
  1723. return updatedPage;
  1724. }
  1725. async revertRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1726. const Page = mongoose.model('Page') as unknown as PageModel;
  1727. const descendantsSubscribedSets = new Set();
  1728. await this.revertDeletedDescendantsWithStream(page, user, options, false, descendantsSubscribedSets);
  1729. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets);
  1730. this.activityEvent.emit('updated', activity, page, descendantsSubscribedUsers);
  1731. const newPath = Page.getRevertDeletedPageName(page.path);
  1732. // normalize parent of descendant pages
  1733. const shouldNormalize = this.shouldNormalizeParent(page);
  1734. if (shouldNormalize) {
  1735. try {
  1736. await this.normalizeParentAndDescendantCountOfDescendants(newPath, user);
  1737. logger.info(`Successfully normalized reverted descendant pages under "${newPath}"`);
  1738. }
  1739. catch (err) {
  1740. logger.error('Failed to normalize descendants afrer revert:', err);
  1741. throw err;
  1742. }
  1743. }
  1744. // Set to Sub
  1745. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  1746. if (pageOp == null) {
  1747. throw Error('PageOperation document not found');
  1748. }
  1749. /*
  1750. * Sub Operation
  1751. */
  1752. await this.revertRecursivelySubOperation(newPath, pageOp._id);
  1753. }
  1754. async revertRecursivelySubOperation(newPath: string, pageOpId: ObjectIdLike): Promise<void> {
  1755. const Page = mongoose.model('Page') as unknown as PageModel;
  1756. const newTarget = await Page.findOne({ path: newPath }); // only one page will be found since duplicating to existing path is forbidden
  1757. if (newTarget == null) {
  1758. throw Error('No reverted page found. Something might have gone wrong in revertRecursivelyMainOperation.');
  1759. }
  1760. // update descendantCount of ancestors'
  1761. await this.updateDescendantCountOfAncestors(newTarget.parent as ObjectIdLike, newTarget.descendantCount + 1, true);
  1762. await PageOperation.findByIdAndDelete(pageOpId);
  1763. }
  1764. private async revertDeletedPageV4(page, user, options = {}, isRecursively = false) {
  1765. const Page = this.crowi.model('Page');
  1766. const PageTagRelation = this.crowi.model('PageTagRelation');
  1767. const newPath = Page.getRevertDeletedPageName(page.path);
  1768. const originPage = await Page.findByPath(newPath);
  1769. if (originPage != null) {
  1770. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1771. }
  1772. if (isRecursively) {
  1773. this.revertDeletedDescendantsWithStream(page, user, options);
  1774. }
  1775. page.status = Page.STATUS_PUBLISHED;
  1776. page.lastUpdateUser = user;
  1777. debug('Revert deleted the page', page, newPath);
  1778. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1779. $set: {
  1780. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1781. },
  1782. }, { new: true });
  1783. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1784. this.pageEvent.emit('revert', page, user);
  1785. return updatedPage;
  1786. }
  1787. /**
  1788. * Create revert stream
  1789. */
  1790. private async revertDeletedDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  1791. if (shouldUseV4Process) {
  1792. return this.revertDeletedDescendantsWithStreamV4(targetPage, user, options);
  1793. }
  1794. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1795. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1796. let count = 0;
  1797. const writeStream = new Writable({
  1798. objectMode: true,
  1799. async write(batch, encoding, callback) {
  1800. try {
  1801. count += batch.length;
  1802. await revertDeletedDescendants(batch, user);
  1803. const subscribedUsers = await Subscription.getSubscriptions(batch);
  1804. subscribedUsers.forEach((eachUser) => {
  1805. descendantsSubscribedSets.add(eachUser);
  1806. });
  1807. logger.debug(`Reverting pages progressing: (count=${count})`);
  1808. }
  1809. catch (err) {
  1810. logger.error('revertPages error on add anyway: ', err);
  1811. }
  1812. callback();
  1813. },
  1814. async final(callback) {
  1815. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1816. callback();
  1817. },
  1818. });
  1819. readStream
  1820. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1821. .pipe(writeStream);
  1822. await streamToPromise(writeStream);
  1823. return count;
  1824. }
  1825. private async revertDeletedDescendantsWithStreamV4(targetPage, user, options = {}) {
  1826. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1827. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1828. let count = 0;
  1829. const writeStream = new Writable({
  1830. objectMode: true,
  1831. async write(batch, encoding, callback) {
  1832. try {
  1833. count += batch.length;
  1834. await revertDeletedDescendants(batch, user);
  1835. logger.debug(`Reverting pages progressing: (count=${count})`);
  1836. }
  1837. catch (err) {
  1838. logger.error('revertPages error on add anyway: ', err);
  1839. }
  1840. callback();
  1841. },
  1842. final(callback) {
  1843. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1844. callback();
  1845. },
  1846. });
  1847. readStream
  1848. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1849. .pipe(writeStream);
  1850. await streamToPromise(readStream);
  1851. return count;
  1852. }
  1853. async handlePrivatePagesForGroupsToDelete(groupsToDelete, action, transferToUserGroupId, user) {
  1854. const Page = this.crowi.model('Page');
  1855. const pages = await Page.find({ grantedGroup: { $in: groupsToDelete } });
  1856. switch (action) {
  1857. case 'public':
  1858. await Page.publicizePages(pages);
  1859. break;
  1860. case 'delete':
  1861. return this.deleteMultipleCompletely(pages, user);
  1862. case 'transfer':
  1863. await Page.transferPagesToGroup(pages, transferToUserGroupId);
  1864. break;
  1865. default:
  1866. throw new Error('Unknown action for private pages');
  1867. }
  1868. }
  1869. private extractStringIds(refs: Ref<HasObjectId>[]) {
  1870. return refs.map((ref: Ref<HasObjectId>) => {
  1871. return (typeof ref === 'string') ? ref : ref._id.toString();
  1872. });
  1873. }
  1874. constructBasicPageInfo(page: PageDocument, isGuestUser?: boolean): IPageInfo | IPageInfoForEntity {
  1875. const isMovable = isGuestUser ? false : isMovablePage(page.path);
  1876. if (page.isEmpty) {
  1877. return {
  1878. isV5Compatible: true,
  1879. isEmpty: true,
  1880. isMovable,
  1881. isDeletable: false,
  1882. isAbleToDeleteCompletely: false,
  1883. isRevertible: false,
  1884. };
  1885. }
  1886. const likers = page.liker.slice(0, 15) as Ref<IUserHasId>[];
  1887. const seenUsers = page.seenUsers.slice(0, 15) as Ref<IUserHasId>[];
  1888. const expandContentWidth = page.expandContentWidth ?? this.crowi.configManager.getConfig('crowi', 'customize:isContainerFluid');
  1889. return {
  1890. isV5Compatible: isTopPage(page.path) || page.parent != null,
  1891. isEmpty: false,
  1892. sumOfLikers: page.liker.length,
  1893. likerIds: this.extractStringIds(likers),
  1894. seenUserIds: this.extractStringIds(seenUsers),
  1895. sumOfSeenUsers: page.seenUsers.length,
  1896. isMovable,
  1897. isDeletable: isMovable,
  1898. isAbleToDeleteCompletely: false,
  1899. isRevertible: isTrashPage(page.path),
  1900. contentAge: page.getContentAge(),
  1901. expandContentWidth,
  1902. };
  1903. }
  1904. async shortBodiesMapByPageIds(pageIds: ObjectId[] = [], user): Promise<Record<string, string | null>> {
  1905. const Page = mongoose.model('Page') as unknown as PageModel;
  1906. const MAX_LENGTH = 350;
  1907. // aggregation options
  1908. let userGroups;
  1909. if (user != null && userGroups == null) {
  1910. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // Typescriptize model
  1911. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  1912. }
  1913. const viewerCondition = Page.generateGrantCondition(user, userGroups);
  1914. const filterByIds = {
  1915. _id: { $in: pageIds },
  1916. };
  1917. let pages;
  1918. try {
  1919. pages = await Page
  1920. .aggregate([
  1921. // filter by pageIds
  1922. {
  1923. $match: filterByIds,
  1924. },
  1925. // filter by viewer
  1926. {
  1927. $match: viewerCondition,
  1928. },
  1929. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  1930. {
  1931. $lookup: {
  1932. from: 'revisions',
  1933. let: { localRevision: '$revision' },
  1934. pipeline: [
  1935. {
  1936. $match: {
  1937. $expr: {
  1938. $eq: ['$_id', '$$localRevision'],
  1939. },
  1940. },
  1941. },
  1942. {
  1943. $project: {
  1944. // What is $substrCP?
  1945. // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
  1946. revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
  1947. },
  1948. },
  1949. ],
  1950. as: 'revisionData',
  1951. },
  1952. },
  1953. // projection
  1954. {
  1955. $project: {
  1956. _id: 1,
  1957. revisionData: 1,
  1958. },
  1959. },
  1960. ]).exec();
  1961. }
  1962. catch (err) {
  1963. logger.error('Error occurred while generating shortBodiesMap');
  1964. throw err;
  1965. }
  1966. const shortBodiesMap = {};
  1967. pages.forEach((page) => {
  1968. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  1969. });
  1970. return shortBodiesMap;
  1971. }
  1972. async normalizeParentByPath(path: string, user): Promise<void> {
  1973. const Page = mongoose.model('Page') as unknown as PageModel;
  1974. const { PageQueryBuilder } = Page;
  1975. // This validation is not 100% correct since it ignores user to count
  1976. const builder = new PageQueryBuilder(Page.find());
  1977. builder.addConditionAsNotMigrated();
  1978. builder.addConditionToListWithDescendants(path);
  1979. const nEstimatedNormalizationTarget: number = await builder.query.exec('count');
  1980. if (nEstimatedNormalizationTarget === 0) {
  1981. throw Error('No page is available for conversion');
  1982. }
  1983. const pages = await Page.findByPathAndViewer(path, user, null, false);
  1984. if (pages == null || !Array.isArray(pages)) {
  1985. throw Error('Something went wrong while converting pages.');
  1986. }
  1987. if (pages.length === 0) {
  1988. const isForbidden = await Page.count({ path, isEmpty: false }) > 0;
  1989. if (isForbidden) {
  1990. throw new V5ConversionError('It is not allowed to convert this page.', V5ConversionErrCode.FORBIDDEN);
  1991. }
  1992. }
  1993. if (pages.length > 1) {
  1994. throw new V5ConversionError(
  1995. `There are more than two pages at the path "${path}". Please rename or delete the page first.`,
  1996. V5ConversionErrCode.DUPLICATE_PAGES_FOUND,
  1997. );
  1998. }
  1999. let page;
  2000. let systematicallyCreatedPage;
  2001. const shouldCreateNewPage = pages[0] == null;
  2002. if (shouldCreateNewPage) {
  2003. const notEmptyParent = await Page.findNotEmptyParentByPathRecursively(path);
  2004. const options: PageCreateOptions & { grantedUsers?: ObjectIdLike[] | undefined } = {
  2005. grant: notEmptyParent.grant,
  2006. grantUserGroupId: notEmptyParent.grantedGroup,
  2007. grantedUsers: notEmptyParent.grantedUsers,
  2008. };
  2009. systematicallyCreatedPage = await this.forceCreateBySystem(
  2010. path,
  2011. '',
  2012. options,
  2013. );
  2014. page = systematicallyCreatedPage;
  2015. }
  2016. else {
  2017. page = pages[0];
  2018. }
  2019. const grant = page.grant;
  2020. const grantedUserIds = page.grantedUsers;
  2021. const grantedGroupId = page.grantedGroup;
  2022. /*
  2023. * UserGroup & Owner validation
  2024. */
  2025. let isGrantNormalized = false;
  2026. try {
  2027. const shouldCheckDescendants = true;
  2028. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  2029. }
  2030. catch (err) {
  2031. logger.error(`Failed to validate grant of page at "${path}"`, err);
  2032. throw err;
  2033. }
  2034. if (!isGrantNormalized) {
  2035. throw new V5ConversionError(
  2036. 'This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.',
  2037. V5ConversionErrCode.GRANT_INVALID,
  2038. );
  2039. }
  2040. let pageOp;
  2041. try {
  2042. pageOp = await PageOperation.create({
  2043. actionType: PageActionType.NormalizeParent,
  2044. actionStage: PageActionStage.Main,
  2045. page,
  2046. user,
  2047. fromPath: page.path,
  2048. toPath: page.path,
  2049. });
  2050. }
  2051. catch (err) {
  2052. logger.error('Failed to create PageOperation document.', err);
  2053. throw err;
  2054. }
  2055. (async() => {
  2056. try {
  2057. await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  2058. }
  2059. catch (err) {
  2060. logger.error('Error occurred while running normalizeParentRecursivelyMainOperation.', err);
  2061. // cleanup
  2062. await PageOperation.deleteOne({ _id: pageOp._id });
  2063. throw err;
  2064. }
  2065. })();
  2066. }
  2067. async normalizeParentByPageIdsRecursively(pageIds: ObjectIdLike[], user): Promise<void> {
  2068. const Page = mongoose.model('Page') as unknown as PageModel;
  2069. const pages = await Page.findByIdsAndViewer(pageIds, user, null);
  2070. if (pages == null || pages.length === 0) {
  2071. throw Error('pageIds is null or 0 length.');
  2072. }
  2073. if (pages.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  2074. throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  2075. }
  2076. await this.normalizeParentRecursivelyByPages(pages, user);
  2077. return;
  2078. }
  2079. async normalizeParentByPageIds(pageIds: ObjectIdLike[], user): Promise<void> {
  2080. const Page = await mongoose.model('Page') as unknown as PageModel;
  2081. const socket = this.crowi.socketIoService.getDefaultSocket();
  2082. for await (const pageId of pageIds) {
  2083. const page = await Page.findById(pageId);
  2084. if (page == null) {
  2085. continue;
  2086. }
  2087. const errorData: PageMigrationErrorData = { paths: [page.path] };
  2088. try {
  2089. const canOperate = await this.crowi.pageOperationService.canOperate(false, page.path, page.path);
  2090. if (!canOperate) {
  2091. throw Error(`Cannot operate normalizeParent to path "${page.path}" right now.`);
  2092. }
  2093. const normalizedPage = await this.normalizeParentByPage(page, user);
  2094. if (normalizedPage == null) {
  2095. socket.emit(SocketEventName.PageMigrationError, errorData);
  2096. logger.error(`Failed to update descendantCount of page of id: "${pageId}"`);
  2097. }
  2098. }
  2099. catch (err) {
  2100. socket.emit(SocketEventName.PageMigrationError, errorData);
  2101. logger.error('Something went wrong while normalizing parent.', err);
  2102. }
  2103. }
  2104. socket.emit(SocketEventName.PageMigrationSuccess);
  2105. }
  2106. private async normalizeParentByPage(page, user) {
  2107. const Page = mongoose.model('Page') as unknown as PageModel;
  2108. const {
  2109. path, grant, grantedUsers: grantedUserIds, grantedGroup: grantedGroupId,
  2110. } = page;
  2111. // check if any page exists at target path already
  2112. const existingPage = await Page.findOne({ path, parent: { $ne: null } });
  2113. if (existingPage != null && !existingPage.isEmpty) {
  2114. throw Error('Page already exists. Please rename the page to continue.');
  2115. }
  2116. /*
  2117. * UserGroup & Owner validation
  2118. */
  2119. if (grant !== Page.GRANT_RESTRICTED) {
  2120. let isGrantNormalized = false;
  2121. try {
  2122. const shouldCheckDescendants = true;
  2123. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  2124. }
  2125. catch (err) {
  2126. logger.error(`Failed to validate grant of page at "${path}"`, err);
  2127. throw err;
  2128. }
  2129. if (!isGrantNormalized) {
  2130. throw Error('This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.');
  2131. }
  2132. }
  2133. else {
  2134. throw Error('Restricted pages can not be migrated');
  2135. }
  2136. let normalizedPage;
  2137. // replace if empty page exists
  2138. if (existingPage != null && existingPage.isEmpty) {
  2139. // Inherit descendantCount from the empty page
  2140. const updatedPage = await Page.findOneAndUpdate({ _id: page._id }, { descendantCount: existingPage.descendantCount }, { new: true });
  2141. await Page.replaceTargetWithPage(existingPage, updatedPage, true);
  2142. normalizedPage = await Page.findById(page._id);
  2143. }
  2144. else {
  2145. const parent = await this.getParentAndFillAncestorsByUser(user, page.path);
  2146. normalizedPage = await Page.findOneAndUpdate({ _id: page._id }, { parent: parent._id }, { new: true });
  2147. }
  2148. // Update descendantCount
  2149. const inc = 1;
  2150. await this.updateDescendantCountOfAncestors(normalizedPage.parent, inc, true);
  2151. return normalizedPage;
  2152. }
  2153. async normalizeParentRecursivelyByPages(pages, user): Promise<void> {
  2154. /*
  2155. * Main Operation
  2156. */
  2157. const socket = this.crowi.socketIoService.getDefaultSocket();
  2158. const pagesToNormalize = omitDuplicateAreaPageFromPages(pages);
  2159. let normalizablePages;
  2160. let nonNormalizablePages;
  2161. try {
  2162. [normalizablePages, nonNormalizablePages] = await this.crowi.pageGrantService.separateNormalizableAndNotNormalizablePages(user, pagesToNormalize);
  2163. }
  2164. catch (err) {
  2165. socket.emit(SocketEventName.PageMigrationError);
  2166. throw err;
  2167. }
  2168. if (normalizablePages.length === 0) {
  2169. socket.emit(SocketEventName.PageMigrationError);
  2170. return;
  2171. }
  2172. if (nonNormalizablePages.length !== 0) {
  2173. const nonNormalizablePagePaths: string[] = nonNormalizablePages.map(p => p.path);
  2174. socket.emit(SocketEventName.PageMigrationError, { paths: nonNormalizablePagePaths });
  2175. logger.debug('Some pages could not be converted.', nonNormalizablePagePaths);
  2176. }
  2177. /*
  2178. * Main Operation (s)
  2179. */
  2180. const errorPagePaths: string[] = [];
  2181. for await (const page of normalizablePages) {
  2182. const canOperate = await this.crowi.pageOperationService.canOperate(true, page.path, page.path);
  2183. if (!canOperate) {
  2184. errorPagePaths.push(page.path);
  2185. throw Error(`Cannot operate normalizeParentRecursiively to path "${page.path}" right now.`);
  2186. }
  2187. const Page = mongoose.model('Page') as unknown as PageModel;
  2188. const { PageQueryBuilder } = Page;
  2189. const builder = new PageQueryBuilder(Page.findOne());
  2190. builder.addConditionAsOnTree();
  2191. builder.addConditionToListByPathsArray([page.path]);
  2192. const existingPage = await builder.query.exec();
  2193. if (existingPage?.parent != null) {
  2194. errorPagePaths.push(page.path);
  2195. throw Error('This page has already converted.');
  2196. }
  2197. let pageOp;
  2198. try {
  2199. pageOp = await PageOperation.create({
  2200. actionType: PageActionType.NormalizeParent,
  2201. actionStage: PageActionStage.Main,
  2202. page,
  2203. user,
  2204. fromPath: page.path,
  2205. toPath: page.path,
  2206. });
  2207. }
  2208. catch (err) {
  2209. errorPagePaths.push(page.path);
  2210. logger.error('Failed to create PageOperation document.', err);
  2211. throw err;
  2212. }
  2213. try {
  2214. await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  2215. }
  2216. catch (err) {
  2217. errorPagePaths.push(page.path);
  2218. logger.error('Failed to run normalizeParentRecursivelyMainOperation.', err);
  2219. // cleanup
  2220. await PageOperation.deleteOne({ _id: pageOp._id });
  2221. throw err;
  2222. }
  2223. }
  2224. if (errorPagePaths.length === 0) {
  2225. socket.emit(SocketEventName.PageMigrationSuccess);
  2226. }
  2227. else {
  2228. socket.emit(SocketEventName.PageMigrationError, { paths: errorPagePaths });
  2229. }
  2230. }
  2231. async normalizeParentRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike): Promise<number> {
  2232. // Save prevDescendantCount for sub-operation
  2233. const Page = mongoose.model('Page') as unknown as PageModel;
  2234. const { PageQueryBuilder } = Page;
  2235. const builder = new PageQueryBuilder(Page.findOne(), true);
  2236. builder.addConditionAsOnTree();
  2237. builder.addConditionToListByPathsArray([page.path]);
  2238. const exPage = await builder.query.exec();
  2239. const options = { prevDescendantCount: exPage?.descendantCount ?? 0 };
  2240. let count: number;
  2241. try {
  2242. count = await this.normalizeParentRecursively([page.path], user);
  2243. }
  2244. catch (err) {
  2245. logger.error('V5 initial miration failed.', err);
  2246. // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
  2247. throw err;
  2248. }
  2249. // Set to Sub
  2250. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  2251. if (pageOp == null) {
  2252. throw Error('PageOperation document not found');
  2253. }
  2254. await this.normalizeParentRecursivelySubOperation(page, user, pageOp._id, options);
  2255. return count;
  2256. }
  2257. async normalizeParentRecursivelySubOperation(page, user, pageOpId: ObjectIdLike, options: {prevDescendantCount: number}): Promise<void> {
  2258. const Page = mongoose.model('Page') as unknown as PageModel;
  2259. try {
  2260. // update descendantCount of self and descendant pages first
  2261. await this.updateDescendantCountOfSelfAndDescendants(page.path);
  2262. // find pages again to get updated descendantCount
  2263. // then calculate inc
  2264. const pageAfterUpdatingDescendantCount = await Page.findByIdAndViewer(page._id, user);
  2265. if (pageAfterUpdatingDescendantCount == null) {
  2266. throw Error('Page not found after updating descendantCount');
  2267. }
  2268. const { prevDescendantCount } = options;
  2269. const newDescendantCount = pageAfterUpdatingDescendantCount.descendantCount;
  2270. let inc = newDescendantCount - prevDescendantCount;
  2271. const isAlreadyConverted = page.parent != null;
  2272. if (!isAlreadyConverted) {
  2273. inc += 1;
  2274. }
  2275. await this.updateDescendantCountOfAncestors(page._id, inc, false);
  2276. }
  2277. catch (err) {
  2278. logger.error('Failed to update descendantCount after normalizing parent:', err);
  2279. throw Error(`Failed to update descendantCount after normalizing parent: ${err}`);
  2280. }
  2281. await PageOperation.findByIdAndDelete(pageOpId);
  2282. }
  2283. async _isPagePathIndexUnique() {
  2284. const Page = this.crowi.model('Page');
  2285. const now = (new Date()).toString();
  2286. const path = `growi_check_is_path_index_unique_${now}`;
  2287. let isUnique = false;
  2288. try {
  2289. await Page.insertMany([
  2290. { path },
  2291. { path },
  2292. ]);
  2293. }
  2294. catch (err) {
  2295. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  2296. isUnique = true;
  2297. logger.info('Page path index is unique.');
  2298. }
  2299. else {
  2300. throw err;
  2301. }
  2302. }
  2303. finally {
  2304. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  2305. }
  2306. return isUnique;
  2307. }
  2308. async normalizeAllPublicPages() {
  2309. let isUnique;
  2310. try {
  2311. isUnique = await this._isPagePathIndexUnique();
  2312. }
  2313. catch (err) {
  2314. logger.error('Failed to check path index status', err);
  2315. throw err;
  2316. }
  2317. // drop unique index first
  2318. if (isUnique) {
  2319. try {
  2320. await this._v5NormalizeIndex();
  2321. }
  2322. catch (err) {
  2323. logger.error('V5 index normalization failed.', err);
  2324. throw err;
  2325. }
  2326. }
  2327. // then migrate
  2328. try {
  2329. await this.normalizeParentRecursively(['/'], null, true);
  2330. }
  2331. catch (err) {
  2332. logger.error('V5 initial miration failed.', err);
  2333. throw err;
  2334. }
  2335. // update descendantCount of all public pages
  2336. try {
  2337. await this.updateDescendantCountOfSelfAndDescendants('/');
  2338. logger.info('Successfully updated all descendantCount of public pages.');
  2339. }
  2340. catch (err) {
  2341. logger.error('Failed updating descendantCount of public pages.', err);
  2342. throw err;
  2343. }
  2344. await this._setIsV5CompatibleTrue();
  2345. }
  2346. private async _setIsV5CompatibleTrue() {
  2347. try {
  2348. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  2349. 'app:isV5Compatible': true,
  2350. });
  2351. logger.info('Successfully migrated all public pages.');
  2352. }
  2353. catch (err) {
  2354. logger.warn('Failed to update app:isV5Compatible to true.');
  2355. throw err;
  2356. }
  2357. }
  2358. private async normalizeParentAndDescendantCountOfDescendants(path: string, user): Promise<void> {
  2359. await this.normalizeParentRecursively([path], user);
  2360. // update descendantCount of descendant pages
  2361. await this.updateDescendantCountOfSelfAndDescendants(path);
  2362. }
  2363. /**
  2364. * Normalize parent attribute by passing paths and user.
  2365. * @param paths Pages under this paths value will be updated.
  2366. * @param user To be used to filter pages to update. If null, only public pages will be updated.
  2367. * @returns Promise<void>
  2368. */
  2369. async normalizeParentRecursively(paths: string[], user: any | null, shouldEmitProgress = false): Promise<number> {
  2370. const Page = mongoose.model('Page') as unknown as PageModel;
  2371. const ancestorPaths = paths.flatMap(p => collectAncestorPaths(p, []));
  2372. // targets' descendants
  2373. const pathAndRegExpsToNormalize: (RegExp | string)[] = paths
  2374. .map(p => new RegExp(`^${escapeStringRegexp(addTrailingSlash(p))}`, 'i'));
  2375. // include targets' path
  2376. pathAndRegExpsToNormalize.push(...paths);
  2377. // determine UserGroup condition
  2378. let userGroups = null;
  2379. if (user != null) {
  2380. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model
  2381. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  2382. }
  2383. const grantFiltersByUser: { $or: any[] } = Page.generateGrantCondition(user, userGroups);
  2384. return this._normalizeParentRecursively(pathAndRegExpsToNormalize, ancestorPaths, grantFiltersByUser, user, shouldEmitProgress);
  2385. }
  2386. private buildFilterForNormalizeParentRecursively(pathOrRegExps: (RegExp | string)[], publicPathsToNormalize: string[], grantFiltersByUser: { $or: any[] }) {
  2387. const Page = mongoose.model('Page') as unknown as PageModel;
  2388. const andFilter: any = {
  2389. $and: [
  2390. {
  2391. parent: null,
  2392. status: Page.STATUS_PUBLISHED,
  2393. path: { $ne: '/' },
  2394. },
  2395. ],
  2396. };
  2397. const orFilter: any = { $or: [] };
  2398. // specified pathOrRegExps
  2399. if (pathOrRegExps.length > 0) {
  2400. orFilter.$or.push(
  2401. {
  2402. path: { $in: pathOrRegExps },
  2403. },
  2404. );
  2405. }
  2406. // not specified but ancestors of specified pathOrRegExps
  2407. if (publicPathsToNormalize.length > 0) {
  2408. orFilter.$or.push(
  2409. {
  2410. path: { $in: publicPathsToNormalize },
  2411. grant: Page.GRANT_PUBLIC, // use only public pages to complete the tree
  2412. },
  2413. );
  2414. }
  2415. // Merge filters
  2416. const mergedFilter = {
  2417. $and: [
  2418. { $and: [grantFiltersByUser, ...andFilter.$and] },
  2419. { $or: orFilter.$or },
  2420. ],
  2421. };
  2422. return mergedFilter;
  2423. }
  2424. private async _normalizeParentRecursively(
  2425. pathOrRegExps: (RegExp | string)[],
  2426. publicPathsToNormalize: string[],
  2427. grantFiltersByUser: { $or: any[] },
  2428. user,
  2429. shouldEmitProgress = false,
  2430. count = 0,
  2431. skiped = 0,
  2432. isFirst = true,
  2433. ): Promise<number> {
  2434. const BATCH_SIZE = 100;
  2435. const PAGES_LIMIT = 1000;
  2436. const socket = shouldEmitProgress ? this.crowi.socketIoService.getAdminSocket() : null;
  2437. const Page = mongoose.model('Page') as unknown as PageModel;
  2438. const { PageQueryBuilder } = Page;
  2439. // Build filter
  2440. const matchFilter = this.buildFilterForNormalizeParentRecursively(pathOrRegExps, publicPathsToNormalize, grantFiltersByUser);
  2441. let baseAggregation = Page
  2442. .aggregate([
  2443. { $match: matchFilter },
  2444. {
  2445. $project: { // minimize data to fetch
  2446. _id: 1,
  2447. path: 1,
  2448. },
  2449. },
  2450. ]);
  2451. // Limit pages to get
  2452. const total = await Page.countDocuments(matchFilter);
  2453. if (isFirst) {
  2454. socket?.emit(SocketEventName.PMStarted, { total });
  2455. }
  2456. if (total > PAGES_LIMIT) {
  2457. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  2458. }
  2459. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  2460. const batchStream = createBatchStream(BATCH_SIZE);
  2461. let shouldContinue = true;
  2462. let nextCount = count;
  2463. let nextSkiped = skiped;
  2464. // eslint-disable-next-line max-len
  2465. const buildPipelineToCreateEmptyPagesByUser = this.buildPipelineToCreateEmptyPagesByUser.bind(this);
  2466. const migratePagesStream = new Writable({
  2467. objectMode: true,
  2468. async write(pages, encoding, callback) {
  2469. const parentPaths = Array.from(new Set<string>(pages.map(p => pathlib.dirname(p.path))));
  2470. // 1. Remove unnecessary empty pages & reset parent for pages which had had those empty pages
  2471. const pageIdsToNotDelete = pages.map(p => p._id);
  2472. const emptyPagePathsToDelete = pages.map(p => p.path);
  2473. const builder1 = new PageQueryBuilder(Page.find({ isEmpty: true }, { _id: 1 }), true);
  2474. builder1.addConditionToListByPathsArray(emptyPagePathsToDelete);
  2475. builder1.addConditionToExcludeByPageIdsArray(pageIdsToNotDelete);
  2476. const emptyPagesToDelete = await builder1.query.lean().exec();
  2477. const resetParentOperations = emptyPagesToDelete.map((p) => {
  2478. return {
  2479. updateOne: {
  2480. filter: {
  2481. parent: p._id,
  2482. },
  2483. update: {
  2484. parent: null,
  2485. },
  2486. },
  2487. };
  2488. });
  2489. await Page.bulkWrite(resetParentOperations);
  2490. await Page.removeEmptyPages(pageIdsToNotDelete, emptyPagePathsToDelete);
  2491. // 2. Create lacking parents as empty pages
  2492. const orFilters = [
  2493. { path: '/' },
  2494. { path: { $in: publicPathsToNormalize }, grant: Page.GRANT_PUBLIC, status: Page.STATUS_PUBLISHED },
  2495. { path: { $in: publicPathsToNormalize }, parent: { $ne: null }, status: Page.STATUS_PUBLISHED },
  2496. { path: { $nin: publicPathsToNormalize }, status: Page.STATUS_PUBLISHED },
  2497. ];
  2498. const filterForApplicableAncestors = { $or: orFilters };
  2499. const aggregationPipeline = await buildPipelineToCreateEmptyPagesByUser(user, parentPaths, false, filterForApplicableAncestors);
  2500. await Page.createEmptyPagesByPaths(parentPaths, aggregationPipeline);
  2501. // 3. Find parents
  2502. const addGrantCondition = (builder) => {
  2503. builder.query = builder.query.and(grantFiltersByUser);
  2504. return builder;
  2505. };
  2506. const builder2 = new PageQueryBuilder(Page.find(), true);
  2507. addGrantCondition(builder2);
  2508. const parents = await builder2
  2509. .addConditionToListByPathsArray(parentPaths)
  2510. .addConditionToFilterByApplicableAncestors(publicPathsToNormalize)
  2511. .query
  2512. .lean()
  2513. .exec();
  2514. // Normalize all siblings for each page
  2515. const updateManyOperations = parents.map((parent) => {
  2516. const parentId = parent._id;
  2517. // Build filter
  2518. const parentPathEscaped = escapeStringRegexp(parent.path === '/' ? '' : parent.path); // adjust the path for RegExp
  2519. const filter: any = {
  2520. $and: [
  2521. {
  2522. path: { $regex: new RegExp(`^${parentPathEscaped}(\\/[^/]+)\\/?$`, 'i') }, // see: regexr.com/6889f (e.g. /parent/any_child or /any_level1)
  2523. },
  2524. {
  2525. path: { $in: pathOrRegExps.concat(publicPathsToNormalize) },
  2526. },
  2527. filterForApplicableAncestors,
  2528. grantFiltersByUser,
  2529. ],
  2530. };
  2531. return {
  2532. updateMany: {
  2533. filter,
  2534. update: {
  2535. parent: parentId,
  2536. },
  2537. },
  2538. };
  2539. });
  2540. try {
  2541. const res = await Page.bulkWrite(updateManyOperations);
  2542. nextCount += res.result.nModified;
  2543. nextSkiped += res.result.writeErrors.length;
  2544. logger.info(`Page migration processing: (migratedPages=${res.result.nModified})`);
  2545. socket?.emit(SocketEventName.PMMigrating, { count: nextCount });
  2546. socket?.emit(SocketEventName.PMErrorCount, { skip: nextSkiped });
  2547. // Throw if any error is found
  2548. if (res.result.writeErrors.length > 0) {
  2549. logger.error('Failed to migrate some pages', res.result.writeErrors);
  2550. socket?.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2551. throw Error('Failed to migrate some pages');
  2552. }
  2553. // Finish migration if no modification occurred
  2554. if (res.result.nModified === 0 && res.result.nMatched === 0) {
  2555. shouldContinue = false;
  2556. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  2557. socket?.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2558. }
  2559. }
  2560. catch (err) {
  2561. logger.error('Failed to update page.parent.', err);
  2562. throw err;
  2563. }
  2564. callback();
  2565. },
  2566. final(callback) {
  2567. callback();
  2568. },
  2569. });
  2570. pagesStream
  2571. .pipe(batchStream)
  2572. .pipe(migratePagesStream);
  2573. await streamToPromise(migratePagesStream);
  2574. if (await Page.exists(matchFilter) && shouldContinue) {
  2575. return this._normalizeParentRecursively(
  2576. pathOrRegExps,
  2577. publicPathsToNormalize,
  2578. grantFiltersByUser,
  2579. user,
  2580. shouldEmitProgress,
  2581. nextCount,
  2582. nextSkiped,
  2583. false,
  2584. );
  2585. }
  2586. // End
  2587. socket?.emit(SocketEventName.PMEnded, { isSucceeded: true });
  2588. return nextCount;
  2589. }
  2590. private async _v5NormalizeIndex() {
  2591. const collection = mongoose.connection.collection('pages');
  2592. try {
  2593. // drop pages.path_1 indexes
  2594. await collection.dropIndex('path_1');
  2595. logger.info('Succeeded to drop unique indexes from pages.path.');
  2596. }
  2597. catch (err) {
  2598. logger.warn('Failed to drop unique indexes from pages.path.', err);
  2599. throw err;
  2600. }
  2601. try {
  2602. // create indexes without
  2603. await collection.createIndex({ path: 1 }, { unique: false });
  2604. logger.info('Succeeded to create non-unique indexes on pages.path.');
  2605. }
  2606. catch (err) {
  2607. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  2608. throw err;
  2609. }
  2610. }
  2611. async countPagesCanNormalizeParentByUser(user): Promise<number> {
  2612. if (user == null) {
  2613. throw Error('user is required');
  2614. }
  2615. const Page = mongoose.model('Page') as unknown as PageModel;
  2616. const { PageQueryBuilder } = Page;
  2617. const builder = new PageQueryBuilder(Page.count(), false);
  2618. await builder.addConditionAsMigratablePages(user);
  2619. const nMigratablePages = await builder.query.exec();
  2620. return nMigratablePages;
  2621. }
  2622. /**
  2623. * update descendantCount of the following pages
  2624. * - page that has the same path as the provided path
  2625. * - pages that are descendants of the above page
  2626. */
  2627. async updateDescendantCountOfSelfAndDescendants(path: string): Promise<void> {
  2628. const BATCH_SIZE = 200;
  2629. const Page = this.crowi.model('Page');
  2630. const { PageQueryBuilder } = Page;
  2631. const builder = new PageQueryBuilder(Page.find(), true);
  2632. builder.addConditionAsOnTree();
  2633. builder.addConditionToListWithDescendants(path);
  2634. builder.addConditionToSortPagesByDescPath();
  2635. const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
  2636. await this.recountAndUpdateDescendantCountOfPages(aggregatedPages, BATCH_SIZE);
  2637. }
  2638. /**
  2639. * update descendantCount of the pages sequentially from longer path to shorter path
  2640. */
  2641. async updateDescendantCountOfPagesWithPaths(paths: string[]): Promise<void> {
  2642. const BATCH_SIZE = 200;
  2643. const Page = this.crowi.model('Page');
  2644. const { PageQueryBuilder } = Page;
  2645. const builder = new PageQueryBuilder(Page.find(), true);
  2646. builder.addConditionToListByPathsArray(paths); // find by paths
  2647. builder.addConditionToSortPagesByDescPath(); // sort in DESC
  2648. const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
  2649. await this.recountAndUpdateDescendantCountOfPages(aggregatedPages, BATCH_SIZE);
  2650. }
  2651. /**
  2652. * Recount descendantCount of pages one by one
  2653. */
  2654. async recountAndUpdateDescendantCountOfPages(pageCursor: QueryCursor<any>, batchSize:number): Promise<void> {
  2655. const Page = this.crowi.model('Page');
  2656. const recountWriteStream = new Writable({
  2657. objectMode: true,
  2658. async write(pageDocuments, encoding, callback) {
  2659. for await (const document of pageDocuments) {
  2660. const descendantCount = await Page.recountDescendantCount(document._id);
  2661. await Page.findByIdAndUpdate(document._id, { descendantCount });
  2662. }
  2663. callback();
  2664. },
  2665. final(callback) {
  2666. callback();
  2667. },
  2668. });
  2669. pageCursor
  2670. .pipe(createBatchStream(batchSize))
  2671. .pipe(recountWriteStream);
  2672. await streamToPromise(recountWriteStream);
  2673. }
  2674. // update descendantCount of all pages that are ancestors of a provided pageId by count
  2675. async updateDescendantCountOfAncestors(pageId: ObjectIdLike, inc: number, shouldIncludeTarget: boolean): Promise<void> {
  2676. const Page = this.crowi.model('Page');
  2677. const ancestors = await Page.findAncestorsUsingParentRecursively(pageId, shouldIncludeTarget);
  2678. const ancestorPageIds = ancestors.map(p => p._id);
  2679. await Page.incrementDescendantCountOfPageIds(ancestorPageIds, inc);
  2680. const updateDescCountData: UpdateDescCountRawData = Object.fromEntries(ancestors.map(p => [p._id.toString(), p.descendantCount + inc]));
  2681. this.emitUpdateDescCount(updateDescCountData);
  2682. }
  2683. private emitUpdateDescCount(data: UpdateDescCountRawData): void {
  2684. const socket = this.crowi.socketIoService.getDefaultSocket();
  2685. socket.emit(SocketEventName.UpdateDescCount, data);
  2686. }
  2687. /**
  2688. * Build the base aggregation pipeline for fillAncestors--- methods
  2689. * @param onlyMigratedAsExistingPages Determine whether to include non-migrated pages as existing pages. If a page exists,
  2690. * an empty page will not be created at that page's path.
  2691. */
  2692. private buildBasePipelineToCreateEmptyPages(paths: string[], onlyMigratedAsExistingPages = true, andFilter?): any[] {
  2693. const aggregationPipeline: any[] = [];
  2694. const Page = mongoose.model('Page') as unknown as PageModel;
  2695. // -- Filter by paths
  2696. aggregationPipeline.push({ $match: { path: { $in: paths } } });
  2697. // -- Normalized condition
  2698. if (onlyMigratedAsExistingPages) {
  2699. aggregationPipeline.push({
  2700. $match: {
  2701. $or: [
  2702. { grant: Page.GRANT_PUBLIC },
  2703. { parent: { $ne: null } },
  2704. { path: '/' },
  2705. ],
  2706. },
  2707. });
  2708. }
  2709. // -- Add custom pipeline
  2710. if (andFilter != null) {
  2711. aggregationPipeline.push({ $match: andFilter });
  2712. }
  2713. return aggregationPipeline;
  2714. }
  2715. private async buildPipelineToCreateEmptyPagesByUser(user, paths: string[], onlyMigratedAsExistingPages = true, andFilter?): Promise<any[]> {
  2716. const Page = mongoose.model('Page') as unknown as PageModel;
  2717. const pipeline = this.buildBasePipelineToCreateEmptyPages(paths, onlyMigratedAsExistingPages, andFilter);
  2718. let userGroups = null;
  2719. if (user != null) {
  2720. const UserGroupRelation = mongoose.model('UserGroupRelation') as any;
  2721. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  2722. }
  2723. const grantCondition = Page.generateGrantCondition(user, userGroups);
  2724. pipeline.push({ $match: grantCondition });
  2725. return pipeline;
  2726. }
  2727. private buildPipelineToCreateEmptyPagesBySystem(paths: string[]): any[] {
  2728. return this.buildBasePipelineToCreateEmptyPages(paths);
  2729. }
  2730. private async connectPageTree(path: string): Promise<void> {
  2731. const Page = mongoose.model('Page') as unknown as PageModel;
  2732. const { PageQueryBuilder } = Page;
  2733. const ancestorPaths = collectAncestorPaths(path);
  2734. // Find ancestors
  2735. const builder = new PageQueryBuilder(Page.find(), true);
  2736. builder.addConditionToFilterByApplicableAncestors(ancestorPaths); // avoid including not normalized pages
  2737. const ancestors = await builder
  2738. .addConditionToListByPathsArray(ancestorPaths)
  2739. .addConditionToSortPagesByDescPath()
  2740. .query
  2741. .exec();
  2742. // Update parent attrs
  2743. const ancestorsMap = new Map(); // Map<path, page>
  2744. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  2745. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  2746. const operations = nonRootAncestors.map((page) => {
  2747. const parentPath = pathlib.dirname(page.path);
  2748. return {
  2749. updateOne: {
  2750. filter: {
  2751. _id: page._id,
  2752. },
  2753. update: {
  2754. parent: ancestorsMap.get(parentPath)._id,
  2755. },
  2756. },
  2757. };
  2758. });
  2759. await Page.bulkWrite(operations);
  2760. }
  2761. /**
  2762. * Find parent or create parent if not exists.
  2763. * It also updates parent of ancestors
  2764. * @param path string
  2765. * @returns Promise<PageDocument>
  2766. */
  2767. async getParentAndFillAncestorsByUser(user, path: string): Promise<PageDocument> {
  2768. const Page = mongoose.model('Page') as unknown as PageModel;
  2769. // Find parent
  2770. const parent = await Page.findParentByPath(path);
  2771. if (parent != null) {
  2772. return parent;
  2773. }
  2774. const ancestorPaths = collectAncestorPaths(path);
  2775. // Fill ancestors
  2776. const aggregationPipeline: any[] = await this.buildPipelineToCreateEmptyPagesByUser(user, ancestorPaths);
  2777. await Page.createEmptyPagesByPaths(ancestorPaths, aggregationPipeline);
  2778. // Connect ancestors
  2779. await this.connectPageTree(path);
  2780. // Return the created parent
  2781. const createdParent = await Page.findParentByPath(path);
  2782. if (createdParent == null) {
  2783. throw Error('Failed to find the created parent by getParentAndFillAncestorsByUser');
  2784. }
  2785. return createdParent;
  2786. }
  2787. async getParentAndFillAncestorsBySystem(path: string): Promise<PageDocument> {
  2788. const Page = mongoose.model('Page') as unknown as PageModel;
  2789. // Find parent
  2790. const parent = await Page.findParentByPath(path);
  2791. if (parent != null) {
  2792. return parent;
  2793. }
  2794. // Fill ancestors
  2795. const ancestorPaths = collectAncestorPaths(path);
  2796. const aggregationPipeline: any[] = this.buildPipelineToCreateEmptyPagesBySystem(ancestorPaths);
  2797. await Page.createEmptyPagesByPaths(ancestorPaths, aggregationPipeline);
  2798. // Connect ancestors
  2799. await this.connectPageTree(path);
  2800. // Return the created parent
  2801. const createdParent = await Page.findParentByPath(path);
  2802. if (createdParent == null) {
  2803. throw Error('Failed to find the created parent by getParentAndFillAncestorsByUser');
  2804. }
  2805. return createdParent;
  2806. }
  2807. // --------- Create ---------
  2808. private async preparePageDocumentToCreate(path: string, shouldNew: boolean): Promise<PageDocument> {
  2809. const Page = mongoose.model('Page') as unknown as PageModel;
  2810. const emptyPage = await Page.findOne({ path, isEmpty: true });
  2811. // Use empty page if exists, if not, create a new page
  2812. let page;
  2813. if (shouldNew) {
  2814. page = new Page();
  2815. }
  2816. else if (emptyPage != null) {
  2817. page = emptyPage;
  2818. const descendantCount = await Page.recountDescendantCount(page._id);
  2819. page.descendantCount = descendantCount;
  2820. page.isEmpty = false;
  2821. }
  2822. else {
  2823. page = new Page();
  2824. }
  2825. return page;
  2826. }
  2827. private setFieldExceptForGrantRevisionParent(
  2828. pageDocument: PageDocument,
  2829. path: string,
  2830. user?,
  2831. ): void {
  2832. const Page = mongoose.model('Page') as unknown as PageModel;
  2833. pageDocument.path = path;
  2834. pageDocument.creator = user;
  2835. pageDocument.lastUpdateUser = user;
  2836. pageDocument.status = Page.STATUS_PUBLISHED;
  2837. }
  2838. private async canProcessCreate(
  2839. path: string,
  2840. grantData: {
  2841. grant: number,
  2842. grantedUserIds?: ObjectIdLike[],
  2843. grantUserGroupId?: ObjectIdLike,
  2844. },
  2845. shouldValidateGrant: boolean,
  2846. user?,
  2847. ): Promise<boolean> {
  2848. const Page = mongoose.model('Page') as unknown as PageModel;
  2849. // Operatability validation
  2850. const canOperate = await this.crowi.pageOperationService.canOperate(false, null, path);
  2851. if (!canOperate) {
  2852. logger.error(`Cannot operate create to path "${path}" right now.`);
  2853. return false;
  2854. }
  2855. // Existance validation
  2856. const isExist = (await Page.count({ path, isEmpty: false })) > 0; // not validate empty page
  2857. if (isExist) {
  2858. logger.error('Cannot create new page to existed path');
  2859. return false;
  2860. }
  2861. // UserGroup & Owner validation
  2862. const { grant, grantedUserIds, grantUserGroupId } = grantData;
  2863. if (shouldValidateGrant) {
  2864. if (user == null) {
  2865. throw Error('user is required to validate grant');
  2866. }
  2867. let isGrantNormalized = false;
  2868. try {
  2869. // It must check descendants as well if emptyTarget is not null
  2870. const isEmptyPageAlreadyExist = await Page.count({ path, isEmpty: true }) > 0;
  2871. const shouldCheckDescendants = isEmptyPageAlreadyExist;
  2872. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantUserGroupId, shouldCheckDescendants);
  2873. }
  2874. catch (err) {
  2875. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  2876. throw err;
  2877. }
  2878. if (!isGrantNormalized) {
  2879. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  2880. }
  2881. }
  2882. return true;
  2883. }
  2884. async create(path: string, body: string, user, options: PageCreateOptions = {}): Promise<PageDocument> {
  2885. const Page = mongoose.model('Page') as unknown as PageModel;
  2886. // Switch method
  2887. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  2888. if (!isV5Compatible) {
  2889. return Page.createV4(path, body, user, options);
  2890. }
  2891. // Values
  2892. // eslint-disable-next-line no-param-reassign
  2893. path = this.crowi.xss.process(path); // sanitize path
  2894. const {
  2895. format = 'markdown', grantUserGroupId,
  2896. } = options;
  2897. const grant = isTopPage(path) ? Page.GRANT_PUBLIC : options.grant;
  2898. const grantData = {
  2899. grant,
  2900. grantedUserIds: grant === Page.GRANT_OWNER ? [user._id] : undefined,
  2901. grantUserGroupId,
  2902. };
  2903. const isGrantRestricted = grant === Page.GRANT_RESTRICTED;
  2904. // Validate
  2905. const shouldValidateGrant = !isGrantRestricted;
  2906. const canProcessCreate = await this.canProcessCreate(path, grantData, shouldValidateGrant, user);
  2907. if (!canProcessCreate) {
  2908. throw Error('Cannnot process create');
  2909. }
  2910. // Prepare a page document
  2911. const shouldNew = isGrantRestricted;
  2912. const page = await this.preparePageDocumentToCreate(path, shouldNew);
  2913. // Set field
  2914. this.setFieldExceptForGrantRevisionParent(page, path, user);
  2915. // Apply scope
  2916. page.applyScope(user, grant, grantUserGroupId);
  2917. // Set parent
  2918. if (isTopPage(path) || isGrantRestricted) { // set parent to null when GRANT_RESTRICTED
  2919. page.parent = null;
  2920. }
  2921. else {
  2922. const parent = await this.getParentAndFillAncestorsByUser(user, path);
  2923. page.parent = parent._id;
  2924. }
  2925. // Save
  2926. let savedPage = await page.save();
  2927. // Create revision
  2928. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  2929. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  2930. savedPage = await pushRevision(savedPage, newRevision, user);
  2931. await savedPage.populateDataToShowRevision();
  2932. // Update descendantCount
  2933. await this.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  2934. // Emit create event
  2935. this.pageEvent.emit('create', savedPage, user);
  2936. // Delete PageRedirect if exists
  2937. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  2938. try {
  2939. await PageRedirect.deleteOne({ fromPath: path });
  2940. logger.warn(`Deleted page redirect after creating a new page at path "${path}".`);
  2941. }
  2942. catch (err) {
  2943. // no throw
  2944. logger.error('Failed to delete PageRedirect');
  2945. }
  2946. return savedPage;
  2947. }
  2948. private async canProcessForceCreateBySystem(
  2949. path: string,
  2950. grantData: {
  2951. grant: number,
  2952. grantedUserIds?: ObjectIdLike[],
  2953. grantUserGroupId?: ObjectIdLike,
  2954. },
  2955. ): Promise<boolean> {
  2956. return this.canProcessCreate(path, grantData, false);
  2957. }
  2958. /**
  2959. * @private
  2960. * This method receives the same arguments as the PageService.create method does except for the added type '{ grantedUsers?: ObjectIdLike[] }'.
  2961. * This additional value is used to determine the grantedUser of the page to be created by system.
  2962. * This method must not run isGrantNormalized method to validate grant. **If necessary, run it before use this method.**
  2963. * -- Reason 1: This is because it is not expected to use this method when the grant validation is required.
  2964. * -- Reason 2: This is because it is not expected to use this method when the program cannot determine the operator.
  2965. */
  2966. private async forceCreateBySystem(path: string, body: string, options: PageCreateOptions & { grantedUsers?: ObjectIdLike[] }): Promise<PageDocument> {
  2967. const Page = mongoose.model('Page') as unknown as PageModel;
  2968. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  2969. if (!isV5Compatible) {
  2970. throw Error('This method is available only when v5 compatible');
  2971. }
  2972. // Values
  2973. // eslint-disable-next-line no-param-reassign
  2974. path = this.crowi.xss.process(path); // sanitize path
  2975. const {
  2976. format = 'markdown', grantUserGroupId, grantedUsers,
  2977. } = options;
  2978. const grant = isTopPage(path) ? Page.GRANT_PUBLIC : options.grant;
  2979. const isGrantRestricted = grant === Page.GRANT_RESTRICTED;
  2980. const isGrantOwner = grant === Page.GRANT_OWNER;
  2981. const grantData = {
  2982. grant,
  2983. grantedUserIds: isGrantOwner ? grantedUsers : undefined,
  2984. grantUserGroupId,
  2985. };
  2986. // Validate
  2987. if (isGrantOwner && grantedUsers?.length !== 1) {
  2988. throw Error('grantedUser must exist when grant is GRANT_OWNER');
  2989. }
  2990. const canProcessForceCreateBySystem = await this.canProcessForceCreateBySystem(path, grantData);
  2991. if (!canProcessForceCreateBySystem) {
  2992. throw Error('Cannnot process forceCreateBySystem');
  2993. }
  2994. // Prepare a page document
  2995. const shouldNew = isGrantRestricted;
  2996. const page = await this.preparePageDocumentToCreate(path, shouldNew);
  2997. // Set field
  2998. this.setFieldExceptForGrantRevisionParent(page, path);
  2999. // Apply scope
  3000. page.applyScope({ _id: grantedUsers?.[0] }, grant, grantUserGroupId);
  3001. // Set parent
  3002. if (isTopPage(path) || isGrantRestricted) { // set parent to null when GRANT_RESTRICTED
  3003. page.parent = null;
  3004. }
  3005. else {
  3006. const parent = await this.getParentAndFillAncestorsBySystem(path);
  3007. page.parent = parent._id;
  3008. }
  3009. // Save
  3010. let savedPage = await page.save();
  3011. // Create revision
  3012. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  3013. const dummyUser = { _id: new mongoose.Types.ObjectId() };
  3014. const newRevision = Revision.prepareRevision(savedPage, body, null, dummyUser, { format });
  3015. savedPage = await pushRevision(savedPage, newRevision, dummyUser);
  3016. // Update descendantCount
  3017. await this.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  3018. // Emit create event
  3019. this.pageEvent.emit('create', savedPage, dummyUser);
  3020. return savedPage;
  3021. }
  3022. /*
  3023. * Find all children by parent's path or id. Using id should be prioritized
  3024. */
  3025. async findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  3026. const Page = mongoose.model('Page') as unknown as PageModel;
  3027. let queryBuilder: PageQueryBuilder;
  3028. if (hasSlash(parentPathOrId)) {
  3029. const path = parentPathOrId;
  3030. const regexp = generateChildrenRegExp(path);
  3031. queryBuilder = new PageQueryBuilder(Page.find({ path: { $regex: regexp } }), true);
  3032. }
  3033. else {
  3034. const parentId = parentPathOrId;
  3035. // Use $eq for user-controlled sources. see: https://codeql.github.com/codeql-query-help/javascript/js-sql-injection/#recommendation
  3036. queryBuilder = new PageQueryBuilder(Page.find({ parent: { $eq: parentId } } as any), true); // TODO: improve type
  3037. }
  3038. await queryBuilder.addViewerCondition(user, userGroups);
  3039. const pages = await queryBuilder
  3040. .addConditionToSortPagesByAscPath()
  3041. .query
  3042. .lean()
  3043. .exec();
  3044. await this.injectProcessDataIntoPagesByActionTypes(pages, [PageActionType.Rename]);
  3045. return pages;
  3046. }
  3047. async findAncestorsChildrenByPathAndViewer(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  3048. const Page = mongoose.model('Page') as unknown as PageModel;
  3049. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  3050. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  3051. // get pages at once
  3052. const queryBuilder = new PageQueryBuilder(Page.find({ path: { $in: regexps } }), true);
  3053. await queryBuilder.addViewerCondition(user, userGroups);
  3054. const pages = await queryBuilder
  3055. .addConditionAsOnTree()
  3056. .addConditionToMinimizeDataForRendering()
  3057. .addConditionToSortPagesByAscPath()
  3058. .query
  3059. .lean()
  3060. .exec();
  3061. this.injectIsTargetIntoPages(pages, path);
  3062. await this.injectProcessDataIntoPagesByActionTypes(pages, [PageActionType.Rename]);
  3063. /*
  3064. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  3065. */
  3066. const pathToChildren: Record<string, PageDocument[]> = {};
  3067. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  3068. sortedPaths.every((path) => {
  3069. const children = pages.filter(page => pathlib.dirname(page.path) === path);
  3070. if (children.length === 0) {
  3071. return false; // break when children do not exist
  3072. }
  3073. pathToChildren[path] = children;
  3074. return true;
  3075. });
  3076. return pathToChildren;
  3077. }
  3078. private injectIsTargetIntoPages(pages: (PageDocument & {isTarget?: boolean})[], path): void {
  3079. pages.forEach((page) => {
  3080. if (page.path === path) {
  3081. page.isTarget = true;
  3082. }
  3083. });
  3084. }
  3085. /**
  3086. * Inject processData into page docuements
  3087. * The processData is a combination of actionType as a key and information on whether the action is processable as a value.
  3088. */
  3089. private async injectProcessDataIntoPagesByActionTypes(
  3090. pages: (PageDocument & { processData?: IPageOperationProcessData })[],
  3091. actionTypes: PageActionType[],
  3092. ): Promise<void> {
  3093. const pageOperations = await PageOperation.find({ actionType: { $in: actionTypes } });
  3094. if (pageOperations == null || pageOperations.length === 0) {
  3095. return;
  3096. }
  3097. const processInfo: IPageOperationProcessInfo = this.crowi.pageOperationService.generateProcessInfo(pageOperations);
  3098. const operatingPageIds: string[] = Object.keys(processInfo);
  3099. // inject processData into pages
  3100. pages.forEach((page) => {
  3101. const pageId = page._id.toString();
  3102. if (operatingPageIds.includes(pageId)) {
  3103. const processData: IPageOperationProcessData = processInfo[pageId];
  3104. page.processData = processData;
  3105. }
  3106. });
  3107. }
  3108. }
  3109. export default PageService;