page.ts 111 KB

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