page.ts 144 KB

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