index.ts 156 KB

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