page.ts 135 KB

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