page.ts 140 KB

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