page.ts 115 KB

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