page.ts 140 KB

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