page.ts 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316
  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;
  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.getParentAndFillAncestors(newPagePath, user);
  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.getParentAndFillAncestors(newPagePath, user);
  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. // TODO: implement this method
  1443. async deleteCompletelySystematically() {
  1444. return;
  1445. }
  1446. async deleteCompletelyRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike): Promise<void> {
  1447. await this.deleteCompletelyDescendantsWithStream(page, user, options, false);
  1448. await PageOperation.findByIdAndDelete(pageOpId);
  1449. // no sub operation available
  1450. }
  1451. private async deleteCompletelyV4(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  1452. const ids = [page._id];
  1453. const paths = [page.path];
  1454. logger.debug('Deleting completely', paths);
  1455. await this.deleteCompletelyOperation(ids, paths);
  1456. if (isRecursively) {
  1457. this.deleteCompletelyDescendantsWithStream(page, user, options);
  1458. }
  1459. if (!page.isEmpty && !preventEmitting) {
  1460. this.pageEvent.emit('deleteCompletely', page, user);
  1461. }
  1462. return;
  1463. }
  1464. async emptyTrashPage(user, options = {}) {
  1465. return this.deleteCompletelyDescendantsWithStream({ path: '/trash' }, user, options);
  1466. }
  1467. /**
  1468. * Create delete completely stream
  1469. */
  1470. private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true): Promise<number> {
  1471. let readStream;
  1472. if (shouldUseV4Process) { // pages don't have parents
  1473. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1474. }
  1475. else {
  1476. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1477. readStream = await factory.generateReadable();
  1478. }
  1479. let count = 0;
  1480. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1481. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  1482. const writeStream = new Writable({
  1483. objectMode: true,
  1484. async write(batch, encoding, callback) {
  1485. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1486. try {
  1487. count += batch.length;
  1488. await deleteMultipleCompletely(batch, user, options);
  1489. logger.debug(`Adding pages progressing: (count=${count})`);
  1490. }
  1491. catch (err) {
  1492. logger.error('addAllPages error on add anyway: ', err);
  1493. }
  1494. callback();
  1495. },
  1496. final(callback) {
  1497. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1498. callback();
  1499. },
  1500. });
  1501. readStream
  1502. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1503. .pipe(writeStream);
  1504. await streamToPromise(writeStream);
  1505. return nDeletedNonEmptyPages;
  1506. }
  1507. // no need to separate Main Sub since it is devided into single page operations
  1508. async deleteMultiplePages(pagesToDelete, user, options): Promise<void> {
  1509. const { isRecursively, isCompletely } = options;
  1510. if (pagesToDelete.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1511. throw Error(`The maximum number of pages is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1512. }
  1513. // omit duplicate paths if isRecursively true, omit empty pages if isRecursively false
  1514. const pages = isRecursively ? omitDuplicateAreaPageFromPages(pagesToDelete) : pagesToDelete.filter(p => !p.isEmpty);
  1515. if (isCompletely) {
  1516. for await (const page of pages) {
  1517. await this.deleteCompletely(page, user, {}, isRecursively);
  1518. }
  1519. }
  1520. else {
  1521. for await (const page of pages) {
  1522. await this.deletePage(page, user, {}, isRecursively);
  1523. }
  1524. }
  1525. }
  1526. // use the same process in both v4 and v5
  1527. private async revertDeletedDescendants(pages, user) {
  1528. const Page = this.crowi.model('Page');
  1529. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1530. const revertPageOperations: any[] = [];
  1531. const fromPathsToDelete: string[] = [];
  1532. pages.forEach((page) => {
  1533. // e.g. page.path = /trash/test, toPath = /test
  1534. const toPath = Page.getRevertDeletedPageName(page.path);
  1535. revertPageOperations.push({
  1536. updateOne: {
  1537. filter: { _id: page._id },
  1538. update: {
  1539. $set: {
  1540. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1541. },
  1542. },
  1543. },
  1544. });
  1545. fromPathsToDelete.push(page.path);
  1546. });
  1547. try {
  1548. await Page.bulkWrite(revertPageOperations);
  1549. await PageRedirect.deleteMany({ fromPath: { $in: fromPathsToDelete } });
  1550. }
  1551. catch (err) {
  1552. if (err.code !== 11000) {
  1553. throw new Error(`Failed to revert pages: ${err}`);
  1554. }
  1555. }
  1556. }
  1557. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  1558. /*
  1559. * Common Operation
  1560. */
  1561. const Page = this.crowi.model('Page');
  1562. const PageTagRelation = this.crowi.model('PageTagRelation');
  1563. // 1. Separate v4 & v5 process
  1564. const shouldUseV4Process = this.shouldUseV4ProcessForRevert(page);
  1565. if (shouldUseV4Process) {
  1566. return this.revertDeletedPageV4(page, user, options, isRecursively);
  1567. }
  1568. const newPath = Page.getRevertDeletedPageName(page.path);
  1569. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1570. if (!canOperate) {
  1571. throw Error(`Cannot operate revert from path "${page.path}" right now.`);
  1572. }
  1573. const includeEmpty = true;
  1574. const originPage = await Page.findByPath(newPath, includeEmpty);
  1575. // throw if any page already exists
  1576. if (originPage != null) {
  1577. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1578. }
  1579. // 2. Revert target
  1580. const parent = await this.getParentAndFillAncestors(newPath, user);
  1581. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1582. $set: {
  1583. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null, parent: parent._id, descendantCount: 0,
  1584. },
  1585. }, { new: true });
  1586. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1587. this.pageEvent.emit('revert', page, user);
  1588. if (!isRecursively) {
  1589. await this.updateDescendantCountOfAncestors(parent._id, 1, true);
  1590. }
  1591. else {
  1592. let pageOp;
  1593. try {
  1594. pageOp = await PageOperation.create({
  1595. actionType: PageActionType.Revert,
  1596. actionStage: PageActionStage.Main,
  1597. page,
  1598. user,
  1599. fromPath: page.path,
  1600. toPath: newPath,
  1601. options,
  1602. });
  1603. }
  1604. catch (err) {
  1605. logger.error('Failed to create PageOperation document.', err);
  1606. throw err;
  1607. }
  1608. /*
  1609. * Resumable Operation
  1610. */
  1611. this.revertRecursivelyMainOperation(page, user, options, pageOp._id);
  1612. }
  1613. return updatedPage;
  1614. }
  1615. async revertRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike): Promise<void> {
  1616. const Page = mongoose.model('Page') as unknown as PageModel;
  1617. await this.revertDeletedDescendantsWithStream(page, user, options, false);
  1618. const newPath = Page.getRevertDeletedPageName(page.path);
  1619. // normalize parent of descendant pages
  1620. const shouldNormalize = this.shouldNormalizeParent(page);
  1621. if (shouldNormalize) {
  1622. try {
  1623. await this.normalizeParentAndDescendantCountOfDescendants(newPath, user);
  1624. logger.info(`Successfully normalized reverted descendant pages under "${newPath}"`);
  1625. }
  1626. catch (err) {
  1627. logger.error('Failed to normalize descendants afrer revert:', err);
  1628. throw err;
  1629. }
  1630. }
  1631. // Set to Sub
  1632. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  1633. if (pageOp == null) {
  1634. throw Error('PageOperation document not found');
  1635. }
  1636. /*
  1637. * Sub Operation
  1638. */
  1639. await this.revertRecursivelySubOperation(newPath, pageOp._id);
  1640. }
  1641. async revertRecursivelySubOperation(newPath: string, pageOpId: ObjectIdLike): Promise<void> {
  1642. const Page = mongoose.model('Page') as unknown as PageModel;
  1643. const newTarget = await Page.findOne({ path: newPath }); // only one page will be found since duplicating to existing path is forbidden
  1644. if (newTarget == null) {
  1645. throw Error('No reverted page found. Something might have gone wrong in revertRecursivelyMainOperation.');
  1646. }
  1647. // update descendantCount of ancestors'
  1648. await this.updateDescendantCountOfAncestors(newTarget.parent as ObjectIdLike, newTarget.descendantCount + 1, true);
  1649. await PageOperation.findByIdAndDelete(pageOpId);
  1650. }
  1651. private async revertDeletedPageV4(page, user, options = {}, isRecursively = false) {
  1652. const Page = this.crowi.model('Page');
  1653. const PageTagRelation = this.crowi.model('PageTagRelation');
  1654. const newPath = Page.getRevertDeletedPageName(page.path);
  1655. const originPage = await Page.findByPath(newPath);
  1656. if (originPage != null) {
  1657. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1658. }
  1659. if (isRecursively) {
  1660. this.revertDeletedDescendantsWithStream(page, user, options);
  1661. }
  1662. page.status = Page.STATUS_PUBLISHED;
  1663. page.lastUpdateUser = user;
  1664. debug('Revert deleted the page', page, newPath);
  1665. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1666. $set: {
  1667. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1668. },
  1669. }, { new: true });
  1670. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1671. this.pageEvent.emit('revert', page, user);
  1672. return updatedPage;
  1673. }
  1674. /**
  1675. * Create revert stream
  1676. */
  1677. private async revertDeletedDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true): Promise<number> {
  1678. if (shouldUseV4Process) {
  1679. return this.revertDeletedDescendantsWithStreamV4(targetPage, user, options);
  1680. }
  1681. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1682. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1683. let count = 0;
  1684. const writeStream = new Writable({
  1685. objectMode: true,
  1686. async write(batch, encoding, callback) {
  1687. try {
  1688. count += batch.length;
  1689. await revertDeletedDescendants(batch, user);
  1690. logger.debug(`Reverting pages progressing: (count=${count})`);
  1691. }
  1692. catch (err) {
  1693. logger.error('revertPages error on add anyway: ', err);
  1694. }
  1695. callback();
  1696. },
  1697. async final(callback) {
  1698. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1699. callback();
  1700. },
  1701. });
  1702. readStream
  1703. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1704. .pipe(writeStream);
  1705. await streamToPromise(writeStream);
  1706. return count;
  1707. }
  1708. private async revertDeletedDescendantsWithStreamV4(targetPage, user, options = {}) {
  1709. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1710. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1711. let count = 0;
  1712. const writeStream = new Writable({
  1713. objectMode: true,
  1714. async write(batch, encoding, callback) {
  1715. try {
  1716. count += batch.length;
  1717. await revertDeletedDescendants(batch, user);
  1718. logger.debug(`Reverting pages progressing: (count=${count})`);
  1719. }
  1720. catch (err) {
  1721. logger.error('revertPages error on add anyway: ', err);
  1722. }
  1723. callback();
  1724. },
  1725. final(callback) {
  1726. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1727. callback();
  1728. },
  1729. });
  1730. readStream
  1731. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1732. .pipe(writeStream);
  1733. await streamToPromise(readStream);
  1734. return count;
  1735. }
  1736. async handlePrivatePagesForGroupsToDelete(groupsToDelete, action, transferToUserGroupId, user) {
  1737. const Page = this.crowi.model('Page');
  1738. const pages = await Page.find({ grantedGroup: { $in: groupsToDelete } });
  1739. switch (action) {
  1740. case 'public':
  1741. await Page.publicizePages(pages);
  1742. break;
  1743. case 'delete':
  1744. return this.deleteMultipleCompletely(pages, user);
  1745. case 'transfer':
  1746. await Page.transferPagesToGroup(pages, transferToUserGroupId);
  1747. break;
  1748. default:
  1749. throw new Error('Unknown action for private pages');
  1750. }
  1751. }
  1752. private extractStringIds(refs: Ref<HasObjectId>[]) {
  1753. return refs.map((ref: Ref<HasObjectId>) => {
  1754. return (typeof ref === 'string') ? ref : ref._id.toString();
  1755. });
  1756. }
  1757. constructBasicPageInfo(page: IPage, isGuestUser?: boolean): IPageInfo | IPageInfoForEntity {
  1758. const isMovable = isGuestUser ? false : isMovablePage(page.path);
  1759. if (page.isEmpty) {
  1760. return {
  1761. isV5Compatible: true,
  1762. isEmpty: true,
  1763. isMovable,
  1764. isDeletable: false,
  1765. isAbleToDeleteCompletely: false,
  1766. isRevertible: false,
  1767. };
  1768. }
  1769. const likers = page.liker.slice(0, 15) as Ref<IUserHasId>[];
  1770. const seenUsers = page.seenUsers.slice(0, 15) as Ref<IUserHasId>[];
  1771. return {
  1772. isV5Compatible: isTopPage(page.path) || page.parent != null,
  1773. isEmpty: false,
  1774. sumOfLikers: page.liker.length,
  1775. likerIds: this.extractStringIds(likers),
  1776. seenUserIds: this.extractStringIds(seenUsers),
  1777. sumOfSeenUsers: page.seenUsers.length,
  1778. isMovable,
  1779. isDeletable: isMovable,
  1780. isAbleToDeleteCompletely: false,
  1781. isRevertible: isTrashPage(page.path),
  1782. };
  1783. }
  1784. async shortBodiesMapByPageIds(pageIds: ObjectId[] = [], user): Promise<Record<string, string | null>> {
  1785. const Page = mongoose.model('Page') as unknown as PageModel;
  1786. const MAX_LENGTH = 350;
  1787. // aggregation options
  1788. let userGroups;
  1789. if (user != null && userGroups == null) {
  1790. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // Typescriptize model
  1791. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  1792. }
  1793. const viewerCondition = Page.generateGrantCondition(user, userGroups);
  1794. const filterByIds = {
  1795. _id: { $in: pageIds },
  1796. };
  1797. let pages;
  1798. try {
  1799. pages = await Page
  1800. .aggregate([
  1801. // filter by pageIds
  1802. {
  1803. $match: filterByIds,
  1804. },
  1805. // filter by viewer
  1806. {
  1807. $match: viewerCondition,
  1808. },
  1809. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  1810. {
  1811. $lookup: {
  1812. from: 'revisions',
  1813. let: { localRevision: '$revision' },
  1814. pipeline: [
  1815. {
  1816. $match: {
  1817. $expr: {
  1818. $eq: ['$_id', '$$localRevision'],
  1819. },
  1820. },
  1821. },
  1822. {
  1823. $project: {
  1824. // What is $substrCP?
  1825. // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
  1826. revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
  1827. },
  1828. },
  1829. ],
  1830. as: 'revisionData',
  1831. },
  1832. },
  1833. // projection
  1834. {
  1835. $project: {
  1836. _id: 1,
  1837. revisionData: 1,
  1838. },
  1839. },
  1840. ]).exec();
  1841. }
  1842. catch (err) {
  1843. logger.error('Error occurred while generating shortBodiesMap');
  1844. throw err;
  1845. }
  1846. const shortBodiesMap = {};
  1847. pages.forEach((page) => {
  1848. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  1849. });
  1850. return shortBodiesMap;
  1851. }
  1852. private async createAndSendNotifications(page, user, action) {
  1853. const { activityService, inAppNotificationService } = this.crowi;
  1854. const snapshot = stringifySnapshot(page);
  1855. // Create activity
  1856. const parameters = {
  1857. user: user._id,
  1858. targetModel: SUPPORTED_TARGET_MODEL_TYPE.MODEL_PAGE,
  1859. target: page,
  1860. action,
  1861. };
  1862. const activity = await activityService.createByParameters(parameters);
  1863. // Get user to be notified
  1864. const targetUsers = await activity.getNotificationTargetUsers();
  1865. // Create and send notifications
  1866. await inAppNotificationService.upsertByActivity(targetUsers, activity, snapshot);
  1867. await inAppNotificationService.emitSocketIo(targetUsers);
  1868. }
  1869. async normalizeParentByPath(path: string, user): Promise<void> {
  1870. const Page = mongoose.model('Page') as unknown as PageModel;
  1871. const pages = await Page.findByPathAndViewer(path, user, null, false);
  1872. if (pages == null || !Array.isArray(pages)) {
  1873. throw Error('Something went wrong while converting pages.');
  1874. }
  1875. if (pages.length === 0) {
  1876. const isForbidden = await Page.count({ path, isEmpty: false }) > 0;
  1877. if (isForbidden) {
  1878. throw new V5ConversionError('It is not allowed to convert this page.', V5ConversionErrCode.FORBIDDEN);
  1879. }
  1880. }
  1881. if (pages.length > 1) {
  1882. throw new V5ConversionError(
  1883. `There are more than two pages at the path "${path}". Please rename or delete the page first.`,
  1884. V5ConversionErrCode.DUPLICATE_PAGES_FOUND,
  1885. );
  1886. }
  1887. let page;
  1888. let systematicallyCreatedPage;
  1889. const shouldCreateNewPage = pages[0] == null;
  1890. if (shouldCreateNewPage) {
  1891. const notEmptyParent = await Page.findNotEmptyParentByPathRecursively(path);
  1892. systematicallyCreatedPage = await Page.createSystematically(
  1893. path,
  1894. 'This page was created by GROWI.',
  1895. {
  1896. grant: notEmptyParent.grant,
  1897. grantedUserIds: notEmptyParent.grantedUsers,
  1898. grantUserGroupId: notEmptyParent.grantedGroup,
  1899. },
  1900. );
  1901. page = systematicallyCreatedPage;
  1902. }
  1903. else {
  1904. page = page[0];
  1905. }
  1906. const grant = page.grant;
  1907. const grantedUserIds = page.grantedUsers;
  1908. const grantedGroupId = page.grantedGroup;
  1909. /*
  1910. * UserGroup & Owner validation
  1911. */
  1912. let isGrantNormalized = false;
  1913. try {
  1914. const shouldCheckDescendants = true;
  1915. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  1916. }
  1917. catch (err) {
  1918. // TODO: delete systematicallyCreatedPage
  1919. logger.error(`Failed to validate grant of page at "${path}"`, err);
  1920. throw err;
  1921. }
  1922. if (!isGrantNormalized) {
  1923. throw new V5ConversionError(
  1924. 'This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.',
  1925. V5ConversionErrCode.GRANT_INVALID,
  1926. );
  1927. }
  1928. let pageOp;
  1929. try {
  1930. pageOp = await PageOperation.create({
  1931. actionType: PageActionType.NormalizeParent,
  1932. actionStage: PageActionStage.Main,
  1933. page,
  1934. user,
  1935. fromPath: page.path,
  1936. toPath: page.path,
  1937. });
  1938. }
  1939. catch (err) {
  1940. // TODO: delete systematicallyCreatedPage
  1941. logger.error('Failed to create PageOperation document.', err);
  1942. throw err;
  1943. }
  1944. // no await
  1945. (async() => {
  1946. // Remove the created page if no page has converted
  1947. const count = await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  1948. if (count === 0) {
  1949. // TODO: delete systematicallyCreatedPage
  1950. // await this.deleteCompletelySystematically(systematicallyCreatedPage, user, {}, false);
  1951. }
  1952. })();
  1953. }
  1954. async normalizeParentByPageIdsRecursively(pageIds: ObjectIdLike[], user): Promise<void> {
  1955. const Page = mongoose.model('Page') as unknown as PageModel;
  1956. const pages = await Page.findByIdsAndViewer(pageIds, user, null);
  1957. if (pages == null || pages.length === 0) {
  1958. throw Error('pageIds is null or 0 length.');
  1959. }
  1960. if (pages.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1961. throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1962. }
  1963. this.normalizeParentRecursivelyByPages(pages, user);
  1964. return;
  1965. }
  1966. async normalizeParentByPageIds(pageIds: ObjectIdLike[], user): Promise<void> {
  1967. const Page = await mongoose.model('Page') as unknown as PageModel;
  1968. const socket = this.crowi.socketIoService.getDefaultSocket();
  1969. for await (const pageId of pageIds) {
  1970. const page = await Page.findById(pageId);
  1971. if (page == null) {
  1972. continue;
  1973. }
  1974. const errorData: PageMigrationErrorData = { paths: [page.path] };
  1975. try {
  1976. const canOperate = await this.crowi.pageOperationService.canOperate(false, page.path, page.path);
  1977. if (!canOperate) {
  1978. throw Error(`Cannot operate normalizeParent to path "${page.path}" right now.`);
  1979. }
  1980. const normalizedPage = await this.normalizeParentByPage(page, user);
  1981. if (normalizedPage == null) {
  1982. socket.emit(SocketEventName.PageMigrationError, errorData);
  1983. logger.error(`Failed to update descendantCount of page of id: "${pageId}"`);
  1984. }
  1985. }
  1986. catch (err) {
  1987. socket.emit(SocketEventName.PageMigrationError, errorData);
  1988. logger.error('Something went wrong while normalizing parent.', err);
  1989. }
  1990. }
  1991. socket.emit(SocketEventName.PageMigrationSuccess);
  1992. }
  1993. private async normalizeParentByPage(page, user) {
  1994. const Page = mongoose.model('Page') as unknown as PageModel;
  1995. const {
  1996. path, grant, grantedUsers: grantedUserIds, grantedGroup: grantedGroupId,
  1997. } = page;
  1998. // check if any page exists at target path already
  1999. const existingPage = await Page.findOne({ path, parent: { $ne: null } });
  2000. if (existingPage != null && !existingPage.isEmpty) {
  2001. throw Error('Page already exists. Please rename the page to continue.');
  2002. }
  2003. /*
  2004. * UserGroup & Owner validation
  2005. */
  2006. if (grant !== Page.GRANT_RESTRICTED) {
  2007. let isGrantNormalized = false;
  2008. try {
  2009. const shouldCheckDescendants = true;
  2010. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  2011. }
  2012. catch (err) {
  2013. logger.error(`Failed to validate grant of page at "${path}"`, err);
  2014. throw err;
  2015. }
  2016. if (!isGrantNormalized) {
  2017. throw Error('This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.');
  2018. }
  2019. }
  2020. else {
  2021. throw Error('Restricted pages can not be migrated');
  2022. }
  2023. let normalizedPage;
  2024. // replace if empty page exists
  2025. if (existingPage != null && existingPage.isEmpty) {
  2026. // Inherit descendantCount from the empty page
  2027. const updatedPage = await Page.findOneAndUpdate({ _id: page._id }, { descendantCount: existingPage.descendantCount }, { new: true });
  2028. await Page.replaceTargetWithPage(existingPage, updatedPage, true);
  2029. normalizedPage = await Page.findById(page._id);
  2030. }
  2031. else {
  2032. const parent = await this.getParentAndFillAncestors(page.path, user);
  2033. normalizedPage = await Page.findOneAndUpdate({ _id: page._id }, { parent: parent._id }, { new: true });
  2034. }
  2035. // Update descendantCount
  2036. const inc = 1;
  2037. await this.updateDescendantCountOfAncestors(normalizedPage.parent, inc, true);
  2038. return normalizedPage;
  2039. }
  2040. async normalizeParentRecursivelyByPages(pages, user): Promise<void> {
  2041. /*
  2042. * Main Operation
  2043. */
  2044. const socket = this.crowi.socketIoService.getDefaultSocket();
  2045. const pagesToNormalize = omitDuplicateAreaPageFromPages(pages);
  2046. let normalizablePages;
  2047. let nonNormalizablePages;
  2048. try {
  2049. [normalizablePages, nonNormalizablePages] = await this.crowi.pageGrantService.separateNormalizableAndNotNormalizablePages(user, pagesToNormalize);
  2050. }
  2051. catch (err) {
  2052. socket.emit(SocketEventName.PageMigrationError);
  2053. throw err;
  2054. }
  2055. if (normalizablePages.length === 0) {
  2056. socket.emit(SocketEventName.PageMigrationError);
  2057. return;
  2058. }
  2059. if (nonNormalizablePages.length !== 0) {
  2060. const nonNormalizablePagePaths: string[] = nonNormalizablePages.map(p => p.path);
  2061. socket.emit(SocketEventName.PageMigrationError, { paths: nonNormalizablePagePaths });
  2062. logger.debug('Some pages could not be converted.', nonNormalizablePagePaths);
  2063. }
  2064. /*
  2065. * Main Operation (s)
  2066. */
  2067. const errorPagePaths: string[] = [];
  2068. for await (const page of normalizablePages) {
  2069. const canOperate = await this.crowi.pageOperationService.canOperate(true, page.path, page.path);
  2070. if (!canOperate) {
  2071. errorPagePaths.push(page.path);
  2072. throw Error(`Cannot operate normalizeParentRecursiively to path "${page.path}" right now.`);
  2073. }
  2074. const Page = mongoose.model('Page') as unknown as PageModel;
  2075. const { PageQueryBuilder } = Page;
  2076. const builder = new PageQueryBuilder(Page.findOne());
  2077. builder.addConditionAsMigrated();
  2078. builder.addConditionToListByPathsArray([page.path]);
  2079. const existingPage = await builder.query.exec();
  2080. if (existingPage?.parent != null) {
  2081. errorPagePaths.push(page.path);
  2082. throw Error('This page has already converted.');
  2083. }
  2084. let pageOp;
  2085. try {
  2086. pageOp = await PageOperation.create({
  2087. actionType: PageActionType.NormalizeParent,
  2088. actionStage: PageActionStage.Main,
  2089. page,
  2090. user,
  2091. fromPath: page.path,
  2092. toPath: page.path,
  2093. });
  2094. }
  2095. catch (err) {
  2096. errorPagePaths.push(page.path);
  2097. logger.error('Failed to create PageOperation document.', err);
  2098. throw err;
  2099. }
  2100. try {
  2101. await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  2102. }
  2103. catch (err) {
  2104. errorPagePaths.push(page.path);
  2105. logger.err('Failed to run normalizeParentRecursivelyMainOperation.', err);
  2106. throw err;
  2107. }
  2108. }
  2109. if (errorPagePaths.length === 0) {
  2110. socket.emit(SocketEventName.PageMigrationSuccess);
  2111. }
  2112. else {
  2113. socket.emit(SocketEventName.PageMigrationError, { paths: errorPagePaths });
  2114. }
  2115. }
  2116. async normalizeParentRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike): Promise<number> {
  2117. // Save prevDescendantCount for sub-operation
  2118. const Page = mongoose.model('Page') as unknown as PageModel;
  2119. const { PageQueryBuilder } = Page;
  2120. const builder = new PageQueryBuilder(Page.findOne(), true);
  2121. builder.addConditionAsMigrated();
  2122. builder.addConditionToListByPathsArray([page.path]);
  2123. const exPage = await builder.query.exec();
  2124. const options = { prevDescendantCount: exPage?.descendantCount ?? 0 };
  2125. let count: number;
  2126. try {
  2127. count = await this.normalizeParentRecursively([page.path], user);
  2128. }
  2129. catch (err) {
  2130. logger.error('V5 initial miration failed.', err);
  2131. // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
  2132. throw err;
  2133. }
  2134. // Set to Sub
  2135. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  2136. if (pageOp == null) {
  2137. throw Error('PageOperation document not found');
  2138. }
  2139. await this.normalizeParentRecursivelySubOperation(page, user, pageOp._id, options);
  2140. return count;
  2141. }
  2142. async normalizeParentRecursivelySubOperation(page, user, pageOpId: ObjectIdLike, options: {prevDescendantCount: number}): Promise<void> {
  2143. const Page = mongoose.model('Page') as unknown as PageModel;
  2144. try {
  2145. // update descendantCount of self and descendant pages first
  2146. await this.updateDescendantCountOfSelfAndDescendants(page.path);
  2147. // find pages again to get updated descendantCount
  2148. // then calculate inc
  2149. const pageAfterUpdatingDescendantCount = await Page.findByIdAndViewer(page._id, user);
  2150. if (pageAfterUpdatingDescendantCount == null) {
  2151. throw Error('Page not found after updating descendantCount');
  2152. }
  2153. const { prevDescendantCount } = options;
  2154. const newDescendantCount = pageAfterUpdatingDescendantCount.descendantCount;
  2155. let inc = newDescendantCount - prevDescendantCount;
  2156. const isAlreadyConverted = page.parent != null;
  2157. if (!isAlreadyConverted) {
  2158. inc += 1;
  2159. }
  2160. await this.updateDescendantCountOfAncestors(page._id, inc, false);
  2161. }
  2162. catch (err) {
  2163. logger.error('Failed to update descendantCount after normalizing parent:', err);
  2164. throw Error(`Failed to update descendantCount after normalizing parent: ${err}`);
  2165. }
  2166. await PageOperation.findByIdAndDelete(pageOpId);
  2167. }
  2168. async _isPagePathIndexUnique() {
  2169. const Page = this.crowi.model('Page');
  2170. const now = (new Date()).toString();
  2171. const path = `growi_check_is_path_index_unique_${now}`;
  2172. let isUnique = false;
  2173. try {
  2174. await Page.insertMany([
  2175. { path },
  2176. { path },
  2177. ]);
  2178. }
  2179. catch (err) {
  2180. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  2181. isUnique = true;
  2182. logger.info('Page path index is unique.');
  2183. }
  2184. else {
  2185. throw err;
  2186. }
  2187. }
  2188. finally {
  2189. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  2190. }
  2191. return isUnique;
  2192. }
  2193. // TODO: use socket to send status to the client
  2194. async normalizeAllPublicPages() {
  2195. // const socket = this.crowi.socketIoService.getAdminSocket();
  2196. let isUnique;
  2197. try {
  2198. isUnique = await this._isPagePathIndexUnique();
  2199. }
  2200. catch (err) {
  2201. logger.error('Failed to check path index status', err);
  2202. throw err;
  2203. }
  2204. // drop unique index first
  2205. if (isUnique) {
  2206. try {
  2207. await this._v5NormalizeIndex();
  2208. }
  2209. catch (err) {
  2210. logger.error('V5 index normalization failed.', err);
  2211. // socket.emit('v5IndexNormalizationFailed', { error: err.message });
  2212. throw err;
  2213. }
  2214. }
  2215. // then migrate
  2216. try {
  2217. await this.normalizeParentRecursively(['/'], null);
  2218. }
  2219. catch (err) {
  2220. logger.error('V5 initial miration failed.', err);
  2221. // socket.emit('v5InitialMirationFailed', { error: err.message });
  2222. throw err;
  2223. }
  2224. // update descendantCount of all public pages
  2225. try {
  2226. await this.updateDescendantCountOfSelfAndDescendants('/');
  2227. logger.info('Successfully updated all descendantCount of public pages.');
  2228. }
  2229. catch (err) {
  2230. logger.error('Failed updating descendantCount of public pages.', err);
  2231. throw err;
  2232. }
  2233. await this._setIsV5CompatibleTrue();
  2234. }
  2235. private async _setIsV5CompatibleTrue() {
  2236. try {
  2237. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  2238. 'app:isV5Compatible': true,
  2239. });
  2240. logger.info('Successfully migrated all public pages.');
  2241. }
  2242. catch (err) {
  2243. logger.warn('Failed to update app:isV5Compatible to true.');
  2244. throw err;
  2245. }
  2246. }
  2247. private async normalizeParentAndDescendantCountOfDescendants(path: string, user): Promise<void> {
  2248. await this.normalizeParentRecursively([path], user);
  2249. // update descendantCount of descendant pages
  2250. await this.updateDescendantCountOfSelfAndDescendants(path);
  2251. }
  2252. /**
  2253. * Normalize parent attribute by passing paths and user.
  2254. * @param paths Pages under this paths value will be updated.
  2255. * @param user To be used to filter pages to update. If null, only public pages will be updated.
  2256. * @returns Promise<void>
  2257. */
  2258. async normalizeParentRecursively(paths: string[], user: any | null): Promise<number> {
  2259. const Page = mongoose.model('Page') as unknown as PageModel;
  2260. const ancestorPaths = paths.flatMap(p => collectAncestorPaths(p, []));
  2261. // targets' descendants
  2262. const pathAndRegExpsToNormalize: (RegExp | string)[] = paths
  2263. .map(p => new RegExp(`^${escapeStringRegexp(addTrailingSlash(p))}`, 'i'));
  2264. // include targets' path
  2265. pathAndRegExpsToNormalize.push(...paths);
  2266. // determine UserGroup condition
  2267. let userGroups = null;
  2268. if (user != null) {
  2269. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model
  2270. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  2271. }
  2272. const grantFiltersByUser: { $or: any[] } = Page.generateGrantCondition(user, userGroups);
  2273. return this._normalizeParentRecursively(pathAndRegExpsToNormalize, ancestorPaths, grantFiltersByUser, user);
  2274. }
  2275. private buildFilterForNormalizeParentRecursively(pathOrRegExps: (RegExp | string)[], publicPathsToNormalize: string[], grantFiltersByUser: { $or: any[] }) {
  2276. const Page = mongoose.model('Page') as unknown as PageModel;
  2277. const andFilter: any = {
  2278. $and: [
  2279. {
  2280. parent: null,
  2281. status: Page.STATUS_PUBLISHED,
  2282. path: { $ne: '/' },
  2283. },
  2284. ],
  2285. };
  2286. const orFilter: any = { $or: [] };
  2287. // specified pathOrRegExps
  2288. if (pathOrRegExps.length > 0) {
  2289. orFilter.$or.push(
  2290. {
  2291. path: { $in: pathOrRegExps },
  2292. },
  2293. );
  2294. }
  2295. // not specified but ancestors of specified pathOrRegExps
  2296. if (publicPathsToNormalize.length > 0) {
  2297. orFilter.$or.push(
  2298. {
  2299. path: { $in: publicPathsToNormalize },
  2300. grant: Page.GRANT_PUBLIC, // use only public pages to complete the tree
  2301. },
  2302. );
  2303. }
  2304. // Merge filters
  2305. const mergedFilter = {
  2306. $and: [
  2307. { $and: [grantFiltersByUser, ...andFilter.$and] },
  2308. { $or: orFilter.$or },
  2309. ],
  2310. };
  2311. return mergedFilter;
  2312. }
  2313. private async _normalizeParentRecursively(
  2314. pathOrRegExps: (RegExp | string)[], publicPathsToNormalize: string[], grantFiltersByUser: { $or: any[] }, user, count = 0, skiped = 0, isFirst = true,
  2315. ): Promise<number> {
  2316. const BATCH_SIZE = 100;
  2317. const PAGES_LIMIT = 1000;
  2318. const socket = this.crowi.socketIoService.getAdminSocket();
  2319. const Page = mongoose.model('Page') as unknown as PageModel;
  2320. const { PageQueryBuilder } = Page;
  2321. // Build filter
  2322. const matchFilter = this.buildFilterForNormalizeParentRecursively(pathOrRegExps, publicPathsToNormalize, grantFiltersByUser);
  2323. let baseAggregation = Page
  2324. .aggregate([
  2325. { $match: matchFilter },
  2326. {
  2327. $project: { // minimize data to fetch
  2328. _id: 1,
  2329. path: 1,
  2330. },
  2331. },
  2332. ]);
  2333. // Limit pages to get
  2334. const total = await Page.countDocuments(matchFilter);
  2335. if (isFirst) {
  2336. socket.emit(SocketEventName.PMStarted, { total });
  2337. }
  2338. if (total > PAGES_LIMIT) {
  2339. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  2340. }
  2341. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  2342. const batchStream = createBatchStream(BATCH_SIZE);
  2343. let shouldContinue = true;
  2344. let nextCount = count;
  2345. let nextSkiped = skiped;
  2346. const createEmptyPagesByPaths = this.createEmptyPagesByPaths.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. await createEmptyPagesByPaths(parentPaths, user, false, true, filterForApplicableAncestors);
  2381. // 3. Find parents
  2382. const addGrantCondition = (builder) => {
  2383. builder.query = builder.query.and(grantFiltersByUser);
  2384. return builder;
  2385. };
  2386. const builder2 = new PageQueryBuilder(Page.find(), true);
  2387. addGrantCondition(builder2);
  2388. const parents = await builder2
  2389. .addConditionToListByPathsArray(parentPaths)
  2390. .addConditionToFilterByApplicableAncestors(publicPathsToNormalize)
  2391. .query
  2392. .lean()
  2393. .exec();
  2394. // Normalize all siblings for each page
  2395. const updateManyOperations = parents.map((parent) => {
  2396. const parentId = parent._id;
  2397. // Build filter
  2398. const parentPathEscaped = escapeStringRegexp(parent.path === '/' ? '' : parent.path); // adjust the path for RegExp
  2399. const filter: any = {
  2400. $and: [
  2401. {
  2402. path: { $regex: new RegExp(`^${parentPathEscaped}(\\/[^/]+)\\/?$`, 'i') }, // see: regexr.com/6889f (e.g. /parent/any_child or /any_level1)
  2403. },
  2404. {
  2405. path: { $in: pathOrRegExps.concat(publicPathsToNormalize) },
  2406. },
  2407. filterForApplicableAncestors,
  2408. grantFiltersByUser,
  2409. ],
  2410. };
  2411. return {
  2412. updateMany: {
  2413. filter,
  2414. update: {
  2415. parent: parentId,
  2416. },
  2417. },
  2418. };
  2419. });
  2420. try {
  2421. const res = await Page.bulkWrite(updateManyOperations);
  2422. nextCount += res.result.nModified;
  2423. nextSkiped += res.result.writeErrors.length;
  2424. logger.info(`Page migration processing: (migratedPages=${res.result.nModified})`);
  2425. socket.emit(SocketEventName.PMMigrating, { count: nextCount });
  2426. socket.emit(SocketEventName.PMErrorCount, { skip: nextSkiped });
  2427. // Throw if any error is found
  2428. if (res.result.writeErrors.length > 0) {
  2429. logger.error('Failed to migrate some pages', res.result.writeErrors);
  2430. socket.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2431. throw Error('Failed to migrate some pages');
  2432. }
  2433. // Finish migration if no modification occurred
  2434. if (res.result.nModified === 0 && res.result.nMatched === 0) {
  2435. shouldContinue = false;
  2436. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  2437. socket.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2438. }
  2439. }
  2440. catch (err) {
  2441. logger.error('Failed to update page.parent.', err);
  2442. throw err;
  2443. }
  2444. callback();
  2445. },
  2446. final(callback) {
  2447. callback();
  2448. },
  2449. });
  2450. pagesStream
  2451. .pipe(batchStream)
  2452. .pipe(migratePagesStream);
  2453. await streamToPromise(migratePagesStream);
  2454. if (await Page.exists(matchFilter) && shouldContinue) {
  2455. return this._normalizeParentRecursively(pathOrRegExps, publicPathsToNormalize, grantFiltersByUser, user, nextCount, nextSkiped, false);
  2456. }
  2457. // End
  2458. socket.emit(SocketEventName.PMEnded, { isSucceeded: true });
  2459. return nextCount;
  2460. }
  2461. private async _v5NormalizeIndex() {
  2462. const collection = mongoose.connection.collection('pages');
  2463. try {
  2464. // drop pages.path_1 indexes
  2465. await collection.dropIndex('path_1');
  2466. logger.info('Succeeded to drop unique indexes from pages.path.');
  2467. }
  2468. catch (err) {
  2469. logger.warn('Failed to drop unique indexes from pages.path.', err);
  2470. throw err;
  2471. }
  2472. try {
  2473. // create indexes without
  2474. await collection.createIndex({ path: 1 }, { unique: false });
  2475. logger.info('Succeeded to create non-unique indexes on pages.path.');
  2476. }
  2477. catch (err) {
  2478. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  2479. throw err;
  2480. }
  2481. }
  2482. async countPagesCanNormalizeParentByUser(user): Promise<number> {
  2483. if (user == null) {
  2484. throw Error('user is required');
  2485. }
  2486. const Page = mongoose.model('Page') as unknown as PageModel;
  2487. const { PageQueryBuilder } = Page;
  2488. const builder = new PageQueryBuilder(Page.count(), false);
  2489. await builder.addConditionAsMigratablePages(user);
  2490. const nMigratablePages = await builder.query.exec();
  2491. return nMigratablePages;
  2492. }
  2493. /**
  2494. * update descendantCount of the following pages
  2495. * - page that has the same path as the provided path
  2496. * - pages that are descendants of the above page
  2497. */
  2498. async updateDescendantCountOfSelfAndDescendants(path: string): Promise<void> {
  2499. const BATCH_SIZE = 200;
  2500. const Page = this.crowi.model('Page');
  2501. const { PageQueryBuilder } = Page;
  2502. const builder = new PageQueryBuilder(Page.find(), true);
  2503. builder.addConditionAsMigrated();
  2504. builder.addConditionToListWithDescendants(path);
  2505. builder.addConditionToSortPagesByDescPath();
  2506. const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
  2507. const recountWriteStream = new Writable({
  2508. objectMode: true,
  2509. async write(pageDocuments, encoding, callback) {
  2510. for await (const document of pageDocuments) {
  2511. const descendantCount = await Page.recountDescendantCount(document._id);
  2512. await Page.findByIdAndUpdate(document._id, { descendantCount });
  2513. }
  2514. callback();
  2515. },
  2516. final(callback) {
  2517. callback();
  2518. },
  2519. });
  2520. aggregatedPages
  2521. .pipe(createBatchStream(BATCH_SIZE))
  2522. .pipe(recountWriteStream);
  2523. await streamToPromise(recountWriteStream);
  2524. }
  2525. // update descendantCount of all pages that are ancestors of a provided pageId by count
  2526. async updateDescendantCountOfAncestors(pageId: ObjectIdLike, inc: number, shouldIncludeTarget: boolean): Promise<void> {
  2527. const Page = this.crowi.model('Page');
  2528. const ancestors = await Page.findAncestorsUsingParentRecursively(pageId, shouldIncludeTarget);
  2529. const ancestorPageIds = ancestors.map(p => p._id);
  2530. await Page.incrementDescendantCountOfPageIds(ancestorPageIds, inc);
  2531. const updateDescCountData: UpdateDescCountRawData = Object.fromEntries(ancestors.map(p => [p._id.toString(), p.descendantCount + inc]));
  2532. this.emitUpdateDescCount(updateDescCountData);
  2533. }
  2534. private emitUpdateDescCount(data: UpdateDescCountRawData): void {
  2535. const socket = this.crowi.socketIoService.getDefaultSocket();
  2536. socket.emit(SocketEventName.UpdateDescCount, data);
  2537. }
  2538. /**
  2539. * Find parent or create parent if not exists.
  2540. * It also updates parent of ancestors
  2541. * @param path string
  2542. * @returns Promise<PageDocument>
  2543. */
  2544. async getParentAndFillAncestors(path: string, user, options?: { isSystematically?: boolean }): Promise<PageDocument> {
  2545. const Page = mongoose.model('Page') as unknown as PageModel;
  2546. const { PageQueryBuilder } = Page;
  2547. const parentPath = pathlib.dirname(path);
  2548. const builder1 = new PageQueryBuilder(Page.find({ path: parentPath }), true);
  2549. const pagesCanBeParent = await builder1
  2550. .addConditionAsMigrated()
  2551. .query
  2552. .exec();
  2553. if (pagesCanBeParent.length >= 1) {
  2554. return pagesCanBeParent[0]; // the earliest page will be the result
  2555. }
  2556. /*
  2557. * Fill parents if parent is null
  2558. */
  2559. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  2560. // just create ancestors with empty pages
  2561. // TODO: separate process
  2562. await this.createEmptyPagesByPaths(ancestorPaths, user, true);
  2563. // find ancestors
  2564. const builder2 = new PageQueryBuilder(Page.find(), true);
  2565. // avoid including not normalized pages
  2566. builder2.addConditionToFilterByApplicableAncestors(ancestorPaths);
  2567. const ancestors = await builder2
  2568. .addConditionToListByPathsArray(ancestorPaths)
  2569. .addConditionToSortPagesByDescPath()
  2570. .query
  2571. .exec();
  2572. const ancestorsMap = new Map(); // Map<path, page>
  2573. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  2574. // bulkWrite to update ancestors
  2575. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  2576. const operations = nonRootAncestors.map((page) => {
  2577. const parentPath = pathlib.dirname(page.path);
  2578. return {
  2579. updateOne: {
  2580. filter: {
  2581. _id: page._id,
  2582. },
  2583. update: {
  2584. parent: ancestorsMap.get(parentPath)._id,
  2585. },
  2586. },
  2587. };
  2588. });
  2589. await Page.bulkWrite(operations);
  2590. const parentId = ancestorsMap.get(parentPath)._id; // get parent page id to fetch updated parent parent
  2591. const createdParent = await Page.findOne({ _id: parentId });
  2592. if (createdParent == null) {
  2593. throw Error('updated parent not Found');
  2594. }
  2595. return createdParent;
  2596. }
  2597. // TODO: separate processes for systematical and manual operations
  2598. /**
  2599. * Create empty pages if the page in paths didn't exist
  2600. * @param onlyMigratedAsExistingPages Determine whether to include non-migrated pages as existing pages. If a page exists,
  2601. * an empty page will not be created at that page's path.
  2602. */
  2603. async createEmptyPagesByPaths(
  2604. paths: string[],
  2605. user: any | null,
  2606. onlyMigratedAsExistingPages = true,
  2607. andFilter?,
  2608. ): Promise<void> {
  2609. const Page = mongoose.model('Page') as unknown as PageModel;
  2610. const aggregationPipeline: any[] = [];
  2611. // 1. Filter by paths
  2612. aggregationPipeline.push({ $match: { path: { $in: paths } } });
  2613. // 2. Normalized condition
  2614. if (onlyMigratedAsExistingPages) {
  2615. aggregationPipeline.push({
  2616. $match: {
  2617. $or: [
  2618. { grant: Page.GRANT_PUBLIC },
  2619. { parent: { $ne: null } },
  2620. { path: '/' },
  2621. ],
  2622. },
  2623. });
  2624. }
  2625. // 3. Add custom pipeline
  2626. if (andFilter != null) {
  2627. aggregationPipeline.push({ $match: andFilter });
  2628. }
  2629. // 4. Add grant conditions
  2630. // TODO: need to separate here
  2631. let userGroups = null;
  2632. if (user != null) {
  2633. const UserGroupRelation = mongoose.model('UserGroupRelation') as any;
  2634. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  2635. }
  2636. const grantCondition = Page.generateGrantCondition(user, userGroups);
  2637. aggregationPipeline.push({ $match: grantCondition });
  2638. // Run aggregation
  2639. const existingPages = await Page.aggregate(aggregationPipeline);
  2640. const existingPagePaths = existingPages.map(page => page.path);
  2641. // paths to create empty pages
  2642. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  2643. // insertMany empty pages
  2644. try {
  2645. await Page.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  2646. }
  2647. catch (err) {
  2648. logger.error('Failed to insert empty pages.', err);
  2649. throw err;
  2650. }
  2651. }
  2652. async create(path: string, body: string, user, options: PageCreateOptions = {}) {
  2653. const Page = mongoose.model('Page') as unknown as PageModel;
  2654. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  2655. const { isSystematically } = options;
  2656. if (user == null && !isSystematically) {
  2657. throw Error('Cannot call create() without a parameter "user" when shouldSkipUserValidation is false.');
  2658. }
  2659. const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  2660. // v4 compatible process
  2661. if (!isV5Compatible) {
  2662. return Page.createV4(path, body, user, options);
  2663. }
  2664. const canOperate = await this.crowi.pageOperationService.canOperate(false, null, path);
  2665. if (!canOperate) {
  2666. throw Error(`Cannot operate create to path "${path}" right now.`);
  2667. }
  2668. const {
  2669. format = 'markdown', grantUserGroupId, grantedUserIds,
  2670. } = options;
  2671. let grant = options.grant;
  2672. // sanitize path
  2673. path = this.crowi.xss.process(path); // eslint-disable-line no-param-reassign
  2674. // throw if exists
  2675. const isExist = (await Page.count({ path, isEmpty: false })) > 0; // not validate empty page
  2676. if (isExist) {
  2677. throw Error('Cannot create new page to existed path');
  2678. }
  2679. // force public
  2680. if (isTopPage(path)) {
  2681. grant = Page.GRANT_PUBLIC;
  2682. }
  2683. // find an existing empty page
  2684. const emptyPage = await Page.findOne({ path, isEmpty: true });
  2685. /*
  2686. * UserGroup & Owner validation
  2687. */
  2688. if (!isSystematically && grant !== Page.GRANT_RESTRICTED) {
  2689. let isGrantNormalized = false;
  2690. try {
  2691. // It must check descendants as well if emptyTarget is not null
  2692. const shouldCheckDescendants = emptyPage != null;
  2693. const newGrantedUserIds = grant === Page.GRANT_OWNER ? [user._id] : undefined;
  2694. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  2695. }
  2696. catch (err) {
  2697. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  2698. throw err;
  2699. }
  2700. if (!isGrantNormalized) {
  2701. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  2702. }
  2703. }
  2704. /*
  2705. * update empty page if exists, if not, create a new page
  2706. */
  2707. let page;
  2708. if (emptyPage != null && grant !== Page.GRANT_RESTRICTED) {
  2709. page = emptyPage;
  2710. const descendantCount = await Page.recountDescendantCount(page._id);
  2711. page.descendantCount = descendantCount;
  2712. page.isEmpty = false;
  2713. }
  2714. else {
  2715. page = new Page();
  2716. }
  2717. page.path = path;
  2718. page.creator = user;
  2719. page.lastUpdateUser = user;
  2720. page.status = Page.STATUS_PUBLISHED;
  2721. // set parent to null when GRANT_RESTRICTED
  2722. const isGrantRestricted = grant === Page.GRANT_RESTRICTED;
  2723. if (isTopPage(path) || isGrantRestricted) {
  2724. page.parent = null;
  2725. }
  2726. else {
  2727. const options = { isSystematically };
  2728. const parent = await this.getParentAndFillAncestors(path, user, options);
  2729. page.parent = parent._id;
  2730. }
  2731. const userForApplyScope = grantedUserIds?.[0] != null ? { _id: grantedUserIds[0] } : user;
  2732. page.applyScope(userForApplyScope, grant, grantUserGroupId);
  2733. let savedPage = await page.save();
  2734. /*
  2735. * After save
  2736. */
  2737. // Delete PageRedirect if exists
  2738. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  2739. try {
  2740. await PageRedirect.deleteOne({ fromPath: path });
  2741. logger.warn(`Deleted page redirect after creating a new page at path "${path}".`);
  2742. }
  2743. catch (err) {
  2744. // no throw
  2745. logger.error('Failed to delete PageRedirect');
  2746. }
  2747. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  2748. savedPage = await pushRevision(savedPage, newRevision, user);
  2749. await savedPage.populateDataToShowRevision();
  2750. this.pageEvent.emit('create', savedPage, user);
  2751. // update descendantCount asynchronously
  2752. await this.crowi.pageService.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  2753. return savedPage;
  2754. }
  2755. }
  2756. export default PageService;