index.ts 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499
  1. import type EventEmitter from 'events';
  2. import pathlib from 'path';
  3. import { Readable, Writable } from 'stream';
  4. import { pipeline } from 'stream/promises';
  5. import {
  6. PageStatus, YDocStatus, getIdForRef,
  7. getIdStringForRef,
  8. } from '@growi/core';
  9. import { PageGrant } from '@growi/core/dist/interfaces';
  10. import type {
  11. Ref, HasObjectId, IUserHasId, IUser,
  12. IPage, IPageInfo, IPageInfoAll, IPageInfoForEntity, IGrantedGroup, IRevisionHasId,
  13. IDataWithMeta,
  14. } from '@growi/core/dist/interfaces';
  15. import {
  16. pagePathUtils, pathUtils,
  17. } from '@growi/core/dist/utils';
  18. import escapeStringRegexp from 'escape-string-regexp';
  19. import type { Cursor, HydratedDocument } from 'mongoose';
  20. import mongoose from 'mongoose';
  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 { isAiEnabled } from '~/features/openai/server/services';
  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. await pipeline(readStream, batchStream, writeStream);
  863. }
  864. private async renameDescendantsWithStreamV4(targetPage, newPagePath, user, options = {}) {
  865. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  866. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  867. const newPagePathPrefix = newPagePath;
  868. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  869. const renameDescendants = this.renameDescendants.bind(this);
  870. const pageEvent = this.pageEvent;
  871. let count = 0;
  872. const writeStream = new Writable({
  873. objectMode: true,
  874. async write(batch, encoding, callback) {
  875. try {
  876. count += batch.length;
  877. await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
  878. logger.debug(`Renaming pages progressing: (count=${count})`);
  879. }
  880. catch (err) {
  881. logger.error('renameDescendants error on add anyway: ', err);
  882. }
  883. callback();
  884. },
  885. final(callback) {
  886. logger.debug(`Renaming pages has completed: (totalCount=${count})`);
  887. // update path
  888. targetPage.path = newPagePath;
  889. pageEvent.emit('syncDescendantsUpdate', targetPage, user);
  890. callback();
  891. },
  892. });
  893. await pipeline(readStream, batchStream, writeStream);
  894. }
  895. /*
  896. * Duplicate
  897. */
  898. async duplicate(page: PageDocument, newPagePath: string, user, isRecursively: boolean, onlyDuplicateUserRelatedResources: boolean) {
  899. /*
  900. * Common Operation
  901. */
  902. const isEmptyAndNotRecursively = page?.isEmpty && !isRecursively;
  903. if (page == null || isEmptyAndNotRecursively) {
  904. throw new Error('Cannot find or duplicate the empty page');
  905. }
  906. const Page = mongoose.model('Page') as unknown as PageModel;
  907. if (!isRecursively && page.isEmpty) {
  908. throw Error('Page not found.');
  909. }
  910. newPagePath = generalXssFilter.process(newPagePath); // eslint-disable-line no-param-reassign
  911. // 1. Separate v4 & v5 process
  912. const isShouldUseV4Process = shouldUseV4Process(page);
  913. if (isShouldUseV4Process) {
  914. return this.duplicateV4(page, newPagePath, user, isRecursively, onlyDuplicateUserRelatedResources);
  915. }
  916. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPagePath);
  917. if (!canOperate) {
  918. throw Error(`Cannot operate duplicate to path "${newPagePath}" right now.`);
  919. }
  920. // 2. UserGroup & Owner validation
  921. // use the parent's grant when target page is an empty page
  922. let grant: PageGrant;
  923. let grantedUserIds;
  924. let grantedGroupIds: IGrantedGroup[];
  925. if (page.isEmpty) {
  926. const parent = await Page.findOne({ _id: page.parent });
  927. if (parent == null) {
  928. throw Error('parent not found');
  929. }
  930. grant = parent.grant;
  931. grantedUserIds = parent.grantedUsers;
  932. grantedGroupIds = onlyDuplicateUserRelatedResources ? (await this.pageGrantService.getUserRelatedGrantedGroups(parent, user)) : parent.grantedGroups;
  933. }
  934. else {
  935. grant = page.grant;
  936. grantedUserIds = page.grantedUsers;
  937. grantedGroupIds = onlyDuplicateUserRelatedResources ? (await this.pageGrantService.getUserRelatedGrantedGroups(page, user)) : page.grantedGroups;
  938. }
  939. if (grant !== Page.GRANT_RESTRICTED) {
  940. let isGrantNormalized = false;
  941. try {
  942. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, newPagePath, grant, grantedUserIds, grantedGroupIds, false);
  943. }
  944. catch (err) {
  945. logger.error(`Failed to validate grant of page at "${newPagePath}" when duplicating`, err);
  946. throw err;
  947. }
  948. if (!isGrantNormalized) {
  949. throw Error(`This page cannot be duplicated to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
  950. }
  951. }
  952. // copy & populate (reason why copy: SubOperation only allows non-populated page document)
  953. const copyPage = { ...page };
  954. // 3. Duplicate target
  955. const options: IOptionsForCreate = {
  956. grant,
  957. grantUserGroupIds: grantedGroupIds,
  958. };
  959. let duplicatedTarget: HydratedDocument<PageDocument>;
  960. if (page.isEmpty) {
  961. const parent = await this.getParentAndFillAncestorsByUser(user, newPagePath);
  962. duplicatedTarget = await Page.createEmptyPage(newPagePath, parent);
  963. }
  964. else {
  965. const populatedPage = await page.populate<{revision: IRevisionHasId | null}>({ path: 'revision', model: 'Revision', select: 'body' });
  966. duplicatedTarget = await (this.create as CreateMethod)(
  967. newPagePath, populatedPage?.revision?.body ?? '', user, options,
  968. );
  969. if (isAiEnabled()) {
  970. // TODO: https://redmine.weseek.co.jp/issues/160336
  971. const { getOpenaiService } = await import('~/features/openai/server/services/openai');
  972. // Do not await because communication with OpenAI takes time
  973. const openaiService = getOpenaiService();
  974. // openaiService?.createVectorStoreFile([duplicatedTarget]);
  975. }
  976. }
  977. this.pageEvent.emit('duplicate', page, user);
  978. // 4. Take over tags
  979. const originTags = await page.findRelatedTagsById();
  980. let savedTags: PageTagRelationDocument[] = [];
  981. if (originTags.length !== 0) {
  982. await PageTagRelation.updatePageTags(duplicatedTarget._id, originTags);
  983. savedTags = await PageTagRelation.listTagNamesByPage(duplicatedTarget._id);
  984. this.tagEvent.emit('update', duplicatedTarget, savedTags);
  985. }
  986. if (isRecursively) {
  987. /*
  988. * Resumable Operation
  989. */
  990. let pageOp;
  991. try {
  992. pageOp = await PageOperation.create({
  993. actionType: PageActionType.Duplicate,
  994. actionStage: PageActionStage.Main,
  995. page: copyPage,
  996. user,
  997. fromPath: page.path,
  998. toPath: newPagePath,
  999. });
  1000. }
  1001. catch (err) {
  1002. logger.error('Failed to create PageOperation document.', err);
  1003. throw err;
  1004. }
  1005. (async() => {
  1006. try {
  1007. await this.duplicateRecursivelyMainOperation(page, newPagePath, user, pageOp._id, onlyDuplicateUserRelatedResources);
  1008. }
  1009. catch (err) {
  1010. logger.error('Error occurred while running duplicateRecursivelyMainOperation.', err);
  1011. // cleanup
  1012. await PageOperation.deleteOne({ _id: pageOp._id });
  1013. throw err;
  1014. }
  1015. })();
  1016. }
  1017. const result = serializePageSecurely(duplicatedTarget);
  1018. result.tags = savedTags;
  1019. return result;
  1020. }
  1021. async duplicateRecursivelyMainOperation(
  1022. page: PageDocument,
  1023. newPagePath: string,
  1024. user,
  1025. pageOpId: ObjectIdLike,
  1026. onlyDuplicateUserRelatedResources: boolean,
  1027. ): Promise<void> {
  1028. const nDuplicatedPages = await this.duplicateDescendantsWithStream(page, newPagePath, user, onlyDuplicateUserRelatedResources, false);
  1029. // normalize parent of descendant pages
  1030. const shouldNormalize = this.shouldNormalizeParent(page);
  1031. if (shouldNormalize) {
  1032. try {
  1033. await this.normalizeParentAndDescendantCountOfDescendants(newPagePath, user, true);
  1034. logger.info(`Successfully normalized duplicated descendant pages under "${newPagePath}"`);
  1035. }
  1036. catch (err) {
  1037. logger.error('Failed to normalize descendants afrer duplicate:', err);
  1038. throw err;
  1039. }
  1040. }
  1041. // Set to Sub
  1042. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  1043. if (pageOp == null) {
  1044. throw Error('PageOperation document not found');
  1045. }
  1046. /*
  1047. * Sub Operation
  1048. */
  1049. await this.duplicateRecursivelySubOperation(newPagePath, nDuplicatedPages, pageOp._id);
  1050. }
  1051. async duplicateRecursivelySubOperation(newPagePath: string, nDuplicatedPages: number, pageOpId: ObjectIdLike): Promise<void> {
  1052. const Page = mongoose.model('Page');
  1053. const newTarget = await Page.findOne({ path: newPagePath }); // only one page will be found since duplicating to existing path is forbidden
  1054. if (newTarget == null) {
  1055. throw Error('No duplicated page found. Something might have gone wrong in duplicateRecursivelyMainOperation.');
  1056. }
  1057. await this.updateDescendantCountOfAncestors(newTarget._id, nDuplicatedPages, false);
  1058. await PageOperation.findByIdAndDelete(pageOpId);
  1059. }
  1060. async duplicateV4(page, newPagePath, user, isRecursively, onlyDuplicateUserRelatedResources: boolean) {
  1061. // populate
  1062. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  1063. // create option
  1064. const options: any = { page };
  1065. options.grant = page.grant;
  1066. options.grantUserGroupIds = page.grantedGroups;
  1067. options.grantedUserIds = page.grantedUsers;
  1068. newPagePath = generalXssFilter.process(newPagePath); // eslint-disable-line no-param-reassign
  1069. const createdPage = await this.create(
  1070. newPagePath, page.revision.body, user, options,
  1071. );
  1072. this.pageEvent.emit('duplicate', page, user);
  1073. if (isRecursively) {
  1074. this.duplicateDescendantsWithStream(page, newPagePath, user, onlyDuplicateUserRelatedResources);
  1075. }
  1076. // take over tags
  1077. const originTags = await page.findRelatedTagsById();
  1078. let savedTags: PageTagRelationDocument[] = [];
  1079. if (originTags != null) {
  1080. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  1081. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  1082. this.tagEvent.emit('update', createdPage, savedTags);
  1083. }
  1084. const result = serializePageSecurely(createdPage);
  1085. result.tags = savedTags;
  1086. return result;
  1087. }
  1088. /**
  1089. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  1090. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  1091. */
  1092. private async duplicateTags(pageIdMapping) {
  1093. // convert pageId from string to ObjectId
  1094. const pageIds = Object.keys(pageIdMapping);
  1095. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: new mongoose.Types.ObjectId(pageId) } }) };
  1096. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  1097. {
  1098. $match: stage,
  1099. },
  1100. {
  1101. $group: {
  1102. _id: '$relatedTag',
  1103. relatedPages: { $push: '$relatedPage' },
  1104. },
  1105. },
  1106. ]);
  1107. const newPageTagRelation: any[] = [];
  1108. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  1109. // relatedPages
  1110. relatedPages.forEach((pageId) => {
  1111. newPageTagRelation.push({
  1112. relatedPage: pageIdMapping[pageId], // newPageId
  1113. relatedTag: _id,
  1114. });
  1115. });
  1116. });
  1117. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  1118. }
  1119. private async duplicateDescendants(
  1120. pages, user, oldPagePathPrefix, newPagePathPrefix,
  1121. onlyDuplicateUserRelatedResources: boolean, shouldUseV4Process = true,
  1122. ) {
  1123. if (shouldUseV4Process) {
  1124. return this.duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix);
  1125. }
  1126. const Page = mongoose.model<PageDocument, PageModel>('Page');
  1127. const pageIds = pages.map(page => page._id);
  1128. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  1129. // Mapping to set to the body of the new revision
  1130. const pageIdRevisionMapping: Record<string, IRevisionDocument> = {};
  1131. revisions.forEach((revision) => {
  1132. pageIdRevisionMapping[getIdStringForRef(revision.pageId)] = revision;
  1133. });
  1134. // key: oldPageId, value: newPageId
  1135. const pageIdMapping = {};
  1136. const newPages: any[] = [];
  1137. const newRevisions: any[] = [];
  1138. const userRelatedGroups = await this.pageGrantService.getUserRelatedGroups(user);
  1139. // no need to save parent here
  1140. pages.forEach((page) => {
  1141. const newPageId = new mongoose.Types.ObjectId();
  1142. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  1143. const revisionId = new mongoose.Types.ObjectId();
  1144. pageIdMapping[page._id] = newPageId;
  1145. const isDuplicateTarget = !page.isEmpty
  1146. && (!onlyDuplicateUserRelatedResources || this.pageGrantService.isUserGrantedPageAccess(page, user, userRelatedGroups));
  1147. if (isDuplicateTarget) {
  1148. const grantedGroups = onlyDuplicateUserRelatedResources
  1149. ? this.pageGrantService.getUserRelatedGrantedGroupsSyncronously(userRelatedGroups, page)
  1150. : page.grantedGroups;
  1151. const newPage = {
  1152. _id: newPageId,
  1153. path: newPagePath,
  1154. creator: user._id,
  1155. grant: page.grant,
  1156. grantedGroups,
  1157. grantedUsers: page.grantedUsers,
  1158. lastUpdateUser: user._id,
  1159. revision: revisionId,
  1160. };
  1161. newRevisions.push({
  1162. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id.toString()].body, author: user._id, format: 'markdown',
  1163. });
  1164. newPages.push(newPage);
  1165. }
  1166. });
  1167. const duplicatedPages = await Page.insertMany(newPages, { ordered: false });
  1168. const duplicatedPageIds = duplicatedPages.map(duplicatedPage => duplicatedPage._id);
  1169. await Revision.insertMany(newRevisions, { ordered: false });
  1170. await this.duplicateTags(pageIdMapping);
  1171. const duplicatedPagesWithPopulatedToShowRevison = await Page
  1172. .find({ _id: { $in: duplicatedPageIds }, grant: PageGrant.GRANT_PUBLIC }).populate('revision') as PageDocument[];
  1173. if (isAiEnabled()) {
  1174. // TODO: https://redmine.weseek.co.jp/issues/160336
  1175. const { getOpenaiService } = await import('~/features/openai/server/services/openai');
  1176. // Do not await because communication with OpenAI takes time
  1177. const openaiService = getOpenaiService();
  1178. // openaiService?.createVectorStoreFile(duplicatedPagesWithPopulatedToShowRevison);
  1179. }
  1180. }
  1181. private async duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  1182. const Page = this.crowi.model('Page');
  1183. const pageIds = pages.map(page => page._id);
  1184. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  1185. // Mapping to set to the body of the new revision
  1186. const pageIdRevisionMapping: Record<string, IRevisionDocument> = {};
  1187. revisions.forEach((revision) => {
  1188. pageIdRevisionMapping[getIdStringForRef(revision.pageId)] = revision;
  1189. });
  1190. // key: oldPageId, value: newPageId
  1191. const pageIdMapping = {};
  1192. const newPages: any[] = [];
  1193. const newRevisions: any[] = [];
  1194. pages.forEach((page) => {
  1195. const newPageId = new mongoose.Types.ObjectId();
  1196. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  1197. const revisionId = new mongoose.Types.ObjectId();
  1198. pageIdMapping[page._id] = newPageId;
  1199. newPages.push({
  1200. _id: newPageId,
  1201. path: newPagePath,
  1202. creator: user._id,
  1203. grant: page.grant,
  1204. grantedGroups: page.grantedGroups,
  1205. grantedUsers: page.grantedUsers,
  1206. lastUpdateUser: user._id,
  1207. revision: revisionId,
  1208. });
  1209. newRevisions.push({
  1210. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id.toString()].body, author: user._id, format: 'markdown',
  1211. });
  1212. });
  1213. await Page.insertMany(newPages, { ordered: false });
  1214. await Revision.insertMany(newRevisions, { ordered: false });
  1215. await this.duplicateTags(pageIdMapping);
  1216. }
  1217. private async duplicateDescendantsWithStream(page, newPagePath, user, onlyDuplicateUserRelatedResources: boolean, shouldUseV4Process = true) {
  1218. if (shouldUseV4Process) {
  1219. return this.duplicateDescendantsWithStreamV4(page, newPagePath, user, onlyDuplicateUserRelatedResources);
  1220. }
  1221. const iterableFactory = new PageCursorsForDescendantsFactory(user, page, true);
  1222. const readStream = await iterableFactory.generateReadable();
  1223. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  1224. const newPagePathPrefix = newPagePath;
  1225. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  1226. const duplicateDescendants = this.duplicateDescendants.bind(this);
  1227. const pageEvent = this.pageEvent;
  1228. let count = 0;
  1229. let nNonEmptyDuplicatedPages = 0;
  1230. const writeStream = new Writable({
  1231. objectMode: true,
  1232. async write(batch, encoding, callback) {
  1233. try {
  1234. count += batch.length;
  1235. nNonEmptyDuplicatedPages += batch.filter(page => !page.isEmpty).length;
  1236. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, onlyDuplicateUserRelatedResources, shouldUseV4Process);
  1237. logger.debug(`Adding pages progressing: (count=${count})`);
  1238. }
  1239. catch (err) {
  1240. logger.error('addAllPages error on add anyway: ', err);
  1241. }
  1242. callback();
  1243. },
  1244. async final(callback) {
  1245. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1246. // update path
  1247. page.path = newPagePath;
  1248. pageEvent.emit('syncDescendantsUpdate', page, user);
  1249. callback();
  1250. },
  1251. });
  1252. await pipeline(readStream, batchStream, writeStream);
  1253. return nNonEmptyDuplicatedPages;
  1254. }
  1255. private async duplicateDescendantsWithStreamV4(page, newPagePath, user, onlyDuplicateUserRelatedResources: boolean) {
  1256. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  1257. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  1258. const newPagePathPrefix = newPagePath;
  1259. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  1260. const duplicateDescendants = this.duplicateDescendants.bind(this);
  1261. const pageEvent = this.pageEvent;
  1262. let count = 0;
  1263. const writeStream = new Writable({
  1264. objectMode: true,
  1265. async write(batch, encoding, callback) {
  1266. try {
  1267. count += batch.length;
  1268. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, onlyDuplicateUserRelatedResources);
  1269. logger.debug(`Adding pages progressing: (count=${count})`);
  1270. }
  1271. catch (err) {
  1272. logger.error('addAllPages error on add anyway: ', err);
  1273. }
  1274. callback();
  1275. },
  1276. final(callback) {
  1277. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1278. // update path
  1279. page.path = newPagePath;
  1280. pageEvent.emit('syncDescendantsUpdate', page, user);
  1281. callback();
  1282. },
  1283. });
  1284. await pipeline(readStream, batchStream, writeStream);
  1285. return count;
  1286. }
  1287. /*
  1288. * Delete
  1289. */
  1290. async deletePage(page, user, options = {}, isRecursively = false, activityParameters) {
  1291. /*
  1292. * Common Operation
  1293. */
  1294. const Page = mongoose.model('Page') as PageModel;
  1295. // Separate v4 & v5 process
  1296. const isShouldUseV4Process = shouldUseV4Process(page);
  1297. if (isShouldUseV4Process) {
  1298. return this.deletePageV4(page, user, options, isRecursively);
  1299. }
  1300. // Validate
  1301. if (page.isEmpty && !isRecursively) {
  1302. throw Error('Page not found.');
  1303. }
  1304. const isTrashed = isTrashPage(page.path);
  1305. if (isTrashed) {
  1306. throw new Error('This method does NOT support deleting trashed pages.');
  1307. }
  1308. if (isTopPage(page.path) || isUsersTopPage(page.path)) {
  1309. throw new Error('Page is not deletable.');
  1310. }
  1311. if (pagePathUtils.isUsersHomepage(page.path)) {
  1312. if (!this.canDeleteUserHomepageByConfig()) {
  1313. throw new Error('User Homepage is not deletable.');
  1314. }
  1315. if (!await this.isUsersHomepageOwnerAbsent(page.path)) {
  1316. throw new Error('User Homepage is not deletable.');
  1317. }
  1318. }
  1319. const newPath = Page.getDeletedPageName(page.path);
  1320. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1321. if (!canOperate) {
  1322. throw Error(`Cannot operate delete to path "${newPath}" right now.`);
  1323. }
  1324. // Replace with an empty page
  1325. const isChildrenExist = await Page.exists({ parent: page._id });
  1326. const shouldReplace = !isRecursively && isChildrenExist;
  1327. if (shouldReplace) {
  1328. await Page.replaceTargetWithPage(page, null, true);
  1329. }
  1330. const parameters = {
  1331. ip: activityParameters.ip,
  1332. endpoint: activityParameters.endpoint,
  1333. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_DELETE : SupportedAction.ACTION_PAGE_DELETE,
  1334. user,
  1335. target: page,
  1336. targetModel: 'Page',
  1337. snapshot: {
  1338. username: user.username,
  1339. },
  1340. };
  1341. const activity = await this.crowi.activityService.createActivity(parameters);
  1342. // Delete target (only updating an existing document's properties )
  1343. let deletedPage;
  1344. if (!page.isEmpty) {
  1345. deletedPage = await this.deleteNonEmptyTarget(page, user);
  1346. }
  1347. else { // always recursive
  1348. deletedPage = page;
  1349. await Page.deleteOne({ _id: page._id, isEmpty: true });
  1350. }
  1351. // 1. Update descendantCount
  1352. if (isRecursively) {
  1353. const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
  1354. await this.updateDescendantCountOfAncestors(page.parent, inc, true);
  1355. }
  1356. else {
  1357. // update descendantCount of ancestors'
  1358. await this.updateDescendantCountOfAncestors(page.parent, -1, true);
  1359. }
  1360. // 2. Delete leaf empty pages
  1361. await Page.removeLeafEmptyPagesRecursively(page.parent);
  1362. if (isRecursively) {
  1363. let pageOp;
  1364. try {
  1365. pageOp = await PageOperation.create({
  1366. actionType: PageActionType.Delete,
  1367. actionStage: PageActionStage.Main,
  1368. page,
  1369. user,
  1370. fromPath: page.path,
  1371. toPath: newPath,
  1372. });
  1373. }
  1374. catch (err) {
  1375. logger.error('Failed to create PageOperation document.', err);
  1376. throw err;
  1377. }
  1378. /*
  1379. * Resumable Operation
  1380. */
  1381. (async() => {
  1382. try {
  1383. await this.deleteRecursivelyMainOperation(page, user, pageOp._id, activity);
  1384. }
  1385. catch (err) {
  1386. logger.error('Error occurred while running deleteRecursivelyMainOperation.', err);
  1387. // cleanup
  1388. await PageOperation.deleteOne({ _id: pageOp._id });
  1389. throw err;
  1390. }
  1391. finally {
  1392. this.pageEvent.emit('syncDescendantsUpdate', deletedPage, user);
  1393. }
  1394. })();
  1395. }
  1396. else {
  1397. const preNotify = preNotifyService.generatePreNotify(activity);
  1398. this.activityEvent.emit('updated', activity, page, preNotify);
  1399. }
  1400. return deletedPage;
  1401. }
  1402. private async deleteNonEmptyTarget(page, user) {
  1403. const Page = mongoose.model('Page') as unknown as PageModel;
  1404. const newPath = Page.getDeletedPageName(page.path);
  1405. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  1406. $set: {
  1407. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  1408. },
  1409. }, { new: true });
  1410. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  1411. try {
  1412. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  1413. }
  1414. catch (err) {
  1415. if (err.code !== 11000) {
  1416. throw err;
  1417. }
  1418. }
  1419. this.pageEvent.emit('delete', page, deletedPage, user);
  1420. return deletedPage;
  1421. }
  1422. async deleteRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1423. const descendantsSubscribedSets = new Set();
  1424. await this.deleteDescendantsWithStream(page, user, false, descendantsSubscribedSets);
  1425. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  1426. const preNotify = preNotifyService.generatePreNotify(activity, async() => { return descendantsSubscribedUsers });
  1427. this.activityEvent.emit('updated', activity, page, preNotify);
  1428. await PageOperation.findByIdAndDelete(pageOpId);
  1429. // no sub operation available
  1430. }
  1431. private async deletePageV4(page: HydratedDocument<PageDocument>, user, options = {}, isRecursively = false) {
  1432. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  1433. const newPath = Page.getDeletedPageName(page.path);
  1434. const isTrashed = isTrashPage(page.path);
  1435. if (isTrashed) {
  1436. throw new Error('This method does NOT support deleting trashed pages.');
  1437. }
  1438. if (!isMovablePage(page.path)) {
  1439. throw new Error('Page is not deletable.');
  1440. }
  1441. if (isRecursively) {
  1442. this.deleteDescendantsWithStream(page, user);
  1443. }
  1444. // update Revisions
  1445. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  1446. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  1447. $set: {
  1448. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  1449. },
  1450. }, { new: true });
  1451. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  1452. try {
  1453. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  1454. }
  1455. catch (err) {
  1456. if (err.code !== 11000) {
  1457. throw err;
  1458. }
  1459. }
  1460. this.pageEvent.emit('delete', page, deletedPage, user);
  1461. return deletedPage;
  1462. }
  1463. private async deleteDescendants(pages, user) {
  1464. const Page = mongoose.model('Page') as unknown as PageModel;
  1465. const deletePageOperations: any[] = [];
  1466. const insertPageRedirectOperations: any[] = [];
  1467. pages.forEach((page) => {
  1468. const newPath = Page.getDeletedPageName(page.path);
  1469. let operation;
  1470. // if empty, delete completely
  1471. if (page.isEmpty) {
  1472. operation = {
  1473. deleteOne: {
  1474. filter: { _id: page._id },
  1475. },
  1476. };
  1477. }
  1478. // if not empty, set parent to null and update to trash
  1479. else {
  1480. operation = {
  1481. updateOne: {
  1482. filter: { _id: page._id },
  1483. update: {
  1484. $set: {
  1485. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  1486. },
  1487. },
  1488. },
  1489. };
  1490. insertPageRedirectOperations.push({
  1491. insertOne: {
  1492. document: {
  1493. fromPath: page.path,
  1494. toPath: newPath,
  1495. },
  1496. },
  1497. });
  1498. }
  1499. deletePageOperations.push(operation);
  1500. });
  1501. try {
  1502. await Page.bulkWrite(deletePageOperations);
  1503. }
  1504. catch (err) {
  1505. if (err.code !== 11000) {
  1506. throw new Error(`Failed to delete pages: ${err}`);
  1507. }
  1508. }
  1509. finally {
  1510. this.pageEvent.emit('syncDescendantsDelete', pages, user);
  1511. }
  1512. try {
  1513. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  1514. }
  1515. catch (err) {
  1516. if (err.code !== 11000) {
  1517. throw Error(`Failed to create PageRedirect documents: ${err}`);
  1518. }
  1519. }
  1520. }
  1521. /**
  1522. * Create delete stream and return deleted document count
  1523. */
  1524. private async deleteDescendantsWithStream(targetPage, user, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  1525. let readStream;
  1526. if (shouldUseV4Process) {
  1527. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1528. }
  1529. else {
  1530. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1531. readStream = await factory.generateReadable();
  1532. }
  1533. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  1534. const deleteDescendants = this.deleteDescendants.bind(this);
  1535. let count = 0;
  1536. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1537. const writeStream = new Writable({
  1538. objectMode: true,
  1539. async write(batch, encoding, callback) {
  1540. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1541. try {
  1542. count += batch.length;
  1543. await deleteDescendants(batch, user);
  1544. const subscribedUsers = await Subscription.getSubscriptions(batch);
  1545. subscribedUsers.forEach((eachUser) => {
  1546. descendantsSubscribedSets.add(eachUser);
  1547. });
  1548. logger.debug(`Deleting pages progressing: (count=${count})`);
  1549. }
  1550. catch (err) {
  1551. logger.error('deleteDescendants error on add anyway: ', err);
  1552. }
  1553. callback();
  1554. },
  1555. final(callback) {
  1556. logger.debug(`Deleting pages has completed: (totalCount=${count})`);
  1557. callback();
  1558. },
  1559. });
  1560. await pipeline(readStream, batchStream, writeStream);
  1561. return nDeletedNonEmptyPages;
  1562. }
  1563. async deleteCompletelyOperation(pageIds, pagePaths): Promise<void> {
  1564. // Delete Attachments, Revisions, Pages and emit delete
  1565. const Page = this.crowi.model('Page');
  1566. const { attachmentService } = this.crowi;
  1567. const attachments = await Attachment.find({ page: { $in: pageIds } });
  1568. await Promise.all([
  1569. Comment.deleteMany({ page: { $in: pageIds } }),
  1570. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  1571. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  1572. Revision.deleteMany({ pageId: { $in: pageIds } }),
  1573. Page.deleteMany({ _id: { $in: pageIds } }),
  1574. PageRedirect.deleteMany({ $or: [{ fromPath: { $in: pagePaths } }, { toPath: { $in: pagePaths } }] }),
  1575. attachmentService.removeAllAttachments(attachments),
  1576. // Leave bookmarks without deleting -- 2024.05.17 Yuki Takei
  1577. ]);
  1578. if (isAiEnabled()) {
  1579. const { getOpenaiService } = await import('~/features/openai/server/services/openai');
  1580. // TODO: https://redmine.weseek.co.jp/issues/160337
  1581. const openaiService = getOpenaiService();
  1582. if (openaiService != null) {
  1583. // const vectorStore = await openaiService.getOrCreateVectorStoreForPublicScope();
  1584. // const deleteVectorStoreFilePromises = pageIds.map(pageId => openaiService.deleteVectorStoreFile(vectorStore._id, pageId));
  1585. // await Promise.allSettled(deleteVectorStoreFilePromises);
  1586. }
  1587. }
  1588. }
  1589. // delete multiple pages
  1590. async deleteMultipleCompletely(pages, user) {
  1591. const ids = pages.map(page => (page._id));
  1592. const paths = pages.map(page => (page.path));
  1593. logger.debug('Deleting completely', paths);
  1594. await this.deleteCompletelyOperation(ids, paths);
  1595. this.pageEvent.emit('syncDescendantsDelete', pages, user); // update as renamed page
  1596. return;
  1597. }
  1598. async deleteCompletely(page, user, options = {}, isRecursively = false, preventEmitting = false, activityParameters) {
  1599. /*
  1600. * Common Operation
  1601. */
  1602. const Page = mongoose.model('Page') as PageModel;
  1603. if (isTopPage(page.path)) {
  1604. throw Error('It is forbidden to delete the top page');
  1605. }
  1606. if (page.isEmpty && !isRecursively) {
  1607. throw Error('Page not found.');
  1608. }
  1609. // v4 compatible process
  1610. const isShouldUseV4Process = shouldUseV4Process(page);
  1611. if (isShouldUseV4Process) {
  1612. return this.deleteCompletelyV4(page, user, options, isRecursively, preventEmitting);
  1613. }
  1614. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, null);
  1615. if (!canOperate) {
  1616. throw Error(`Cannot operate deleteCompletely from path "${page.path}" right now.`);
  1617. }
  1618. const ids = [page._id];
  1619. const paths = [page.path];
  1620. logger.debug('Deleting completely', paths);
  1621. const parameters = {
  1622. ip: activityParameters.ip,
  1623. endpoint: activityParameters.endpoint,
  1624. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_DELETE_COMPLETELY : SupportedAction.ACTION_PAGE_DELETE_COMPLETELY,
  1625. user,
  1626. target: page,
  1627. targetModel: 'Page',
  1628. snapshot: {
  1629. username: user.username,
  1630. },
  1631. };
  1632. const activity = await this.crowi.activityService.createActivity(parameters);
  1633. // 1. update descendantCount
  1634. if (isRecursively) {
  1635. const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
  1636. await this.updateDescendantCountOfAncestors(page.parent, inc, true);
  1637. }
  1638. else {
  1639. // replace with an empty page
  1640. const shouldReplace = await Page.exists({ parent: page._id });
  1641. let pageToUpdateDescendantCount = page;
  1642. if (shouldReplace) {
  1643. pageToUpdateDescendantCount = await Page.replaceTargetWithPage(page);
  1644. }
  1645. await this.updateDescendantCountOfAncestors(pageToUpdateDescendantCount.parent, -1, true);
  1646. }
  1647. // 2. then delete target completely
  1648. await this.deleteCompletelyOperation(ids, paths);
  1649. // delete leaf empty pages
  1650. await Page.removeLeafEmptyPagesRecursively(page.parent);
  1651. if (!page.isEmpty && !preventEmitting) {
  1652. this.pageEvent.emit('deleteCompletely', page, user);
  1653. }
  1654. if (isRecursively) {
  1655. let pageOp;
  1656. try {
  1657. pageOp = await PageOperation.create({
  1658. actionType: PageActionType.DeleteCompletely,
  1659. actionStage: PageActionStage.Main,
  1660. page,
  1661. user,
  1662. fromPath: page.path,
  1663. options,
  1664. });
  1665. }
  1666. catch (err) {
  1667. logger.error('Failed to create PageOperation document.', err);
  1668. throw err;
  1669. }
  1670. /*
  1671. * Main Operation
  1672. */
  1673. (async() => {
  1674. try {
  1675. await this.deleteCompletelyRecursivelyMainOperation(page, user, options, pageOp._id, activity);
  1676. }
  1677. catch (err) {
  1678. logger.error('Error occurred while running deleteCompletelyRecursivelyMainOperation.', err);
  1679. // cleanup
  1680. await PageOperation.deleteOne({ _id: pageOp._id });
  1681. throw err;
  1682. }
  1683. })();
  1684. }
  1685. else {
  1686. const preNotify = preNotifyService.generatePreNotify(activity);
  1687. this.activityEvent.emit('updated', activity, page, preNotify);
  1688. }
  1689. return;
  1690. }
  1691. async deleteCompletelyRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1692. const descendantsSubscribedSets = new Set();
  1693. await this.deleteCompletelyDescendantsWithStream(page, user, options, false, descendantsSubscribedSets);
  1694. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  1695. const preNotify = preNotifyService.generatePreNotify(activity, async() => { return descendantsSubscribedUsers });
  1696. this.activityEvent.emit('updated', activity, page, preNotify);
  1697. await PageOperation.findByIdAndDelete(pageOpId);
  1698. // no sub operation available
  1699. }
  1700. private async deleteCompletelyV4(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  1701. const ids = [page._id];
  1702. const paths = [page.path];
  1703. logger.debug('Deleting completely', paths);
  1704. await this.deleteCompletelyOperation(ids, paths);
  1705. if (isRecursively) {
  1706. this.deleteCompletelyDescendantsWithStream(page, user, options);
  1707. }
  1708. if (!page.isEmpty && !preventEmitting) {
  1709. this.pageEvent.emit('deleteCompletely', page, user);
  1710. }
  1711. return;
  1712. }
  1713. async emptyTrashPage(user, options = {}, activityParameters) {
  1714. const page = { path: '/trash' };
  1715. const parameters = {
  1716. ...activityParameters,
  1717. action: SupportedAction.ACTION_PAGE_RECURSIVELY_DELETE_COMPLETELY,
  1718. user,
  1719. targetModel: 'Page',
  1720. snapshot: {
  1721. username: user.username,
  1722. },
  1723. };
  1724. const activity = await this.crowi.activityService.createActivity(parameters);
  1725. const descendantsSubscribedSets = new Set();
  1726. const pages = await this.deleteCompletelyDescendantsWithStream(page, user, options, true, descendantsSubscribedSets);
  1727. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  1728. const preNotify = preNotifyService.generatePreNotify(activity, async() => { return descendantsSubscribedUsers });
  1729. this.activityEvent.emit('updated', activity, page, preNotify);
  1730. return pages;
  1731. }
  1732. /**
  1733. * Create delete completely stream
  1734. */
  1735. private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  1736. let readStream;
  1737. if (shouldUseV4Process) { // pages don't have parents
  1738. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1739. }
  1740. else {
  1741. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1742. readStream = await factory.generateReadable();
  1743. }
  1744. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  1745. let count = 0;
  1746. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1747. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  1748. const writeStream = new Writable({
  1749. objectMode: true,
  1750. async write(batch, encoding, callback) {
  1751. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1752. try {
  1753. count += batch.length;
  1754. await deleteMultipleCompletely(batch, user);
  1755. const subscribedUsers = await Subscription.getSubscriptions(batch);
  1756. subscribedUsers.forEach((eachUser) => {
  1757. descendantsSubscribedSets.add(eachUser);
  1758. });
  1759. logger.debug(`Adding pages progressing: (count=${count})`);
  1760. }
  1761. catch (err) {
  1762. logger.error('addAllPages error on add anyway: ', err);
  1763. }
  1764. callback();
  1765. },
  1766. final(callback) {
  1767. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1768. callback();
  1769. },
  1770. });
  1771. await pipeline(readStream, batchStream, writeStream);
  1772. return nDeletedNonEmptyPages;
  1773. }
  1774. // no need to separate Main Sub since it is devided into single page operations
  1775. async deleteMultiplePages(pagesToDelete, user, options, activityParameters): Promise<void> {
  1776. const { isRecursively, isCompletely } = options;
  1777. if (pagesToDelete.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1778. throw Error(`The maximum number of pages is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1779. }
  1780. // omit duplicate paths if isRecursively true, omit empty pages if isRecursively false
  1781. const pages = isRecursively ? omitDuplicateAreaPageFromPages(pagesToDelete) : pagesToDelete.filter(p => !p.isEmpty);
  1782. if (isCompletely) {
  1783. for await (const page of pages) {
  1784. await this.deleteCompletely(page, user, {}, isRecursively, false, activityParameters);
  1785. }
  1786. }
  1787. else {
  1788. for await (const page of pages) {
  1789. await this.deletePage(page, user, {}, isRecursively, activityParameters);
  1790. }
  1791. }
  1792. }
  1793. // use the same process in both v4 and v5
  1794. private async revertDeletedDescendants(pages, user) {
  1795. const Page = this.crowi.model('Page');
  1796. const revertPageOperations: any[] = [];
  1797. const fromPathsToDelete: string[] = [];
  1798. pages.forEach((page) => {
  1799. // e.g. page.path = /trash/test, toPath = /test
  1800. const toPath = Page.getRevertDeletedPageName(page.path);
  1801. revertPageOperations.push({
  1802. updateOne: {
  1803. filter: { _id: page._id },
  1804. update: {
  1805. $set: {
  1806. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1807. },
  1808. },
  1809. },
  1810. });
  1811. fromPathsToDelete.push(page.path);
  1812. });
  1813. try {
  1814. await Page.bulkWrite(revertPageOperations);
  1815. await PageRedirect.deleteMany({ fromPath: { $in: fromPathsToDelete } });
  1816. }
  1817. catch (err) {
  1818. if (err.code !== 11000) {
  1819. throw new Error(`Failed to revert pages: ${err}`);
  1820. }
  1821. }
  1822. }
  1823. async revertDeletedPage(page, user, options = {}, isRecursively = false, activityParameters?) {
  1824. /*
  1825. * Common Operation
  1826. */
  1827. const Page = this.crowi.model('Page');
  1828. const parameters = {
  1829. ip: activityParameters.ip,
  1830. endpoint: activityParameters.endpoint,
  1831. action: page.descendantCount > 0 ? SupportedAction.ACTION_PAGE_RECURSIVELY_REVERT : SupportedAction.ACTION_PAGE_REVERT,
  1832. user,
  1833. target: page,
  1834. targetModel: 'Page',
  1835. snapshot: {
  1836. username: user.username,
  1837. },
  1838. };
  1839. const activity = await this.crowi.activityService.createActivity(parameters);
  1840. // 1. Separate v4 & v5 process
  1841. const shouldUseV4Process = this.shouldUseV4ProcessForRevert(page);
  1842. if (shouldUseV4Process) {
  1843. return this.revertDeletedPageV4(page, user, options, isRecursively);
  1844. }
  1845. const newPath = Page.getRevertDeletedPageName(page.path);
  1846. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1847. if (!canOperate) {
  1848. throw Error(`Cannot operate revert from path "${page.path}" right now.`);
  1849. }
  1850. const includeEmpty = true;
  1851. const originPage = await Page.findByPath(newPath, includeEmpty);
  1852. // throw if any page already exists when recursively operation
  1853. if (originPage != null && (!originPage.isEmpty || isRecursively)) {
  1854. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1855. }
  1856. // 2. Revert target
  1857. const parent = await this.getParentAndFillAncestorsByUser(user, newPath);
  1858. const shouldReplace = originPage != null && originPage.isEmpty;
  1859. let updatedPage = await Page.findByIdAndUpdate(page._id, {
  1860. $set: {
  1861. path: newPath,
  1862. status: Page.STATUS_PUBLISHED,
  1863. lastUpdateUser: user._id,
  1864. deleteUser: null,
  1865. deletedAt: null,
  1866. parent: parent._id,
  1867. descendantCount: shouldReplace ? originPage.descendantCount : 0,
  1868. },
  1869. }, { new: true });
  1870. if (shouldReplace) {
  1871. updatedPage = await Page.replaceTargetWithPage(originPage, updatedPage, true);
  1872. }
  1873. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1874. this.pageEvent.emit('revert', page, updatedPage, user);
  1875. if (!isRecursively) {
  1876. await this.updateDescendantCountOfAncestors(parent._id, 1, true);
  1877. const preNotify = preNotifyService.generatePreNotify(activity);
  1878. this.activityEvent.emit('updated', activity, page, preNotify);
  1879. }
  1880. else {
  1881. let pageOp;
  1882. try {
  1883. pageOp = await PageOperation.create({
  1884. actionType: PageActionType.Revert,
  1885. actionStage: PageActionStage.Main,
  1886. page,
  1887. user,
  1888. fromPath: page.path,
  1889. toPath: newPath,
  1890. options,
  1891. });
  1892. }
  1893. catch (err) {
  1894. logger.error('Failed to create PageOperation document.', err);
  1895. throw err;
  1896. }
  1897. /*
  1898. * Resumable Operation
  1899. */
  1900. (async() => {
  1901. try {
  1902. await this.revertRecursivelyMainOperation(page, user, options, pageOp._id, activity);
  1903. this.pageEvent.emit('syncDescendantsUpdate', updatedPage, user);
  1904. }
  1905. catch (err) {
  1906. logger.error('Error occurred while running revertRecursivelyMainOperation.', err);
  1907. // cleanup
  1908. await PageOperation.deleteOne({ _id: pageOp._id });
  1909. throw err;
  1910. }
  1911. })();
  1912. }
  1913. return updatedPage;
  1914. }
  1915. async revertRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike, activity?): Promise<void> {
  1916. const Page = mongoose.model('Page') as unknown as PageModel;
  1917. const descendantsSubscribedSets = new Set();
  1918. await this.revertDeletedDescendantsWithStream(page, user, options, false, descendantsSubscribedSets);
  1919. const descendantsSubscribedUsers = Array.from(descendantsSubscribedSets) as Ref<IUser>[];
  1920. const preNotify = preNotifyService.generatePreNotify(activity, async() => { return descendantsSubscribedUsers });
  1921. this.activityEvent.emit('updated', activity, page, preNotify);
  1922. const newPath = Page.getRevertDeletedPageName(page.path);
  1923. // normalize parent of descendant pages
  1924. const shouldNormalize = this.shouldNormalizeParent(page);
  1925. if (shouldNormalize) {
  1926. try {
  1927. await this.normalizeParentAndDescendantCountOfDescendants(newPath, user);
  1928. logger.info(`Successfully normalized reverted descendant pages under "${newPath}"`);
  1929. }
  1930. catch (err) {
  1931. logger.error('Failed to normalize descendants afrer revert:', err);
  1932. throw err;
  1933. }
  1934. }
  1935. // Set to Sub
  1936. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  1937. if (pageOp == null) {
  1938. throw Error('PageOperation document not found');
  1939. }
  1940. /*
  1941. * Sub Operation
  1942. */
  1943. await this.revertRecursivelySubOperation(newPath, pageOp._id);
  1944. }
  1945. async revertRecursivelySubOperation(newPath: string, pageOpId: ObjectIdLike): Promise<void> {
  1946. const Page = mongoose.model('Page') as unknown as PageModel;
  1947. const newTarget = await Page.findOne({ path: newPath }); // only one page will be found since duplicating to existing path is forbidden
  1948. if (newTarget == null) {
  1949. throw Error('No reverted page found. Something might have gone wrong in revertRecursivelyMainOperation.');
  1950. }
  1951. // update descendantCount of ancestors'
  1952. await this.updateDescendantCountOfAncestors(newTarget.parent as ObjectIdLike, newTarget.descendantCount + 1, true);
  1953. await PageOperation.findByIdAndDelete(pageOpId);
  1954. }
  1955. private async revertDeletedPageV4(page, user, options = {}, isRecursively = false) {
  1956. const Page = this.crowi.model('Page');
  1957. const newPath = Page.getRevertDeletedPageName(page.path);
  1958. const originPage = await Page.findByPath(newPath);
  1959. if (originPage != null) {
  1960. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1961. }
  1962. if (isRecursively) {
  1963. this.revertDeletedDescendantsWithStream(page, user, options);
  1964. }
  1965. page.status = Page.STATUS_PUBLISHED;
  1966. page.lastUpdateUser = user;
  1967. logger.debug('Revert deleted the page', page, newPath);
  1968. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1969. $set: {
  1970. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1971. },
  1972. }, { new: true });
  1973. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1974. this.pageEvent.emit('revert', page, updatedPage, user);
  1975. return updatedPage;
  1976. }
  1977. private async applyScopesToDescendantsWithStream(parentPage, user, isV4 = false) {
  1978. const Page = this.crowi.model('Page');
  1979. const builder = new Page.PageQueryBuilder(Page.find());
  1980. builder.addConditionToListOnlyDescendants(parentPage.path);
  1981. if (isV4) {
  1982. builder.addConditionAsRootOrNotOnTree();
  1983. }
  1984. else {
  1985. builder.addConditionAsOnTree();
  1986. }
  1987. // add grant conditions
  1988. await Page.addConditionToFilteringByViewerToEdit(builder, user);
  1989. const grant = parentPage.grant;
  1990. const userRelatedGroups = await this.pageGrantService.getUserRelatedGroups(user);
  1991. const userRelatedParentGrantedGroups = this.pageGrantService.getUserRelatedGrantedGroupsSyncronously(
  1992. userRelatedGroups, parentPage,
  1993. );
  1994. const childPagesReadableStream = builder.query.cursor({ batchSize: BULK_REINDEX_SIZE });
  1995. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  1996. const childPagesWritable = new Writable({
  1997. objectMode: true,
  1998. write: async(batch, encoding, callback) => {
  1999. await this.updateChildPagesGrant(batch, grant, user, userRelatedGroups, userRelatedParentGrantedGroups);
  2000. callback();
  2001. },
  2002. });
  2003. await pipeline(childPagesReadableStream, batchStream, childPagesWritable);
  2004. }
  2005. async updateChildPagesGrant(
  2006. pages: PageDocument[], grant: PageGrant, user, userRelatedGroups: PopulatedGrantedGroup[], userRelatedParentGrantedGroups: IGrantedGroup[],
  2007. ): Promise<void> {
  2008. const Page = this.crowi.model('Page');
  2009. const operations: any = [];
  2010. pages.forEach((childPage) => {
  2011. let newChildGrantedGroups: IGrantedGroup[] = [];
  2012. if (grant === PageGrant.GRANT_USER_GROUP) {
  2013. newChildGrantedGroups = this.getNewGrantedGroupsSyncronously(userRelatedGroups, userRelatedParentGrantedGroups, childPage);
  2014. }
  2015. const canChangeGrant = this.pageGrantService
  2016. .validateGrantChangeSyncronously(userRelatedGroups, childPage.grantedGroups, grant, newChildGrantedGroups);
  2017. if (canChangeGrant) {
  2018. operations.push({
  2019. updateOne: {
  2020. filter: { _id: childPage._id },
  2021. update: { $set: { grant, grantedUsers: grant === PageGrant.GRANT_OWNER ? [user._id] : [], grantedGroups: newChildGrantedGroups } },
  2022. },
  2023. });
  2024. }
  2025. });
  2026. await Page.bulkWrite(operations);
  2027. }
  2028. /**
  2029. * Create revert stream
  2030. */
  2031. private async revertDeletedDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true, descendantsSubscribedSets?): Promise<number> {
  2032. if (shouldUseV4Process) {
  2033. return this.revertDeletedDescendantsWithStreamV4(targetPage, user, options);
  2034. }
  2035. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  2036. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  2037. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  2038. let count = 0;
  2039. const writeStream = new Writable({
  2040. objectMode: true,
  2041. async write(batch, encoding, callback) {
  2042. try {
  2043. count += batch.length;
  2044. await revertDeletedDescendants(batch, user);
  2045. const subscribedUsers = await Subscription.getSubscriptions(batch);
  2046. subscribedUsers.forEach((eachUser) => {
  2047. descendantsSubscribedSets.add(eachUser);
  2048. });
  2049. logger.debug(`Reverting pages progressing: (count=${count})`);
  2050. }
  2051. catch (err) {
  2052. logger.error('revertPages error on add anyway: ', err);
  2053. }
  2054. callback();
  2055. },
  2056. async final(callback) {
  2057. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  2058. callback();
  2059. },
  2060. });
  2061. await pipeline(readStream, batchStream, writeStream);
  2062. return count;
  2063. }
  2064. private async revertDeletedDescendantsWithStreamV4(targetPage, user, options = {}) {
  2065. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  2066. const batchStream = createBatchStream(BULK_REINDEX_SIZE);
  2067. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  2068. let count = 0;
  2069. const writeStream = new Writable({
  2070. objectMode: true,
  2071. async write(batch, encoding, callback) {
  2072. try {
  2073. count += batch.length;
  2074. await revertDeletedDescendants(batch, user);
  2075. logger.debug(`Reverting pages progressing: (count=${count})`);
  2076. }
  2077. catch (err) {
  2078. logger.error('revertPages error on add anyway: ', err);
  2079. }
  2080. callback();
  2081. },
  2082. final(callback) {
  2083. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  2084. callback();
  2085. },
  2086. });
  2087. await pipeline(readStream, batchStream, writeStream);
  2088. return count;
  2089. }
  2090. async handlePrivatePagesForGroupsToDelete(
  2091. groupsToDelete: UserGroupDocument[] | ExternalUserGroupDocument[], action: PageActionOnGroupDelete, transferToUserGroup: IGrantedGroup, user,
  2092. ): Promise<void> {
  2093. const Page = mongoose.model<IPage, PageModel>('Page');
  2094. const pages = await Page.find({ grantedGroups: { $elemMatch: { item: { $in: groupsToDelete } } } });
  2095. switch (action) {
  2096. case PageActionOnGroupDelete.publicize:
  2097. await Page.removeGroupsToDeleteFromPages(pages, groupsToDelete);
  2098. break;
  2099. case PageActionOnGroupDelete.delete:
  2100. return this.deleteMultipleCompletely(pages, user);
  2101. case PageActionOnGroupDelete.transfer:
  2102. await Page.transferPagesToGroup(pages, transferToUserGroup);
  2103. break;
  2104. default:
  2105. throw new Error('Unknown action for private pages');
  2106. }
  2107. }
  2108. private extractStringIds(refs: Ref<HasObjectId>[]) {
  2109. return refs.map((ref: Ref<HasObjectId>) => {
  2110. return (typeof ref === 'string') ? ref : ref._id.toString();
  2111. });
  2112. }
  2113. constructBasicPageInfo(page: PageDocument, isGuestUser?: boolean): IPageInfo | Omit<IPageInfoForEntity, 'bookmarkCount'> {
  2114. const isMovable = isGuestUser ? false : isMovablePage(page.path);
  2115. const isDeletable = !(isGuestUser || isTopPage(page.path) || isUsersTopPage(page.path));
  2116. if (page.isEmpty) {
  2117. return {
  2118. isV5Compatible: true,
  2119. isEmpty: true,
  2120. isMovable,
  2121. isDeletable: false,
  2122. isAbleToDeleteCompletely: false,
  2123. isRevertible: false,
  2124. };
  2125. }
  2126. const likers = page.liker.slice(0, 15) as Ref<IUserHasId>[];
  2127. const seenUsers = page.seenUsers.slice(0, 15) as Ref<IUserHasId>[];
  2128. const infoForEntity: Omit<IPageInfoForEntity, 'bookmarkCount'> = {
  2129. isV5Compatible: isTopPage(page.path) || page.parent != null,
  2130. isEmpty: false,
  2131. sumOfLikers: page.liker.length,
  2132. likerIds: this.extractStringIds(likers),
  2133. seenUserIds: this.extractStringIds(seenUsers),
  2134. sumOfSeenUsers: page.seenUsers.length,
  2135. isMovable,
  2136. isDeletable,
  2137. isAbleToDeleteCompletely: false,
  2138. isRevertible: isTrashPage(page.path),
  2139. contentAge: page.getContentAge(),
  2140. descendantCount: page.descendantCount,
  2141. commentCount: page.commentCount,
  2142. };
  2143. return infoForEntity;
  2144. }
  2145. async shortBodiesMapByPageIds(pageIds: ObjectIdLike[] = [], user?): Promise<Record<string, string | null>> {
  2146. const Page = mongoose.model('Page') as unknown as PageModel;
  2147. const MAX_LENGTH = 350;
  2148. // aggregation options
  2149. const userGroups = user != null ? [
  2150. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2151. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2152. ] : null;
  2153. const viewerCondition = Page.generateGrantCondition(user, userGroups);
  2154. const filterByIds = {
  2155. _id: { $in: pageIds },
  2156. };
  2157. let pages;
  2158. try {
  2159. pages = await Page
  2160. .aggregate([
  2161. // filter by pageIds
  2162. {
  2163. $match: filterByIds,
  2164. },
  2165. // filter by viewer
  2166. {
  2167. $match: viewerCondition,
  2168. },
  2169. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  2170. {
  2171. $lookup: {
  2172. from: 'revisions',
  2173. let: { localRevision: '$revision' },
  2174. pipeline: [
  2175. {
  2176. $match: {
  2177. $expr: {
  2178. $eq: ['$_id', '$$localRevision'],
  2179. },
  2180. },
  2181. },
  2182. {
  2183. $project: {
  2184. // What is $substrCP?
  2185. // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
  2186. revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
  2187. },
  2188. },
  2189. ],
  2190. as: 'revisionData',
  2191. },
  2192. },
  2193. // projection
  2194. {
  2195. $project: {
  2196. _id: 1,
  2197. revisionData: 1,
  2198. },
  2199. },
  2200. ]).exec();
  2201. }
  2202. catch (err) {
  2203. logger.error('Error occurred while generating shortBodiesMap');
  2204. throw err;
  2205. }
  2206. const shortBodiesMap = {};
  2207. pages.forEach((page) => {
  2208. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  2209. });
  2210. return shortBodiesMap;
  2211. }
  2212. async normalizeParentByPath(path: string, user): Promise<void> {
  2213. const Page = mongoose.model<PageDocument, PageModel>('Page');
  2214. const { PageQueryBuilder } = Page;
  2215. // This validation is not 100% correct since it ignores user to count
  2216. const builder = new PageQueryBuilder(Page.find());
  2217. builder.addConditionAsRootOrNotOnTree();
  2218. builder.addConditionToListWithDescendants(path);
  2219. const nEstimatedNormalizationTarget: number = await builder.query.exec('count');
  2220. if (nEstimatedNormalizationTarget === 0) {
  2221. throw Error('No page is available for conversion');
  2222. }
  2223. const pages = await Page.findByPathAndViewer(path, user, null, false);
  2224. if (pages == null || !Array.isArray(pages)) {
  2225. throw Error('Something went wrong while converting pages.');
  2226. }
  2227. if (pages.length === 0) {
  2228. const isForbidden = await Page.count({ path, isEmpty: false }) > 0;
  2229. if (isForbidden) {
  2230. throw new V5ConversionError('It is not allowed to convert this page.', V5ConversionErrCode.FORBIDDEN);
  2231. }
  2232. }
  2233. if (pages.length > 1) {
  2234. throw new V5ConversionError(
  2235. `There are more than two pages at the path "${path}". Please rename or delete the page first.`,
  2236. V5ConversionErrCode.DUPLICATE_PAGES_FOUND,
  2237. );
  2238. }
  2239. let page;
  2240. let systematicallyCreatedPage;
  2241. const shouldCreateNewPage = pages[0] == null;
  2242. if (shouldCreateNewPage) {
  2243. const notEmptyParent = await Page.findNotEmptyParentByPathRecursively(path);
  2244. systematicallyCreatedPage = await this.forceCreateBySystem(
  2245. path,
  2246. '',
  2247. {
  2248. grant: notEmptyParent?.grant,
  2249. grantUserIds: notEmptyParent?.grantedUsers.map(u => getIdForRef(u)),
  2250. grantUserGroupIds: notEmptyParent?.grantedGroups,
  2251. },
  2252. );
  2253. page = systematicallyCreatedPage;
  2254. }
  2255. else {
  2256. page = pages[0];
  2257. }
  2258. const grant = page.grant;
  2259. const grantedUserIds = page.grantedUsers;
  2260. const grantedGroupIds = page.grantedGroups;
  2261. /*
  2262. * UserGroup & Owner validation
  2263. */
  2264. let isGrantNormalized = false;
  2265. try {
  2266. const shouldCheckDescendants = true;
  2267. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupIds, shouldCheckDescendants);
  2268. }
  2269. catch (err) {
  2270. logger.error(`Failed to validate grant of page at "${path}"`, err);
  2271. throw err;
  2272. }
  2273. if (!isGrantNormalized) {
  2274. throw new V5ConversionError(
  2275. 'This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.',
  2276. V5ConversionErrCode.GRANT_INVALID,
  2277. );
  2278. }
  2279. let pageOp;
  2280. try {
  2281. pageOp = await PageOperation.create({
  2282. actionType: PageActionType.NormalizeParent,
  2283. actionStage: PageActionStage.Main,
  2284. page,
  2285. user,
  2286. fromPath: page.path,
  2287. toPath: page.path,
  2288. });
  2289. }
  2290. catch (err) {
  2291. logger.error('Failed to create PageOperation document.', err);
  2292. throw err;
  2293. }
  2294. (async() => {
  2295. try {
  2296. await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  2297. }
  2298. catch (err) {
  2299. logger.error('Error occurred while running normalizeParentRecursivelyMainOperation.', err);
  2300. // cleanup
  2301. await PageOperation.deleteOne({ _id: pageOp._id });
  2302. throw err;
  2303. }
  2304. })();
  2305. }
  2306. async normalizeParentByPageIdsRecursively(pageIds: ObjectIdLike[], user): Promise<void> {
  2307. const Page = mongoose.model('Page') as unknown as PageModel;
  2308. const pages = await Page.findByIdsAndViewer(pageIds, user, null);
  2309. if (pages == null || pages.length === 0) {
  2310. throw Error('pageIds is null or 0 length.');
  2311. }
  2312. if (pages.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  2313. throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  2314. }
  2315. await this.normalizeParentRecursivelyByPages(pages, user);
  2316. return;
  2317. }
  2318. async normalizeParentByPageIds(pageIds: ObjectIdLike[], user): Promise<void> {
  2319. const Page = await mongoose.model('Page') as unknown as PageModel;
  2320. const socket = this.crowi.socketIoService.getDefaultSocket();
  2321. for await (const pageId of pageIds) {
  2322. const page = await Page.findById(pageId);
  2323. if (page == null) {
  2324. continue;
  2325. }
  2326. const errorData: PageMigrationErrorData = { paths: [page.path] };
  2327. try {
  2328. const canOperate = await this.crowi.pageOperationService.canOperate(false, page.path, page.path);
  2329. if (!canOperate) {
  2330. throw Error(`Cannot operate normalizeParent to path "${page.path}" right now.`);
  2331. }
  2332. const normalizedPage = await this.normalizeParentByPage(page, user);
  2333. if (normalizedPage == null) {
  2334. socket.emit(SocketEventName.PageMigrationError, errorData);
  2335. logger.error(`Failed to update descendantCount of page of id: "${pageId}"`);
  2336. }
  2337. }
  2338. catch (err) {
  2339. socket.emit(SocketEventName.PageMigrationError, errorData);
  2340. logger.error('Something went wrong while normalizing parent.', err);
  2341. }
  2342. }
  2343. socket.emit(SocketEventName.PageMigrationSuccess);
  2344. }
  2345. private async normalizeParentByPage(page, user) {
  2346. const Page = mongoose.model('Page') as unknown as PageModel;
  2347. const {
  2348. path, grant, grantedUsers: grantedUserIds, grantedGroups: grantedGroupIds,
  2349. } = page;
  2350. // check if any page exists at target path already
  2351. const existingPage = await Page.findOne({ path, parent: { $ne: null } });
  2352. if (existingPage != null && !existingPage.isEmpty) {
  2353. throw Error('Page already exists. Please rename the page to continue.');
  2354. }
  2355. /*
  2356. * UserGroup & Owner validation
  2357. */
  2358. if (grant !== Page.GRANT_RESTRICTED) {
  2359. let isGrantNormalized = false;
  2360. try {
  2361. const shouldCheckDescendants = true;
  2362. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupIds, shouldCheckDescendants);
  2363. }
  2364. catch (err) {
  2365. logger.error(`Failed to validate grant of page at "${path}"`, err);
  2366. throw err;
  2367. }
  2368. if (!isGrantNormalized) {
  2369. throw Error('This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.');
  2370. }
  2371. }
  2372. else {
  2373. throw Error('Restricted pages can not be migrated');
  2374. }
  2375. let normalizedPage;
  2376. // replace if empty page exists
  2377. if (existingPage != null && existingPage.isEmpty) {
  2378. // Inherit descendantCount from the empty page
  2379. const updatedPage = await Page.findOneAndUpdate({ _id: page._id }, { descendantCount: existingPage.descendantCount }, { new: true });
  2380. await Page.replaceTargetWithPage(existingPage, updatedPage, true);
  2381. normalizedPage = await Page.findById(page._id);
  2382. }
  2383. else {
  2384. const parent = await this.getParentAndFillAncestorsByUser(user, page.path);
  2385. normalizedPage = await Page.findOneAndUpdate({ _id: page._id }, { parent: parent._id }, { new: true });
  2386. }
  2387. // Update descendantCount
  2388. const inc = 1;
  2389. await this.updateDescendantCountOfAncestors(normalizedPage.parent, inc, true);
  2390. return normalizedPage;
  2391. }
  2392. async normalizeParentRecursivelyByPages(pages, user): Promise<void> {
  2393. /*
  2394. * Main Operation
  2395. */
  2396. const socket = this.crowi.socketIoService.getDefaultSocket();
  2397. const pagesToNormalize = omitDuplicateAreaPageFromPages(pages);
  2398. let normalizablePages;
  2399. let nonNormalizablePages;
  2400. try {
  2401. [normalizablePages, nonNormalizablePages] = await this.pageGrantService.separateNormalizableAndNotNormalizablePages(user, pagesToNormalize);
  2402. }
  2403. catch (err) {
  2404. socket.emit(SocketEventName.PageMigrationError);
  2405. throw err;
  2406. }
  2407. if (normalizablePages.length === 0) {
  2408. socket.emit(SocketEventName.PageMigrationError);
  2409. return;
  2410. }
  2411. if (nonNormalizablePages.length !== 0) {
  2412. const nonNormalizablePagePaths: string[] = nonNormalizablePages.map(p => p.path);
  2413. socket.emit(SocketEventName.PageMigrationError, { paths: nonNormalizablePagePaths });
  2414. logger.debug('Some pages could not be converted.', nonNormalizablePagePaths);
  2415. }
  2416. /*
  2417. * Main Operation (s)
  2418. */
  2419. const errorPagePaths: string[] = [];
  2420. for await (const page of normalizablePages) {
  2421. const canOperate = await this.crowi.pageOperationService.canOperate(true, page.path, page.path);
  2422. if (!canOperate) {
  2423. errorPagePaths.push(page.path);
  2424. throw Error(`Cannot operate normalizeParentRecursiively to path "${page.path}" right now.`);
  2425. }
  2426. const Page = mongoose.model('Page') as unknown as PageModel;
  2427. const { PageQueryBuilder } = Page;
  2428. const builder = new PageQueryBuilder(Page.findOne());
  2429. builder.addConditionAsOnTree();
  2430. builder.addConditionToListByPathsArray([page.path]);
  2431. const existingPage = await builder.query.exec();
  2432. if (existingPage?.parent != null) {
  2433. errorPagePaths.push(page.path);
  2434. throw Error('This page has already converted.');
  2435. }
  2436. let pageOp;
  2437. try {
  2438. pageOp = await PageOperation.create({
  2439. actionType: PageActionType.NormalizeParent,
  2440. actionStage: PageActionStage.Main,
  2441. page,
  2442. user,
  2443. fromPath: page.path,
  2444. toPath: page.path,
  2445. });
  2446. }
  2447. catch (err) {
  2448. errorPagePaths.push(page.path);
  2449. logger.error('Failed to create PageOperation document.', err);
  2450. throw err;
  2451. }
  2452. try {
  2453. await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  2454. }
  2455. catch (err) {
  2456. errorPagePaths.push(page.path);
  2457. logger.error('Failed to run normalizeParentRecursivelyMainOperation.', err);
  2458. // cleanup
  2459. await PageOperation.deleteOne({ _id: pageOp._id });
  2460. throw err;
  2461. }
  2462. }
  2463. if (errorPagePaths.length === 0) {
  2464. socket.emit(SocketEventName.PageMigrationSuccess);
  2465. }
  2466. else {
  2467. socket.emit(SocketEventName.PageMigrationError, { paths: errorPagePaths });
  2468. }
  2469. }
  2470. async normalizeParentRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike): Promise<number> {
  2471. // Save prevDescendantCount for sub-operation
  2472. const Page = mongoose.model('Page') as unknown as PageModel;
  2473. const { PageQueryBuilder } = Page;
  2474. const builder = new PageQueryBuilder(Page.findOne(), true);
  2475. builder.addConditionAsOnTree();
  2476. builder.addConditionToListByPathsArray([page.path]);
  2477. const exPage = await builder.query.exec();
  2478. const options = { prevDescendantCount: exPage?.descendantCount ?? 0 };
  2479. let count: number;
  2480. try {
  2481. count = await this.normalizeParentRecursively([page.path], user);
  2482. }
  2483. catch (err) {
  2484. logger.error('V5 initial miration failed.', err);
  2485. // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
  2486. throw err;
  2487. }
  2488. // Set to Sub
  2489. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  2490. if (pageOp == null) {
  2491. throw Error('PageOperation document not found');
  2492. }
  2493. await this.normalizeParentRecursivelySubOperation(page, user, pageOp._id, options);
  2494. return count;
  2495. }
  2496. async normalizeParentRecursivelySubOperation(page, user, pageOpId: ObjectIdLike, options: {prevDescendantCount: number}): Promise<void> {
  2497. const Page = mongoose.model('Page') as unknown as PageModel;
  2498. try {
  2499. // update descendantCount of self and descendant pages first
  2500. await this.updateDescendantCountOfSelfAndDescendants(page.path);
  2501. // find pages again to get updated descendantCount
  2502. // then calculate inc
  2503. const pageAfterUpdatingDescendantCount = await Page.findByIdAndViewer(page._id, user);
  2504. if (pageAfterUpdatingDescendantCount == null) {
  2505. throw Error('Page not found after updating descendantCount');
  2506. }
  2507. const { prevDescendantCount } = options;
  2508. const newDescendantCount = pageAfterUpdatingDescendantCount.descendantCount;
  2509. let inc = newDescendantCount - prevDescendantCount;
  2510. const isAlreadyConverted = page.parent != null;
  2511. if (!isAlreadyConverted) {
  2512. inc += 1;
  2513. }
  2514. await this.updateDescendantCountOfAncestors(page._id, inc, false);
  2515. }
  2516. catch (err) {
  2517. logger.error('Failed to update descendantCount after normalizing parent:', err);
  2518. throw Error(`Failed to update descendantCount after normalizing parent: ${err}`);
  2519. }
  2520. await PageOperation.findByIdAndDelete(pageOpId);
  2521. }
  2522. async _isPagePathIndexUnique() {
  2523. const Page = this.crowi.model('Page');
  2524. const now = (new Date()).toString();
  2525. const path = `growi_check_is_path_index_unique_${now}`;
  2526. let isUnique = false;
  2527. try {
  2528. await Page.insertMany([
  2529. { path },
  2530. { path },
  2531. ]);
  2532. }
  2533. catch (err) {
  2534. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  2535. isUnique = true;
  2536. logger.info('Page path index is unique.');
  2537. }
  2538. else {
  2539. throw err;
  2540. }
  2541. }
  2542. finally {
  2543. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  2544. }
  2545. return isUnique;
  2546. }
  2547. async normalizeAllPublicPages(): Promise<void> {
  2548. let isUnique;
  2549. try {
  2550. isUnique = await this._isPagePathIndexUnique();
  2551. }
  2552. catch (err) {
  2553. logger.error('Failed to check path index status', err);
  2554. throw err;
  2555. }
  2556. // drop unique index first
  2557. if (isUnique) {
  2558. try {
  2559. await this._v5NormalizeIndex();
  2560. }
  2561. catch (err) {
  2562. logger.error('V5 index normalization failed.', err);
  2563. throw err;
  2564. }
  2565. }
  2566. // then migrate
  2567. try {
  2568. await this.normalizeParentRecursively(['/'], null, false, true);
  2569. }
  2570. catch (err) {
  2571. logger.error('V5 initial miration failed.', err);
  2572. throw err;
  2573. }
  2574. // update descendantCount of all public pages
  2575. try {
  2576. await this.updateDescendantCountOfSelfAndDescendants('/');
  2577. logger.info('Successfully updated all descendantCount of public pages.');
  2578. }
  2579. catch (err) {
  2580. logger.error('Failed updating descendantCount of public pages.', err);
  2581. throw err;
  2582. }
  2583. await this._setIsV5CompatibleTrue();
  2584. }
  2585. private async _setIsV5CompatibleTrue() {
  2586. try {
  2587. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  2588. 'app:isV5Compatible': true,
  2589. });
  2590. logger.info('Successfully migrated all public pages.');
  2591. }
  2592. catch (err) {
  2593. logger.warn('Failed to update app:isV5Compatible to true.');
  2594. throw err;
  2595. }
  2596. }
  2597. private async normalizeParentAndDescendantCountOfDescendants(path: string, user, isDuplicateOperation = false): Promise<void> {
  2598. await this.normalizeParentRecursively([path], user, isDuplicateOperation);
  2599. // update descendantCount of descendant pages
  2600. await this.updateDescendantCountOfSelfAndDescendants(path);
  2601. }
  2602. /**
  2603. * Normalize parent attribute by passing paths and user.
  2604. * @param paths Pages under this paths value will be updated.
  2605. * @param user To be used to filter pages to update. If null, only public pages will be updated.
  2606. * @returns Promise<void>
  2607. */
  2608. async normalizeParentRecursively(paths: string[], user: any | null, isDuplicateOperation = false, shouldEmitProgress = false): Promise<number> {
  2609. const Page = mongoose.model('Page') as unknown as PageModel;
  2610. const ancestorPaths = paths.flatMap(p => collectAncestorPaths(p, []));
  2611. // targets' descendants
  2612. const pathAndRegExpsToNormalize: (RegExp | string)[] = paths
  2613. .map(p => new RegExp(`^${escapeStringRegexp(addTrailingSlash(p))}`, 'i'));
  2614. // include targets' path
  2615. pathAndRegExpsToNormalize.push(...paths);
  2616. // determine UserGroup condition
  2617. const userGroups = user != null ? [
  2618. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2619. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2620. ] : null;
  2621. const grantFiltersByUser: { $or: any[] } | null = !isDuplicateOperation ? Page.generateGrantCondition(user, userGroups) : null;
  2622. return this._normalizeParentRecursively(pathAndRegExpsToNormalize, ancestorPaths, user, grantFiltersByUser, shouldEmitProgress);
  2623. }
  2624. private buildFilterForNormalizeParentRecursively(
  2625. pathOrRegExps: (RegExp | string)[], publicPathsToNormalize: string[], grantFiltersByUser?: { $or: any[] } | null,
  2626. ) {
  2627. const Page = mongoose.model('Page') as unknown as PageModel;
  2628. const andFilter: any = {
  2629. $and: [
  2630. {
  2631. parent: null,
  2632. status: Page.STATUS_PUBLISHED,
  2633. path: { $ne: '/' },
  2634. },
  2635. ],
  2636. };
  2637. const orFilter: any = { $or: [] };
  2638. // specified pathOrRegExps
  2639. if (pathOrRegExps.length > 0) {
  2640. orFilter.$or.push(
  2641. {
  2642. path: { $in: pathOrRegExps },
  2643. },
  2644. );
  2645. }
  2646. // not specified but ancestors of specified pathOrRegExps
  2647. if (publicPathsToNormalize.length > 0) {
  2648. orFilter.$or.push(
  2649. {
  2650. path: { $in: publicPathsToNormalize },
  2651. grant: Page.GRANT_PUBLIC, // use only public pages to complete the tree
  2652. },
  2653. );
  2654. }
  2655. // Merge filters
  2656. const mergedFilter = {
  2657. $and: [
  2658. { $and: grantFiltersByUser != null ? [grantFiltersByUser, ...andFilter.$and] : [...andFilter.$and] },
  2659. { $or: orFilter.$or },
  2660. ],
  2661. };
  2662. return mergedFilter;
  2663. }
  2664. private async _normalizeParentRecursively(
  2665. pathOrRegExps: (RegExp | string)[],
  2666. publicPathsToNormalize: string[],
  2667. user,
  2668. grantFiltersByUser: { $or: any[] } | null,
  2669. shouldEmitProgress = false,
  2670. count = 0,
  2671. skiped = 0,
  2672. isFirst = true,
  2673. ): Promise<number> {
  2674. const BATCH_SIZE = 100;
  2675. const PAGES_LIMIT = 1000;
  2676. const socket = shouldEmitProgress ? this.crowi.socketIoService.getAdminSocket() : null;
  2677. const Page = mongoose.model('Page') as unknown as PageModel;
  2678. const { PageQueryBuilder } = Page;
  2679. // Build filter
  2680. const matchFilter = this.buildFilterForNormalizeParentRecursively(pathOrRegExps, publicPathsToNormalize, grantFiltersByUser);
  2681. let baseAggregation = Page
  2682. .aggregate([
  2683. { $match: matchFilter },
  2684. {
  2685. $project: { // minimize data to fetch
  2686. _id: 1,
  2687. path: 1,
  2688. },
  2689. },
  2690. ]);
  2691. // Limit pages to get
  2692. const total = await Page.countDocuments(matchFilter);
  2693. if (isFirst) {
  2694. socket?.emit(SocketEventName.PMStarted, { total });
  2695. }
  2696. if (total > PAGES_LIMIT) {
  2697. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  2698. }
  2699. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  2700. const batchStream = createBatchStream(BATCH_SIZE);
  2701. let shouldContinue = true;
  2702. let nextCount = count;
  2703. let nextSkiped = skiped;
  2704. // eslint-disable-next-line max-len
  2705. const buildPipelineToCreateEmptyPagesByUser = this.buildPipelineToCreateEmptyPagesByUser.bind(this);
  2706. const migratePagesStream = new Writable({
  2707. objectMode: true,
  2708. async write(pages, encoding, callback) {
  2709. const parentPaths = Array.from(new Set<string>(pages.map(p => pathlib.dirname(p.path))));
  2710. // 1. Remove unnecessary empty pages & reset parent for pages which had had those empty pages
  2711. const pageIdsToNotDelete = pages.map(p => p._id);
  2712. const emptyPagePathsToDelete = pages.map(p => p.path);
  2713. const builder1 = new PageQueryBuilder(Page.find({ isEmpty: true }, { _id: 1 }), true);
  2714. builder1.addConditionToListByPathsArray(emptyPagePathsToDelete);
  2715. builder1.addConditionToExcludeByPageIdsArray(pageIdsToNotDelete);
  2716. const emptyPagesToDelete = await builder1.query.lean().exec();
  2717. const resetParentOperations = emptyPagesToDelete.map((p) => {
  2718. return {
  2719. updateOne: {
  2720. filter: {
  2721. parent: p._id,
  2722. },
  2723. update: {
  2724. parent: null,
  2725. },
  2726. },
  2727. };
  2728. });
  2729. await Page.bulkWrite(resetParentOperations);
  2730. await Page.removeEmptyPages(pageIdsToNotDelete, emptyPagePathsToDelete);
  2731. // 2. Create lacking parents as empty pages
  2732. const orFilters = [
  2733. { path: '/' },
  2734. { path: { $in: publicPathsToNormalize }, grant: Page.GRANT_PUBLIC, status: Page.STATUS_PUBLISHED },
  2735. { path: { $in: publicPathsToNormalize }, parent: { $ne: null }, status: Page.STATUS_PUBLISHED },
  2736. { path: { $nin: publicPathsToNormalize }, status: Page.STATUS_PUBLISHED },
  2737. ];
  2738. const filterForApplicableAncestors = { $or: orFilters };
  2739. const aggregationPipeline = await buildPipelineToCreateEmptyPagesByUser(user, parentPaths, false, filterForApplicableAncestors);
  2740. await Page.createEmptyPagesByPaths(parentPaths, aggregationPipeline);
  2741. // 3. Find parents
  2742. const builder2 = new PageQueryBuilder(Page.find(), true);
  2743. if (grantFiltersByUser != null) {
  2744. builder2.query = builder2.query.and(grantFiltersByUser);
  2745. }
  2746. const parents = await builder2
  2747. .addConditionToListByPathsArray(parentPaths)
  2748. .addConditionToFilterByApplicableAncestors(publicPathsToNormalize)
  2749. .query
  2750. .lean()
  2751. .exec();
  2752. // Normalize all siblings for each page
  2753. const updateManyOperations = parents.map((parent) => {
  2754. const parentId = parent._id;
  2755. // Build filter
  2756. const parentPathEscaped = escapeStringRegexp(parent.path === '/' ? '' : parent.path); // adjust the path for RegExp
  2757. const filter: any = {
  2758. $and: [
  2759. {
  2760. path: { $regex: new RegExp(`^${parentPathEscaped}(\\/[^/]+)\\/?$`, 'i') }, // see: regexr.com/6889f (e.g. /parent/any_child or /any_level1)
  2761. },
  2762. {
  2763. path: { $in: pathOrRegExps.concat(publicPathsToNormalize) },
  2764. },
  2765. filterForApplicableAncestors,
  2766. ],
  2767. };
  2768. if (grantFiltersByUser != null) {
  2769. filter.$and.push(grantFiltersByUser);
  2770. }
  2771. return {
  2772. updateMany: {
  2773. filter,
  2774. update: {
  2775. parent: parentId,
  2776. },
  2777. },
  2778. };
  2779. });
  2780. try {
  2781. const res = await Page.bulkWrite(updateManyOperations);
  2782. nextCount += res.result.nModified;
  2783. nextSkiped += res.result.writeErrors.length;
  2784. logger.info(`Page migration processing: (migratedPages=${res.result.nModified})`);
  2785. socket?.emit(SocketEventName.PMMigrating, { count: nextCount });
  2786. socket?.emit(SocketEventName.PMErrorCount, { skip: nextSkiped });
  2787. // Throw if any error is found
  2788. if (res.result.writeErrors.length > 0) {
  2789. logger.error('Failed to migrate some pages', res.result.writeErrors);
  2790. socket?.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2791. throw Error('Failed to migrate some pages');
  2792. }
  2793. // Finish migration if no modification occurred
  2794. if (res.result.nModified === 0 && res.result.nMatched === 0) {
  2795. shouldContinue = false;
  2796. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  2797. socket?.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2798. }
  2799. }
  2800. catch (err) {
  2801. logger.error('Failed to update page.parent.', err);
  2802. throw err;
  2803. }
  2804. callback();
  2805. },
  2806. final(callback) {
  2807. callback();
  2808. },
  2809. });
  2810. await pipeline(pagesStream, batchStream, migratePagesStream);
  2811. if (await Page.exists(matchFilter) && shouldContinue) {
  2812. return this._normalizeParentRecursively(
  2813. pathOrRegExps,
  2814. publicPathsToNormalize,
  2815. user,
  2816. grantFiltersByUser,
  2817. shouldEmitProgress,
  2818. nextCount,
  2819. nextSkiped,
  2820. false,
  2821. );
  2822. }
  2823. // End
  2824. socket?.emit(SocketEventName.PMEnded, { isSucceeded: true });
  2825. return nextCount;
  2826. }
  2827. private async _v5NormalizeIndex() {
  2828. const collection = mongoose.connection.collection('pages');
  2829. try {
  2830. // drop pages.path_1 indexes
  2831. await collection.dropIndex('path_1');
  2832. logger.info('Succeeded to drop unique indexes from pages.path.');
  2833. }
  2834. catch (err) {
  2835. logger.warn('Failed to drop unique indexes from pages.path.', err);
  2836. throw err;
  2837. }
  2838. try {
  2839. // create indexes without
  2840. await collection.createIndex({ path: 1 }, { unique: false });
  2841. logger.info('Succeeded to create non-unique indexes on pages.path.');
  2842. }
  2843. catch (err) {
  2844. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  2845. throw err;
  2846. }
  2847. }
  2848. async countPagesCanNormalizeParentByUser(user): Promise<number> {
  2849. if (user == null) {
  2850. throw Error('user is required');
  2851. }
  2852. const Page = mongoose.model('Page') as unknown as PageModel;
  2853. const { PageQueryBuilder } = Page;
  2854. const builder = new PageQueryBuilder(Page.count(), false);
  2855. await builder.addConditionAsMigratablePages(user);
  2856. const nMigratablePages = await builder.query.exec();
  2857. return nMigratablePages;
  2858. }
  2859. /**
  2860. * update descendantCount of the following pages
  2861. * - page that has the same path as the provided path
  2862. * - pages that are descendants of the above page
  2863. */
  2864. async updateDescendantCountOfSelfAndDescendants(path: string): Promise<void> {
  2865. const BATCH_SIZE = 200;
  2866. const Page = this.crowi.model('Page');
  2867. const { PageQueryBuilder } = Page;
  2868. const builder = new PageQueryBuilder(Page.find(), true);
  2869. builder.addConditionAsOnTree();
  2870. builder.addConditionToListWithDescendants(path);
  2871. builder.addConditionToSortPagesByDescPath();
  2872. const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
  2873. await this.recountAndUpdateDescendantCountOfPages(aggregatedPages, BATCH_SIZE);
  2874. }
  2875. /**
  2876. * update descendantCount of the pages sequentially from longer path to shorter path
  2877. */
  2878. async updateDescendantCountOfPagesWithPaths(paths: string[]): Promise<void> {
  2879. const BATCH_SIZE = 200;
  2880. const Page = this.crowi.model('Page');
  2881. const { PageQueryBuilder } = Page;
  2882. const builder = new PageQueryBuilder(Page.find(), true);
  2883. builder.addConditionToListByPathsArray(paths); // find by paths
  2884. builder.addConditionToSortPagesByDescPath(); // sort in DESC
  2885. const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
  2886. await this.recountAndUpdateDescendantCountOfPages(aggregatedPages, BATCH_SIZE);
  2887. }
  2888. /**
  2889. * Recount descendantCount of pages one by one
  2890. */
  2891. async recountAndUpdateDescendantCountOfPages(pageCursor: Cursor<any>, batchSize:number): Promise<void> {
  2892. const Page = this.crowi.model('Page');
  2893. const batchStream = createBatchStream(batchSize);
  2894. const recountWriteStream = new Writable({
  2895. objectMode: true,
  2896. async write(pageDocuments, encoding, callback) {
  2897. for await (const document of pageDocuments) {
  2898. const descendantCount = await Page.recountDescendantCount(document._id);
  2899. await Page.findByIdAndUpdate(document._id, { descendantCount });
  2900. }
  2901. callback();
  2902. },
  2903. final(callback) {
  2904. callback();
  2905. },
  2906. });
  2907. await pipeline(pageCursor, batchStream, recountWriteStream);
  2908. }
  2909. // update descendantCount of all pages that are ancestors of a provided pageId by count
  2910. async updateDescendantCountOfAncestors(pageId: ObjectIdLike, inc: number, shouldIncludeTarget: boolean): Promise<void> {
  2911. const Page = this.crowi.model('Page');
  2912. const ancestors = await Page.findAncestorsUsingParentRecursively(pageId, shouldIncludeTarget);
  2913. const ancestorPageIds = ancestors.map(p => p._id);
  2914. await Page.incrementDescendantCountOfPageIds(ancestorPageIds, inc);
  2915. const updateDescCountData: UpdateDescCountRawData = Object.fromEntries(ancestors.map(p => [p._id.toString(), p.descendantCount + inc]));
  2916. this.emitUpdateDescCount(updateDescCountData);
  2917. }
  2918. private emitUpdateDescCount(data: UpdateDescCountRawData): void {
  2919. const socket = this.crowi.socketIoService.getDefaultSocket();
  2920. socket.emit(SocketEventName.UpdateDescCount, data);
  2921. }
  2922. /**
  2923. * Build the base aggregation pipeline for fillAncestors--- methods
  2924. * @param onlyMigratedAsExistingPages Determine whether to include non-migrated pages as existing pages. If a page exists,
  2925. * an empty page will not be created at that page's path.
  2926. */
  2927. private buildBasePipelineToCreateEmptyPages(paths: string[], onlyMigratedAsExistingPages = true, andFilter?): any[] {
  2928. const aggregationPipeline: any[] = [];
  2929. const Page = mongoose.model('Page') as unknown as PageModel;
  2930. // -- Filter by paths
  2931. aggregationPipeline.push({ $match: { path: { $in: paths } } });
  2932. // -- Normalized condition
  2933. if (onlyMigratedAsExistingPages) {
  2934. aggregationPipeline.push({
  2935. $match: {
  2936. $or: [
  2937. { grant: Page.GRANT_PUBLIC },
  2938. { parent: { $ne: null } },
  2939. { path: '/' },
  2940. ],
  2941. },
  2942. });
  2943. }
  2944. // -- Add custom pipeline
  2945. if (andFilter != null) {
  2946. aggregationPipeline.push({ $match: andFilter });
  2947. }
  2948. return aggregationPipeline;
  2949. }
  2950. private async buildPipelineToCreateEmptyPagesByUser(user, paths: string[], onlyMigratedAsExistingPages = true, andFilter?): Promise<any[]> {
  2951. const Page = mongoose.model('Page') as unknown as PageModel;
  2952. const pipeline = this.buildBasePipelineToCreateEmptyPages(paths, onlyMigratedAsExistingPages, andFilter);
  2953. const userGroups = user != null ? [
  2954. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2955. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  2956. ] : null;
  2957. const grantCondition = Page.generateGrantCondition(user, userGroups);
  2958. pipeline.push({ $match: grantCondition });
  2959. return pipeline;
  2960. }
  2961. private buildPipelineToCreateEmptyPagesBySystem(paths: string[]): any[] {
  2962. return this.buildBasePipelineToCreateEmptyPages(paths);
  2963. }
  2964. private async connectPageTree(path: string): Promise<void> {
  2965. const Page = mongoose.model('Page') as unknown as PageModel;
  2966. const { PageQueryBuilder } = Page;
  2967. const ancestorPaths = collectAncestorPaths(path);
  2968. // Find ancestors
  2969. const builder = new PageQueryBuilder(Page.find(), true);
  2970. builder.addConditionToFilterByApplicableAncestors(ancestorPaths); // avoid including not normalized pages
  2971. const ancestors = await builder
  2972. .addConditionToListByPathsArray(ancestorPaths)
  2973. .addConditionToSortPagesByDescPath()
  2974. .query
  2975. .exec();
  2976. // Update parent attrs
  2977. const ancestorsMap = new Map(); // Map<path, page>
  2978. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  2979. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  2980. const operations = nonRootAncestors.map((page) => {
  2981. const parentPath = pathlib.dirname(page.path);
  2982. return {
  2983. updateOne: {
  2984. filter: {
  2985. _id: page._id,
  2986. },
  2987. update: {
  2988. parent: ancestorsMap.get(parentPath)._id,
  2989. },
  2990. },
  2991. };
  2992. });
  2993. await Page.bulkWrite(operations);
  2994. }
  2995. /**
  2996. * Find parent or create parent if not exists.
  2997. * It also updates parent of ancestors
  2998. * @param path string
  2999. * @returns Promise<PageDocument>
  3000. */
  3001. async getParentAndFillAncestorsByUser(user, path: string): Promise<HydratedDocument<PageDocument>> {
  3002. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  3003. // Find parent
  3004. const parent = await Page.findParentByPath(path);
  3005. if (parent != null) {
  3006. return parent;
  3007. }
  3008. const ancestorPaths = collectAncestorPaths(path);
  3009. // Fill ancestors
  3010. const aggregationPipeline: any[] = await this.buildPipelineToCreateEmptyPagesByUser(user, ancestorPaths);
  3011. await Page.createEmptyPagesByPaths(ancestorPaths, aggregationPipeline);
  3012. // Connect ancestors
  3013. await this.connectPageTree(path);
  3014. // Return the created parent
  3015. const createdParent = await Page.findParentByPath(path);
  3016. if (createdParent == null) {
  3017. throw Error('Failed to find the created parent by getParentAndFillAncestorsByUser');
  3018. }
  3019. return createdParent;
  3020. }
  3021. async getParentAndFillAncestorsBySystem(path: string): Promise<HydratedDocument<PageDocument>> {
  3022. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  3023. // Find parent
  3024. const parent = await Page.findParentByPath(path);
  3025. if (parent != null) {
  3026. return parent;
  3027. }
  3028. // Fill ancestors
  3029. const ancestorPaths = collectAncestorPaths(path);
  3030. const aggregationPipeline: any[] = this.buildPipelineToCreateEmptyPagesBySystem(ancestorPaths);
  3031. await Page.createEmptyPagesByPaths(ancestorPaths, aggregationPipeline);
  3032. // Connect ancestors
  3033. await this.connectPageTree(path);
  3034. // Return the created parent
  3035. const createdParent = await Page.findParentByPath(path);
  3036. if (createdParent == null) {
  3037. throw Error('Failed to find the created parent by getParentAndFillAncestorsByUser');
  3038. }
  3039. return createdParent;
  3040. }
  3041. // --------- Create ---------
  3042. private async preparePageDocumentToCreate(path: string, shouldNew: boolean): Promise<HydratedDocument<PageDocument>> {
  3043. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  3044. const emptyPage = await Page.findOne({ path, isEmpty: true });
  3045. // Use empty page if exists, if not, create a new page
  3046. let page: HydratedDocument<PageDocument>;
  3047. if (shouldNew) {
  3048. page = new Page();
  3049. }
  3050. else if (emptyPage != null) {
  3051. page = emptyPage;
  3052. const descendantCount = await Page.recountDescendantCount(page._id);
  3053. page.descendantCount = descendantCount;
  3054. page.isEmpty = false;
  3055. }
  3056. else {
  3057. page = new Page();
  3058. }
  3059. return page;
  3060. }
  3061. private setFieldExceptForGrantRevisionParent(
  3062. pageDocument: PageDocument,
  3063. path: string,
  3064. user?,
  3065. ): void {
  3066. const Page = mongoose.model('Page') as unknown as PageModel;
  3067. pageDocument.path = path;
  3068. pageDocument.creator = user;
  3069. pageDocument.lastUpdateUser = user;
  3070. pageDocument.status = Page.STATUS_PUBLISHED;
  3071. }
  3072. private async validateAppliedScope(user, grant, grantUserGroupIds: IGrantedGroup[]) {
  3073. if (grant === PageGrant.GRANT_USER_GROUP && grantUserGroupIds == null) {
  3074. throw new Error('grantUserGroupIds is not specified');
  3075. }
  3076. if (grant === PageGrant.GRANT_USER_GROUP) {
  3077. const { grantedUserGroups: grantedUserGroupIds, grantedExternalUserGroups: grantedExternalUserGroupIds } = divideByType(grantUserGroupIds);
  3078. const count = await UserGroupRelation.countByGroupIdsAndUser(grantedUserGroupIds, user)
  3079. + await ExternalUserGroupRelation.countByGroupIdsAndUser(grantedExternalUserGroupIds, user);
  3080. if (count === 0) {
  3081. throw new Error('no relations were exist for group and user.');
  3082. }
  3083. }
  3084. }
  3085. private async canProcessCreate(
  3086. path: string,
  3087. grantData: {
  3088. grant?: PageGrant,
  3089. grantUserIds?: ObjectIdLike[],
  3090. grantUserGroupIds?: IGrantedGroup[],
  3091. },
  3092. shouldValidateGrant: boolean,
  3093. user?,
  3094. options?: IOptionsForCreate,
  3095. ): Promise<boolean> {
  3096. const Page = mongoose.model('Page') as unknown as PageModel;
  3097. // Operatability validation
  3098. const canOperate = await this.crowi.pageOperationService.canOperate(false, null, path);
  3099. if (!canOperate) {
  3100. logger.error(`Cannot operate create to path "${path}" right now.`);
  3101. return false;
  3102. }
  3103. // Existance validation
  3104. const isExist = (await Page.count({ path, isEmpty: false })) > 0; // not validate empty page
  3105. if (isExist) {
  3106. logger.error('Cannot create new page to existed path');
  3107. return false;
  3108. }
  3109. // UserGroup & Owner validation
  3110. const { grant, grantUserIds, grantUserGroupIds } = grantData;
  3111. if (shouldValidateGrant) {
  3112. if (user == null) {
  3113. throw Error('user is required to validate grant');
  3114. }
  3115. let isGrantNormalized = false;
  3116. try {
  3117. // It must check descendants as well if emptyTarget is not null
  3118. const isEmptyPageAlreadyExist = await Page.count({ path, isEmpty: true }) > 0;
  3119. const shouldCheckDescendants = isEmptyPageAlreadyExist && !options?.overwriteScopesOfDescendants;
  3120. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, path, grant, grantUserIds, grantUserGroupIds, shouldCheckDescendants);
  3121. }
  3122. catch (err) {
  3123. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  3124. throw err;
  3125. }
  3126. if (!isGrantNormalized) {
  3127. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  3128. }
  3129. if (options?.overwriteScopesOfDescendants) {
  3130. const updateGrantInfo = await this.pageGrantService.generateUpdateGrantInfoToOverwriteDescendants(user, grant, options.grantUserGroupIds);
  3131. const canOverwriteDescendants = await this.pageGrantService.canOverwriteDescendants(path, user, updateGrantInfo);
  3132. if (!canOverwriteDescendants) {
  3133. throw Error('Cannot overwrite scopes of descendants.');
  3134. }
  3135. }
  3136. }
  3137. return true;
  3138. }
  3139. /**
  3140. * Create a page
  3141. * Set options.isSynchronously to true to await all process when you want to run this method multiple times at short intervals.
  3142. */
  3143. async create(_path: string, body: string, user: HasObjectId, options: IOptionsForCreate = {}): Promise<HydratedDocument<PageDocument>> {
  3144. // Switch method
  3145. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  3146. if (!isV5Compatible) {
  3147. return this.createV4(_path, body, user, options);
  3148. }
  3149. // Values
  3150. const path: string = generalXssFilter.process(_path); // sanitize path
  3151. // Retrieve closest ancestor document
  3152. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  3153. const closestAncestor = await Page.findNonEmptyClosestAncestor(path);
  3154. // Determine grantData
  3155. const grant = options.grant ?? closestAncestor?.grant ?? PageGrant.GRANT_PUBLIC;
  3156. const grantUserIds = grant === PageGrant.GRANT_OWNER ? [user._id] : undefined;
  3157. const getGrantedGroupsFromClosestAncestor = async() => {
  3158. if (closestAncestor == null) return undefined;
  3159. if (options.onlyInheritUserRelatedGrantedGroups) {
  3160. return this.pageGrantService.getUserRelatedGrantedGroups(closestAncestor, user);
  3161. }
  3162. return closestAncestor.grantedGroups;
  3163. };
  3164. const grantUserGroupIds = options.grantUserGroupIds ?? await getGrantedGroupsFromClosestAncestor();
  3165. const grantData = {
  3166. grant,
  3167. grantUserIds,
  3168. grantUserGroupIds,
  3169. };
  3170. const isGrantRestricted = grant === PageGrant.GRANT_RESTRICTED;
  3171. // Validate
  3172. const shouldValidateGrant = !isGrantRestricted;
  3173. const canProcessCreate = await this.canProcessCreate(path, grantData, shouldValidateGrant, user, options);
  3174. if (!canProcessCreate) {
  3175. throw Error('Cannot process create');
  3176. }
  3177. // Prepare a page document
  3178. const shouldNew = isGrantRestricted;
  3179. const page = await this.preparePageDocumentToCreate(path, shouldNew);
  3180. // Set field
  3181. this.setFieldExceptForGrantRevisionParent(page, path, user);
  3182. // Apply scope
  3183. page.applyScope(user, grant, grantUserGroupIds);
  3184. // Set parent
  3185. if (isTopPage(path) || isGrantRestricted) { // set parent to null when GRANT_RESTRICTED
  3186. page.parent = null;
  3187. }
  3188. else {
  3189. const parent = await this.getParentAndFillAncestorsByUser(user, path);
  3190. page.parent = parent._id;
  3191. }
  3192. // Make WIP
  3193. if (options.wip) {
  3194. const hasChildren = await Page.exists({ parent: page._id });
  3195. page.makeWip(hasChildren != null); // disableTtl = hasChildren != null
  3196. }
  3197. // Save
  3198. let savedPage = await page.save();
  3199. // Create revision
  3200. const newRevision = Revision.prepareRevision(savedPage, body, null, user, options.origin);
  3201. savedPage = await pushRevision(savedPage, newRevision, user);
  3202. await savedPage.populateDataToShowRevision();
  3203. // Emit create event
  3204. this.pageEvent.emit('create', savedPage, user);
  3205. // Directly run sub operation for now since it might be complex to handle main operation for creating pages -- Taichi Masuyama 2022.11.08
  3206. let pageOp;
  3207. try {
  3208. pageOp = await PageOperation.create({
  3209. actionType: PageActionType.Create,
  3210. actionStage: PageActionStage.Sub,
  3211. page: savedPage,
  3212. user,
  3213. fromPath: path,
  3214. options,
  3215. });
  3216. }
  3217. catch (err) {
  3218. logger.error('Failed to create PageOperation document.', err);
  3219. throw err;
  3220. }
  3221. this.createSubOperation(savedPage, user, options, pageOp._id);
  3222. return savedPage;
  3223. }
  3224. /**
  3225. * Used to run sub operation in create method
  3226. */
  3227. async createSubOperation(page, user, options: IOptionsForCreate, pageOpId: ObjectIdLike): Promise<void> {
  3228. await this.disableAncestorPagesTtl(page.path);
  3229. // Update descendantCount
  3230. await this.updateDescendantCountOfAncestors(page._id, 1, false);
  3231. // Delete PageRedirect if exists
  3232. try {
  3233. await PageRedirect.deleteOne({ fromPath: page.path });
  3234. logger.warn(`Deleted page redirect after creating a new page at path "${page.path}".`);
  3235. }
  3236. catch (err) {
  3237. // no throw
  3238. logger.error('Failed to delete PageRedirect');
  3239. }
  3240. // update scopes for descendants
  3241. if (options.overwriteScopesOfDescendants) {
  3242. await this.applyScopesToDescendantsWithStream(page, user);
  3243. }
  3244. await PageOperation.findByIdAndDelete(pageOpId);
  3245. }
  3246. /**
  3247. * V4 compatible create method
  3248. */
  3249. private async createV4(path, body, user, options: any = {}) {
  3250. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  3251. const format = options.format || 'markdown';
  3252. const grantUserGroupIds = options.grantUserGroupIds || null;
  3253. const expandContentWidth = this.crowi.configManager.getConfig('crowi', 'customize:isContainerFluid');
  3254. // sanitize path
  3255. path = generalXssFilter.process(path); // eslint-disable-line no-param-reassign
  3256. let grant = options.grant;
  3257. // force public
  3258. if (isTopPage(path)) {
  3259. grant = PageGrant.GRANT_PUBLIC;
  3260. }
  3261. const isExist = await Page.count({ path });
  3262. if (isExist) {
  3263. throw new Error('Cannot create new page to existed path');
  3264. }
  3265. const page = new Page();
  3266. page.path = path;
  3267. page.creator = user;
  3268. page.lastUpdateUser = user;
  3269. page.status = PageStatus.STATUS_PUBLISHED;
  3270. if (expandContentWidth != null) {
  3271. page.expandContentWidth = expandContentWidth;
  3272. }
  3273. await this.validateAppliedScope(user, grant, grantUserGroupIds);
  3274. page.applyScope(user, grant, grantUserGroupIds);
  3275. let savedPage = await page.save();
  3276. const newRevision = Revision.prepareRevision(savedPage, body, null, user, undefined, { format });
  3277. savedPage = await pushRevision(savedPage, newRevision, user);
  3278. await savedPage.populateDataToShowRevision();
  3279. this.pageEvent.emit('create', savedPage, user);
  3280. // update scopes for descendants
  3281. if (options.overwriteScopesOfDescendants) {
  3282. this.applyScopesToDescendantsWithStream(savedPage, user, true);
  3283. }
  3284. return savedPage;
  3285. }
  3286. private async canProcessForceCreateBySystem(
  3287. path: string,
  3288. grantData: {
  3289. grant: PageGrant,
  3290. grantUserIds?: ObjectIdLike[],
  3291. grantUserGroupId?: ObjectIdLike,
  3292. },
  3293. ): Promise<boolean> {
  3294. return this.canProcessCreate(path, grantData, false);
  3295. }
  3296. private async disableAncestorPagesTtl(path: string): Promise<void> {
  3297. const Page = mongoose.model<PageDocument, PageModel>('Page');
  3298. const ancestorPaths = collectAncestorPaths(path);
  3299. const ancestorPageIds = await Page.aggregate([
  3300. { $match: { path: { $in: ancestorPaths, $nin: ['/'] }, isEmpty: false } },
  3301. { $project: { _id: 1 } },
  3302. ]);
  3303. await Page.updateMany({ _id: { $in: ancestorPageIds } }, { $unset: { ttlTimestamp: true } });
  3304. }
  3305. /**
  3306. * @private
  3307. * This method receives the same arguments as the PageService.create method does except for the added type '{ grantUserIds?: ObjectIdLike[] }'.
  3308. * This additional value is used to determine the grantedUser of the page to be created by system.
  3309. * This method must not run isGrantNormalized method to validate grant. **If necessary, run it before use this method.**
  3310. * -- Reason 1: This is because it is not expected to use this method when the grant validation is required.
  3311. * -- Reason 2: This is because it is not expected to use this method when the program cannot determine the operator.
  3312. */
  3313. async forceCreateBySystem(path: string, body: string, options: IOptionsForCreate & { grantUserIds?: ObjectIdLike[] }): Promise<PageDocument> {
  3314. const Page = mongoose.model('Page') as unknown as PageModel;
  3315. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  3316. if (!isV5Compatible) {
  3317. throw Error('This method is available only when v5 compatible');
  3318. }
  3319. // Values
  3320. // eslint-disable-next-line no-param-reassign
  3321. path = generalXssFilter.process(path); // sanitize path
  3322. const {
  3323. grantUserGroupIds, grantUserIds,
  3324. } = options;
  3325. const grant = isTopPage(path) ? Page.GRANT_PUBLIC : options.grant;
  3326. const isGrantRestricted = grant === Page.GRANT_RESTRICTED;
  3327. const isGrantOwner = grant === Page.GRANT_OWNER;
  3328. const grantData = {
  3329. grant,
  3330. grantUserIds: isGrantOwner ? grantUserIds : undefined,
  3331. grantUserGroupIds,
  3332. };
  3333. // Validate
  3334. if (isGrantOwner && grantUserIds?.length !== 1) {
  3335. throw Error('grantedUser must exist when grant is GRANT_OWNER');
  3336. }
  3337. const canProcessForceCreateBySystem = await this.canProcessForceCreateBySystem(path, grantData);
  3338. if (!canProcessForceCreateBySystem) {
  3339. throw Error('Cannot process forceCreateBySystem');
  3340. }
  3341. // Prepare a page document
  3342. const shouldNew = isGrantRestricted;
  3343. const page = await this.preparePageDocumentToCreate(path, shouldNew);
  3344. // Set field
  3345. this.setFieldExceptForGrantRevisionParent(page, path);
  3346. // Apply scope
  3347. page.applyScope({ _id: grantUserIds?.[0] }, grant, grantUserGroupIds);
  3348. // Set parent
  3349. if (isTopPage(path) || isGrantRestricted) { // set parent to null when GRANT_RESTRICTED
  3350. page.parent = null;
  3351. }
  3352. else {
  3353. const parent = await this.getParentAndFillAncestorsBySystem(path);
  3354. page.parent = parent._id;
  3355. }
  3356. // Save
  3357. let savedPage = await page.save();
  3358. // Create revision
  3359. const dummyUser: HasObjectId = { _id: new mongoose.Types.ObjectId().toString() };
  3360. const newRevision = Revision.prepareRevision(savedPage, body, null, dummyUser);
  3361. savedPage = await pushRevision(savedPage, newRevision, dummyUser);
  3362. if (savedPage._id == null) {
  3363. throw new Error('Something went wrong: _id is null');
  3364. }
  3365. // Update descendantCount
  3366. await this.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  3367. // Emit create event
  3368. this.pageEvent.emit('create', savedPage, dummyUser);
  3369. return savedPage;
  3370. }
  3371. private shouldUseUpdatePageV4(grant: number, isV5Compatible: boolean, isOnTree: boolean): boolean {
  3372. const isRestricted = grant === PageGrant.GRANT_RESTRICTED;
  3373. return !isRestricted && (!isV5Compatible || !isOnTree);
  3374. }
  3375. /**
  3376. * A wrapper method of updatePage for updating grant only.
  3377. * @param {PageDocument} page
  3378. * @param {UserDocument} user
  3379. * @param options
  3380. */
  3381. async updateGrant(page, user, grantData: {grant: PageGrant, userRelatedGrantedGroups: IGrantedGroup[]}): Promise<PageDocument> {
  3382. const { grant, userRelatedGrantedGroups } = grantData;
  3383. const options: IOptionsForUpdate = {
  3384. grant,
  3385. userRelatedGrantUserGroupIds: userRelatedGrantedGroups,
  3386. };
  3387. return this.updatePage(page, null, null, user, options);
  3388. }
  3389. async updatePageSubOperation(page, user, exPage, options: IOptionsForUpdate, pageOpId: ObjectIdLike): Promise<void> {
  3390. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  3391. const currentPage = page;
  3392. const exParent = exPage.parent;
  3393. const wasOnTree = exPage.parent != null || isTopPage(exPage.path);
  3394. const shouldBeOnTree = currentPage.grant !== PageGrant.GRANT_RESTRICTED;
  3395. const isChildrenExist = await Page.count({ path: new RegExp(`^${escapeStringRegexp(addTrailingSlash(currentPage.path))}`), parent: { $ne: null } });
  3396. // 1. Update descendantCount
  3397. const shouldPlusDescCount = !wasOnTree && shouldBeOnTree;
  3398. const shouldMinusDescCount = wasOnTree && !shouldBeOnTree;
  3399. if (shouldPlusDescCount) {
  3400. await this.updateDescendantCountOfAncestors(currentPage._id, 1, false);
  3401. const newDescendantCount = await Page.recountDescendantCount(currentPage._id);
  3402. await Page.updateOne({ _id: currentPage._id }, { descendantCount: newDescendantCount });
  3403. }
  3404. else if (shouldMinusDescCount) {
  3405. // Update from parent. Parent is null if currentPage.grant is RESTRECTED.
  3406. if (currentPage.grant === PageGrant.GRANT_RESTRICTED) {
  3407. await this.updateDescendantCountOfAncestors(exParent, -1, true);
  3408. }
  3409. }
  3410. // 2. Delete unnecessary empty pages
  3411. const shouldRemoveLeafEmpPages = wasOnTree && !isChildrenExist;
  3412. if (shouldRemoveLeafEmpPages) {
  3413. await Page.removeLeafEmptyPagesRecursively(exParent);
  3414. }
  3415. // 3. Update scopes for descendants
  3416. if (options.overwriteScopesOfDescendants && shouldBeOnTree) {
  3417. await this.applyScopesToDescendantsWithStream(currentPage, user);
  3418. }
  3419. await PageOperation.findByIdAndDelete(pageOpId);
  3420. }
  3421. /**
  3422. * Get the new GrantedGroups for the page going through an update operation.
  3423. * 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.
  3424. * @param userRelatedGrantedGroups The groups specified by the operator
  3425. * @param page The page going through an update operation
  3426. * @param user The operator
  3427. * @returns The new GrantedGroups array to be set to the page
  3428. */
  3429. async getNewGrantedGroups(userRelatedGrantedGroups: IGrantedGroup[], page: PageDocument, user): Promise<IGrantedGroup[]> {
  3430. const userRelatedGroups = await this.pageGrantService.getUserRelatedGroups(user);
  3431. return this.getNewGrantedGroupsSyncronously(userRelatedGroups, userRelatedGrantedGroups, page);
  3432. }
  3433. /**
  3434. * Use when you do not want to use getNewGrantedGroups with async/await (e.g inside loops that process a large amount of pages)
  3435. * Specification of userRelatedGroups is necessary to avoid the cost of fetching userRelatedGroups from DB every time.
  3436. */
  3437. getNewGrantedGroupsSyncronously(userRelatedGroups: PopulatedGrantedGroup[], userRelatedGrantedGroups: IGrantedGroup[], page: PageDocument): IGrantedGroup[] {
  3438. const previousGrantedGroups = page.grantedGroups;
  3439. const userRelatedPreviousGrantedGroups = this.pageGrantService.getUserRelatedGrantedGroupsSyncronously(
  3440. userRelatedGroups, page,
  3441. ).map(g => getIdForRef(g.item));
  3442. const userUnrelatedPreviousGrantedGroups = previousGrantedGroups.filter(g => !userRelatedPreviousGrantedGroups.includes(getIdForRef(g.item)));
  3443. return [...userUnrelatedPreviousGrantedGroups, ...userRelatedGrantedGroups];
  3444. }
  3445. async updatePage(
  3446. pageData: HydratedDocument<PageDocument>,
  3447. body: string | null,
  3448. previousBody: string | null,
  3449. user: IUserHasId,
  3450. options: IOptionsForUpdate = {},
  3451. ): Promise<HydratedDocument<PageDocument>> {
  3452. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  3453. const wasOnTree = pageData.parent != null || isTopPage(pageData.path);
  3454. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  3455. const shouldUseV4Process = this.shouldUseUpdatePageV4(pageData.grant, isV5Compatible, wasOnTree);
  3456. if (shouldUseV4Process) {
  3457. // v4 compatible process
  3458. return this.updatePageV4(pageData, body, previousBody, user, options);
  3459. }
  3460. // Clone page document
  3461. const clonedPageData = Page.hydrate(pageData.toObject());
  3462. const newPageData = pageData;
  3463. // Once updated it's exempt from automatic deletion
  3464. if (options.wip == null) {
  3465. newPageData.ttlTimestamp = undefined;
  3466. }
  3467. else if (options.wip) {
  3468. newPageData.unpublish();
  3469. }
  3470. else {
  3471. newPageData.publish();
  3472. }
  3473. // use the previous data if absent
  3474. const grant = options.grant ?? clonedPageData.grant;
  3475. const grantUserGroupIds = options.userRelatedGrantUserGroupIds != null
  3476. ? (await this.getNewGrantedGroups(options.userRelatedGrantUserGroupIds, clonedPageData, user))
  3477. : clonedPageData.grantedGroups;
  3478. const grantedUserIds = clonedPageData.grantedUserIds || [user._id];
  3479. const shouldBeOnTree = grant !== PageGrant.GRANT_RESTRICTED;
  3480. const isChildrenExist = await Page.count({ path: new RegExp(`^${escapeStringRegexp(addTrailingSlash(clonedPageData.path))}`), parent: { $ne: null } });
  3481. const isGrantChangeable = await this.pageGrantService.validateGrantChange(user, pageData.grantedGroups, grant, grantUserGroupIds);
  3482. if (!isGrantChangeable) {
  3483. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  3484. }
  3485. if (shouldBeOnTree) {
  3486. let isGrantNormalized = false;
  3487. try {
  3488. const shouldCheckDescendants = !options.overwriteScopesOfDescendants;
  3489. // eslint-disable-next-line max-len
  3490. isGrantNormalized = await this.pageGrantService.isGrantNormalized(user, clonedPageData.path, grant, grantedUserIds, grantUserGroupIds, shouldCheckDescendants, false);
  3491. }
  3492. catch (err) {
  3493. logger.error(`Failed to validate grant of page at "${clonedPageData.path}" of grant ${grant}:`, err);
  3494. throw err;
  3495. }
  3496. if (!isGrantNormalized) {
  3497. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  3498. }
  3499. if (options.overwriteScopesOfDescendants) {
  3500. const updateGrantInfo = await this.pageGrantService.generateUpdateGrantInfoToOverwriteDescendants(user, grant, options.userRelatedGrantUserGroupIds);
  3501. const canOverwriteDescendants = await this.pageGrantService.canOverwriteDescendants(clonedPageData.path, user, updateGrantInfo);
  3502. if (!canOverwriteDescendants) {
  3503. throw Error('Cannot overwrite scopes of descendants.');
  3504. }
  3505. }
  3506. if (!wasOnTree) {
  3507. const newParent = await this.getParentAndFillAncestorsByUser(user, newPageData.path);
  3508. newPageData.parent = newParent._id;
  3509. }
  3510. }
  3511. else {
  3512. if (wasOnTree && isChildrenExist) {
  3513. // Update children's parent with new parent
  3514. const newParentForChildren = await Page.createEmptyPage(clonedPageData.path, clonedPageData.parent, clonedPageData.descendantCount);
  3515. await Page.updateMany(
  3516. { parent: clonedPageData._id },
  3517. { parent: newParentForChildren._id },
  3518. );
  3519. }
  3520. newPageData.parent = null;
  3521. newPageData.descendantCount = 0;
  3522. }
  3523. newPageData.applyScope(user, grant, grantUserGroupIds);
  3524. // update existing page
  3525. let savedPage = await newPageData.save();
  3526. // Update body
  3527. const isBodyPresent = body != null;
  3528. const shouldUpdateBody = isBodyPresent;
  3529. if (shouldUpdateBody) {
  3530. const origin = options.origin;
  3531. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user, origin);
  3532. savedPage = await pushRevision(savedPage, newRevision, user);
  3533. await savedPage.populateDataToShowRevision();
  3534. }
  3535. this.pageEvent.emit('update', savedPage, user);
  3536. // Update ex children's parent
  3537. if (!wasOnTree && shouldBeOnTree) {
  3538. const emptyPageAtSamePath = await Page.findOne({ path: clonedPageData.path, isEmpty: true }); // this page is necessary to find children
  3539. if (isChildrenExist) {
  3540. if (emptyPageAtSamePath != null) {
  3541. // Update children's parent with new parent
  3542. await Page.updateMany(
  3543. { parent: emptyPageAtSamePath._id },
  3544. { parent: savedPage._id },
  3545. );
  3546. }
  3547. }
  3548. await Page.findOneAndDelete({ path: clonedPageData.path, isEmpty: true }); // delete here
  3549. }
  3550. // Directly run sub operation for now since it might be complex to handle main operation for updating pages -- Taichi Masuyama 2022.11.08
  3551. let pageOp;
  3552. try {
  3553. pageOp = await PageOperation.create({
  3554. actionType: PageActionType.Update,
  3555. actionStage: PageActionStage.Sub,
  3556. page: savedPage,
  3557. exPage: clonedPageData,
  3558. user,
  3559. fromPath: clonedPageData.path,
  3560. options,
  3561. });
  3562. }
  3563. catch (err) {
  3564. logger.error('Failed to create PageOperation document.', err);
  3565. throw err;
  3566. }
  3567. this.updatePageSubOperation(savedPage, user, clonedPageData, options, pageOp._id);
  3568. return savedPage;
  3569. }
  3570. async updatePageV4(
  3571. pageData: HydratedDocument<PageDocument>, body, previousBody, user, options: IOptionsForUpdate = {},
  3572. ): Promise<HydratedDocument<PageDocument>> {
  3573. // use the previous data if absent
  3574. const grant = options.grant || pageData.grant;
  3575. const grantUserGroupIds = options.userRelatedGrantUserGroupIds != null
  3576. ? (await this.getNewGrantedGroups(options.userRelatedGrantUserGroupIds, pageData, user))
  3577. : pageData.grantedGroups;
  3578. // validate multiple group grant before save using pageData and options
  3579. await this.pageGrantService.validateGrantChange(user, pageData.grantedGroups, grant, grantUserGroupIds);
  3580. await this.validateAppliedScope(user, grant, grantUserGroupIds);
  3581. pageData.applyScope(user, grant, grantUserGroupIds);
  3582. // update existing page
  3583. let savedPage = await pageData.save();
  3584. // Update revision
  3585. const isBodyPresent = body != null && previousBody != null;
  3586. const shouldUpdateBody = isBodyPresent;
  3587. if (shouldUpdateBody) {
  3588. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  3589. savedPage = await pushRevision(savedPage, newRevision, user);
  3590. await savedPage.populateDataToShowRevision();
  3591. }
  3592. // update scopes for descendants
  3593. if (options.overwriteScopesOfDescendants) {
  3594. this.applyScopesToDescendantsWithStream(savedPage, user, true);
  3595. }
  3596. this.pageEvent.emit('update', savedPage, user);
  3597. return savedPage;
  3598. }
  3599. /*
  3600. * Find all children by parent's path or id. Using id should be prioritized
  3601. */
  3602. async findChildrenByParentPathOrIdAndViewer(
  3603. parentPathOrId: string,
  3604. user,
  3605. userGroups = null,
  3606. showPagesRestrictedByOwner = false,
  3607. showPagesRestrictedByGroup = false,
  3608. ): Promise<(HydratedDocument<PageDocument> & { processData?: IPageOperationProcessData })[]> {
  3609. const Page = mongoose.model<HydratedDocument<PageDocument>, PageModel>('Page');
  3610. let queryBuilder: PageQueryBuilder;
  3611. if (hasSlash(parentPathOrId)) {
  3612. const path = parentPathOrId;
  3613. const regexp = generateChildrenRegExp(path);
  3614. queryBuilder = new PageQueryBuilder(Page.find({ path: { $regex: regexp } }), true);
  3615. }
  3616. else {
  3617. const parentId = parentPathOrId;
  3618. // Use $eq for user-controlled sources. see: https://codeql.github.com/codeql-query-help/javascript/js-sql-injection/#recommendation
  3619. queryBuilder = new PageQueryBuilder(Page.find({ parent: { $eq: parentId } } as any), true); // TODO: improve type
  3620. }
  3621. await queryBuilder.addViewerCondition(user, userGroups, undefined, showPagesRestrictedByOwner, showPagesRestrictedByGroup);
  3622. const pages: HydratedDocument<PageDocument>[] = await queryBuilder
  3623. .addConditionToSortPagesByAscPath()
  3624. .query
  3625. .lean()
  3626. .exec();
  3627. await this.injectProcessDataIntoPagesByActionTypes(pages, [PageActionType.Rename]);
  3628. return pages;
  3629. }
  3630. /**
  3631. * Find all pages in trash page
  3632. */
  3633. async findAllTrashPages(user: IUserHasId, userGroups = null): Promise<PageDocument[]> {
  3634. const Page = mongoose.model('Page') as unknown as PageModel;
  3635. // https://regex101.com/r/KYZWls/1
  3636. // ex. /trash/.*
  3637. const regexp = new RegExp('^/trash\\/.*$');
  3638. const queryBuilder = new PageQueryBuilder(Page.find({ path: { $regex: regexp } }), true);
  3639. await queryBuilder.addViewerCondition(user, userGroups);
  3640. const pages = await queryBuilder
  3641. .addConditionToSortPagesByAscPath()
  3642. .query
  3643. .lean()
  3644. .exec();
  3645. await this.injectProcessDataIntoPagesByActionTypes(pages, [PageActionType.Rename]);
  3646. return pages;
  3647. }
  3648. async findAncestorsChildrenByPathAndViewer(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  3649. const Page = mongoose.model('Page') as unknown as PageModel;
  3650. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  3651. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  3652. // get pages at once
  3653. const queryBuilder = new PageQueryBuilder(Page.find({ path: { $in: regexps } }), true);
  3654. await queryBuilder.addViewerCondition(user, userGroups);
  3655. const pages = await queryBuilder
  3656. .addConditionAsOnTree()
  3657. .addConditionToMinimizeDataForRendering()
  3658. .addConditionToSortPagesByAscPath()
  3659. .query
  3660. .lean()
  3661. .exec();
  3662. await this.injectProcessDataIntoPagesByActionTypes(pages, [PageActionType.Rename]);
  3663. /*
  3664. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  3665. */
  3666. const pathToChildren: Record<string, PageDocument[]> = {};
  3667. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  3668. sortedPaths.every((path) => {
  3669. const children = pages.filter(page => pathlib.dirname(page.path) === path);
  3670. if (children.length === 0) {
  3671. return false; // break when children do not exist
  3672. }
  3673. pathToChildren[path] = children;
  3674. return true;
  3675. });
  3676. return pathToChildren;
  3677. }
  3678. /**
  3679. * Inject processData into page docuements
  3680. * The processData is a combination of actionType as a key and information on whether the action is processable as a value.
  3681. */
  3682. private async injectProcessDataIntoPagesByActionTypes(
  3683. pages: (HydratedDocument<PageDocument> & { processData?: IPageOperationProcessData })[],
  3684. actionTypes: PageActionType[],
  3685. ): Promise<void> {
  3686. const pageOperations = await PageOperation.find({ actionType: { $in: actionTypes } });
  3687. if (pageOperations == null || pageOperations.length === 0) {
  3688. return;
  3689. }
  3690. const processInfo: IPageOperationProcessInfo = this.crowi.pageOperationService.generateProcessInfo(pageOperations);
  3691. const operatingPageIds: string[] = Object.keys(processInfo);
  3692. // inject processData into pages
  3693. pages.forEach((page) => {
  3694. const pageId = page._id.toString();
  3695. if (operatingPageIds.includes(pageId)) {
  3696. const processData: IPageOperationProcessData = processInfo[pageId];
  3697. page.processData = processData;
  3698. }
  3699. });
  3700. }
  3701. async getYjsData(pageId: string): Promise<CurrentPageYjsData> {
  3702. const yjsService = getYjsService();
  3703. const currentYdoc = yjsService.getCurrentYdoc(pageId);
  3704. const ydocStatus = await yjsService.getYDocStatus(pageId);
  3705. const hasYdocsNewerThanLatestRevision = ydocStatus === YDocStatus.DRAFT;
  3706. return {
  3707. hasYdocsNewerThanLatestRevision,
  3708. awarenessStateSize: currentYdoc?.awareness.states.size,
  3709. };
  3710. }
  3711. async createTtlIndex(): Promise<void> {
  3712. const wipPageExpirationSeconds = configManager.getConfig('crowi', 'app:wipPageExpirationSeconds') ?? 172800;
  3713. const collection = mongoose.connection.collection('pages');
  3714. try {
  3715. const targetField = 'ttlTimestamp_1';
  3716. const indexes = await collection.indexes();
  3717. const foundTargetField = indexes.find(i => i.name === targetField);
  3718. const isNotSpec = foundTargetField?.expireAfterSeconds == null || foundTargetField?.expireAfterSeconds !== wipPageExpirationSeconds;
  3719. const shoudDropIndex = foundTargetField != null && isNotSpec;
  3720. const shoudCreateIndex = foundTargetField == null || shoudDropIndex;
  3721. if (shoudDropIndex) {
  3722. await collection.dropIndex(targetField);
  3723. }
  3724. if (shoudCreateIndex) {
  3725. await collection.createIndex({ ttlTimestamp: 1 }, { expireAfterSeconds: wipPageExpirationSeconds });
  3726. }
  3727. }
  3728. catch (err) {
  3729. logger.error('Failed to create TTL Index', err);
  3730. throw err;
  3731. }
  3732. }
  3733. }
  3734. export default PageService;