page.ts 140 KB

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