page.ts 122 KB

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