page.ts 136 KB

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