page.ts 115 KB

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