page.ts 112 KB

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