index.ts 153 KB

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