page.ts 115 KB

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