index.ts 152 KB

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