page.ts 144 KB

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