page.ts 142 KB

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