index.ts 145 KB

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