page.ts 117 KB

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