page.ts 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010
  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,
  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 Page.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 Page.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 (Page.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 Page = this.crowi.model('Page');
  881. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  882. // populate
  883. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  884. // create option
  885. const options: any = { page };
  886. options.grant = page.grant;
  887. options.grantUserGroupId = page.grantedGroup;
  888. options.grantedUserIds = page.grantedUsers;
  889. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  890. const createdPage = await Page.create(
  891. newPagePath, page.revision.body, user, options,
  892. );
  893. this.pageEvent.emit('duplicate', page, user);
  894. if (isRecursively) {
  895. this.duplicateDescendantsWithStream(page, newPagePath, user);
  896. }
  897. // take over tags
  898. const originTags = await page.findRelatedTagsById();
  899. let savedTags = [];
  900. if (originTags != null) {
  901. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  902. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  903. this.tagEvent.emit('update', createdPage, savedTags);
  904. }
  905. const result = serializePageSecurely(createdPage);
  906. result.tags = savedTags;
  907. return result;
  908. }
  909. /**
  910. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  911. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  912. */
  913. private async duplicateTags(pageIdMapping) {
  914. const PageTagRelation = mongoose.model('PageTagRelation');
  915. // convert pageId from string to ObjectId
  916. const pageIds = Object.keys(pageIdMapping);
  917. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: new mongoose.Types.ObjectId(pageId) } }) };
  918. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  919. {
  920. $match: stage,
  921. },
  922. {
  923. $group: {
  924. _id: '$relatedTag',
  925. relatedPages: { $push: '$relatedPage' },
  926. },
  927. },
  928. ]);
  929. const newPageTagRelation: any[] = [];
  930. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  931. // relatedPages
  932. relatedPages.forEach((pageId) => {
  933. newPageTagRelation.push({
  934. relatedPage: pageIdMapping[pageId], // newPageId
  935. relatedTag: _id,
  936. });
  937. });
  938. });
  939. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  940. }
  941. private async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = true) {
  942. if (shouldUseV4Process) {
  943. return this.duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix);
  944. }
  945. const Page = this.crowi.model('Page');
  946. const Revision = this.crowi.model('Revision');
  947. const pageIds = pages.map(page => page._id);
  948. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  949. // Mapping to set to the body of the new revision
  950. const pageIdRevisionMapping = {};
  951. revisions.forEach((revision) => {
  952. pageIdRevisionMapping[revision.pageId] = revision;
  953. });
  954. // key: oldPageId, value: newPageId
  955. const pageIdMapping = {};
  956. const newPages: any[] = [];
  957. const newRevisions: any[] = [];
  958. // no need to save parent here
  959. pages.forEach((page) => {
  960. const newPageId = new mongoose.Types.ObjectId();
  961. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  962. const revisionId = new mongoose.Types.ObjectId();
  963. pageIdMapping[page._id] = newPageId;
  964. let newPage;
  965. if (!page.isEmpty) {
  966. newPage = {
  967. _id: newPageId,
  968. path: newPagePath,
  969. creator: user._id,
  970. grant: page.grant,
  971. grantedGroup: page.grantedGroup,
  972. grantedUsers: page.grantedUsers,
  973. lastUpdateUser: user._id,
  974. revision: revisionId,
  975. };
  976. newRevisions.push({
  977. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  978. });
  979. }
  980. newPages.push(newPage);
  981. });
  982. await Page.insertMany(newPages, { ordered: false });
  983. await Revision.insertMany(newRevisions, { ordered: false });
  984. await this.duplicateTags(pageIdMapping);
  985. }
  986. private async duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  987. const Page = this.crowi.model('Page');
  988. const Revision = this.crowi.model('Revision');
  989. const pageIds = pages.map(page => page._id);
  990. const revisions = await Revision.find({ pageId: { $in: pageIds } });
  991. // Mapping to set to the body of the new revision
  992. const pageIdRevisionMapping = {};
  993. revisions.forEach((revision) => {
  994. pageIdRevisionMapping[revision.pageId] = revision;
  995. });
  996. // key: oldPageId, value: newPageId
  997. const pageIdMapping = {};
  998. const newPages: any[] = [];
  999. const newRevisions: any[] = [];
  1000. pages.forEach((page) => {
  1001. const newPageId = new mongoose.Types.ObjectId();
  1002. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  1003. const revisionId = new mongoose.Types.ObjectId();
  1004. pageIdMapping[page._id] = newPageId;
  1005. newPages.push({
  1006. _id: newPageId,
  1007. path: newPagePath,
  1008. creator: user._id,
  1009. grant: page.grant,
  1010. grantedGroup: page.grantedGroup,
  1011. grantedUsers: page.grantedUsers,
  1012. lastUpdateUser: user._id,
  1013. revision: revisionId,
  1014. });
  1015. newRevisions.push({
  1016. _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
  1017. });
  1018. });
  1019. await Page.insertMany(newPages, { ordered: false });
  1020. await Revision.insertMany(newRevisions, { ordered: false });
  1021. await this.duplicateTags(pageIdMapping);
  1022. }
  1023. private async duplicateDescendantsWithStream(page, newPagePath, user, shouldUseV4Process = true) {
  1024. if (shouldUseV4Process) {
  1025. return this.duplicateDescendantsWithStreamV4(page, newPagePath, user);
  1026. }
  1027. const iterableFactory = new PageCursorsForDescendantsFactory(user, page, true);
  1028. const readStream = await iterableFactory.generateReadable();
  1029. const newPagePathPrefix = newPagePath;
  1030. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  1031. const duplicateDescendants = this.duplicateDescendants.bind(this);
  1032. const pageEvent = this.pageEvent;
  1033. let count = 0;
  1034. let nNonEmptyDuplicatedPages = 0;
  1035. const writeStream = new Writable({
  1036. objectMode: true,
  1037. async write(batch, encoding, callback) {
  1038. try {
  1039. count += batch.length;
  1040. nNonEmptyDuplicatedPages += batch.filter(page => !page.isEmpty).length;
  1041. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, shouldUseV4Process);
  1042. logger.debug(`Adding pages progressing: (count=${count})`);
  1043. }
  1044. catch (err) {
  1045. logger.error('addAllPages error on add anyway: ', err);
  1046. }
  1047. callback();
  1048. },
  1049. async final(callback) {
  1050. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1051. // update path
  1052. page.path = newPagePath;
  1053. pageEvent.emit('syncDescendantsUpdate', page, user);
  1054. callback();
  1055. },
  1056. });
  1057. readStream
  1058. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1059. .pipe(writeStream);
  1060. await streamToPromise(writeStream);
  1061. return nNonEmptyDuplicatedPages;
  1062. }
  1063. private async duplicateDescendantsWithStreamV4(page, newPagePath, user) {
  1064. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  1065. const newPagePathPrefix = newPagePath;
  1066. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  1067. const duplicateDescendants = this.duplicateDescendants.bind(this);
  1068. const pageEvent = this.pageEvent;
  1069. let count = 0;
  1070. const writeStream = new Writable({
  1071. objectMode: true,
  1072. async write(batch, encoding, callback) {
  1073. try {
  1074. count += batch.length;
  1075. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix);
  1076. logger.debug(`Adding pages progressing: (count=${count})`);
  1077. }
  1078. catch (err) {
  1079. logger.error('addAllPages error on add anyway: ', err);
  1080. }
  1081. callback();
  1082. },
  1083. final(callback) {
  1084. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1085. // update path
  1086. page.path = newPagePath;
  1087. pageEvent.emit('syncDescendantsUpdate', page, user);
  1088. callback();
  1089. },
  1090. });
  1091. readStream
  1092. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1093. .pipe(writeStream);
  1094. await streamToPromise(writeStream);
  1095. return count;
  1096. }
  1097. /*
  1098. * Delete
  1099. */
  1100. async deletePage(page, user, options = {}, isRecursively = false) {
  1101. /*
  1102. * Common Operation
  1103. */
  1104. const Page = mongoose.model('Page') as PageModel;
  1105. // Separate v4 & v5 process
  1106. const shouldUseV4Process = this.shouldUseV4Process(page);
  1107. if (shouldUseV4Process) {
  1108. return this.deletePageV4(page, user, options, isRecursively);
  1109. }
  1110. // Validate
  1111. if (page.isEmpty && !isRecursively) {
  1112. throw Error('Page not found.');
  1113. }
  1114. const isTrashed = isTrashPage(page.path);
  1115. if (isTrashed) {
  1116. throw new Error('This method does NOT support deleting trashed pages.');
  1117. }
  1118. if (!isMovablePage(page.path)) {
  1119. throw new Error('Page is not deletable.');
  1120. }
  1121. const newPath = Page.getDeletedPageName(page.path);
  1122. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1123. if (!canOperate) {
  1124. throw Error(`Cannot operate delete to path "${newPath}" right now.`);
  1125. }
  1126. // Replace with an empty page
  1127. const isChildrenExist = await Page.exists({ parent: page._id });
  1128. const shouldReplace = !isRecursively && isChildrenExist;
  1129. if (shouldReplace) {
  1130. await Page.replaceTargetWithPage(page, null, true);
  1131. }
  1132. // Delete target (only updating an existing document's properties )
  1133. let deletedPage;
  1134. if (!page.isEmpty) {
  1135. deletedPage = await this.deleteNonEmptyTarget(page, user);
  1136. }
  1137. else { // always recursive
  1138. deletedPage = page;
  1139. await this.deleteEmptyTarget(page);
  1140. }
  1141. // 1. Update descendantCount
  1142. if (isRecursively) {
  1143. const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
  1144. await this.updateDescendantCountOfAncestors(page.parent, inc, true);
  1145. }
  1146. else {
  1147. // update descendantCount of ancestors'
  1148. await this.updateDescendantCountOfAncestors(page.parent, -1, true);
  1149. }
  1150. // 2. Delete leaf empty pages
  1151. await Page.removeLeafEmptyPagesRecursively(page.parent);
  1152. if (isRecursively) {
  1153. let pageOp;
  1154. try {
  1155. pageOp = await PageOperation.create({
  1156. actionType: PageActionType.Delete,
  1157. actionStage: PageActionStage.Main,
  1158. page,
  1159. user,
  1160. fromPath: page.path,
  1161. toPath: newPath,
  1162. });
  1163. }
  1164. catch (err) {
  1165. logger.error('Failed to create PageOperation document.', err);
  1166. throw err;
  1167. }
  1168. /*
  1169. * Resumable Operation
  1170. */
  1171. this.deleteRecursivelyMainOperation(page, user, pageOp._id);
  1172. }
  1173. return deletedPage;
  1174. }
  1175. private async deleteNonEmptyTarget(page, user) {
  1176. const Page = mongoose.model('Page') as unknown as PageModel;
  1177. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  1178. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1179. const newPath = Page.getDeletedPageName(page.path);
  1180. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  1181. $set: {
  1182. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  1183. },
  1184. }, { new: true });
  1185. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  1186. try {
  1187. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  1188. }
  1189. catch (err) {
  1190. if (err.code !== 11000) {
  1191. throw err;
  1192. }
  1193. }
  1194. this.pageEvent.emit('delete', page, user);
  1195. this.pageEvent.emit('create', deletedPage, user);
  1196. return deletedPage;
  1197. }
  1198. private async deleteEmptyTarget(page): Promise<void> {
  1199. const Page = mongoose.model('Page') as unknown as PageModel;
  1200. await Page.deleteOne({ _id: page._id, isEmpty: true });
  1201. }
  1202. async deleteRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike): Promise<void> {
  1203. await this.deleteDescendantsWithStream(page, user, false);
  1204. await PageOperation.findByIdAndDelete(pageOpId);
  1205. // no sub operation available
  1206. }
  1207. private async deletePageV4(page, user, options = {}, isRecursively = false) {
  1208. const Page = mongoose.model('Page') as PageModel;
  1209. const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
  1210. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  1211. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1212. const newPath = Page.getDeletedPageName(page.path);
  1213. const isTrashed = isTrashPage(page.path);
  1214. if (isTrashed) {
  1215. throw new Error('This method does NOT support deleting trashed pages.');
  1216. }
  1217. if (!isMovablePage(page.path)) {
  1218. throw new Error('Page is not deletable.');
  1219. }
  1220. if (isRecursively) {
  1221. this.deleteDescendantsWithStream(page, user);
  1222. }
  1223. // update Revisions
  1224. await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
  1225. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  1226. $set: {
  1227. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  1228. },
  1229. }, { new: true });
  1230. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
  1231. try {
  1232. await PageRedirect.create({ fromPath: page.path, toPath: newPath });
  1233. }
  1234. catch (err) {
  1235. if (err.code !== 11000) {
  1236. throw err;
  1237. }
  1238. }
  1239. this.pageEvent.emit('delete', page, user);
  1240. this.pageEvent.emit('create', deletedPage, user);
  1241. return deletedPage;
  1242. }
  1243. private async deleteDescendants(pages, user) {
  1244. const Page = mongoose.model('Page') as unknown as PageModel;
  1245. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1246. const deletePageOperations: any[] = [];
  1247. const insertPageRedirectOperations: any[] = [];
  1248. pages.forEach((page) => {
  1249. const newPath = Page.getDeletedPageName(page.path);
  1250. let operation;
  1251. // if empty, delete completely
  1252. if (page.isEmpty) {
  1253. operation = {
  1254. deleteOne: {
  1255. filter: { _id: page._id },
  1256. },
  1257. };
  1258. }
  1259. // if not empty, set parent to null and update to trash
  1260. else {
  1261. operation = {
  1262. updateOne: {
  1263. filter: { _id: page._id },
  1264. update: {
  1265. $set: {
  1266. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
  1267. },
  1268. },
  1269. },
  1270. };
  1271. insertPageRedirectOperations.push({
  1272. insertOne: {
  1273. document: {
  1274. fromPath: page.path,
  1275. toPath: newPath,
  1276. },
  1277. },
  1278. });
  1279. }
  1280. deletePageOperations.push(operation);
  1281. });
  1282. try {
  1283. await Page.bulkWrite(deletePageOperations);
  1284. }
  1285. catch (err) {
  1286. if (err.code !== 11000) {
  1287. throw new Error(`Failed to delete pages: ${err}`);
  1288. }
  1289. }
  1290. finally {
  1291. this.pageEvent.emit('syncDescendantsDelete', pages, user);
  1292. }
  1293. try {
  1294. await PageRedirect.bulkWrite(insertPageRedirectOperations);
  1295. }
  1296. catch (err) {
  1297. if (err.code !== 11000) {
  1298. throw Error(`Failed to create PageRedirect documents: ${err}`);
  1299. }
  1300. }
  1301. }
  1302. /**
  1303. * Create delete stream and return deleted document count
  1304. */
  1305. private async deleteDescendantsWithStream(targetPage, user, shouldUseV4Process = true): Promise<number> {
  1306. let readStream;
  1307. if (shouldUseV4Process) {
  1308. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1309. }
  1310. else {
  1311. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1312. readStream = await factory.generateReadable();
  1313. }
  1314. const deleteDescendants = this.deleteDescendants.bind(this);
  1315. let count = 0;
  1316. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1317. const writeStream = new Writable({
  1318. objectMode: true,
  1319. async write(batch, encoding, callback) {
  1320. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1321. try {
  1322. count += batch.length;
  1323. await deleteDescendants(batch, user);
  1324. logger.debug(`Deleting pages progressing: (count=${count})`);
  1325. }
  1326. catch (err) {
  1327. logger.error('deleteDescendants error on add anyway: ', err);
  1328. }
  1329. callback();
  1330. },
  1331. final(callback) {
  1332. logger.debug(`Deleting pages has completed: (totalCount=${count})`);
  1333. callback();
  1334. },
  1335. });
  1336. readStream
  1337. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1338. .pipe(writeStream);
  1339. await streamToPromise(writeStream);
  1340. return nDeletedNonEmptyPages;
  1341. }
  1342. private async deleteCompletelyOperation(pageIds, pagePaths) {
  1343. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  1344. const Bookmark = this.crowi.model('Bookmark');
  1345. const Comment = this.crowi.model('Comment');
  1346. const Page = this.crowi.model('Page');
  1347. const PageTagRelation = this.crowi.model('PageTagRelation');
  1348. const ShareLink = this.crowi.model('ShareLink');
  1349. const Revision = this.crowi.model('Revision');
  1350. const Attachment = this.crowi.model('Attachment');
  1351. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1352. const { attachmentService } = this.crowi;
  1353. const attachments = await Attachment.find({ page: { $in: pageIds } });
  1354. return Promise.all([
  1355. Bookmark.deleteMany({ page: { $in: pageIds } }),
  1356. Comment.deleteMany({ page: { $in: pageIds } }),
  1357. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  1358. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  1359. Revision.deleteMany({ pageId: { $in: pageIds } }),
  1360. Page.deleteMany({ _id: { $in: pageIds } }),
  1361. PageRedirect.deleteMany({ $or: [{ fromPath: { $in: pagePaths } }, { toPath: { $in: pagePaths } }] }),
  1362. attachmentService.removeAllAttachments(attachments),
  1363. ]);
  1364. }
  1365. // delete multiple pages
  1366. private async deleteMultipleCompletely(pages, user, options = {}) {
  1367. const ids = pages.map(page => (page._id));
  1368. const paths = pages.map(page => (page.path));
  1369. logger.debug('Deleting completely', paths);
  1370. await this.deleteCompletelyOperation(ids, paths);
  1371. this.pageEvent.emit('syncDescendantsDelete', pages, user); // update as renamed page
  1372. return;
  1373. }
  1374. async deleteCompletely(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  1375. /*
  1376. * Common Operation
  1377. */
  1378. const Page = mongoose.model('Page') as PageModel;
  1379. if (isTopPage(page.path)) {
  1380. throw Error('It is forbidden to delete the top page');
  1381. }
  1382. if (page.isEmpty && !isRecursively) {
  1383. throw Error('Page not found.');
  1384. }
  1385. // v4 compatible process
  1386. const shouldUseV4Process = this.shouldUseV4Process(page);
  1387. if (shouldUseV4Process) {
  1388. return this.deleteCompletelyV4(page, user, options, isRecursively, preventEmitting);
  1389. }
  1390. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, null);
  1391. if (!canOperate) {
  1392. throw Error(`Cannot operate deleteCompletely from path "${page.path}" right now.`);
  1393. }
  1394. const ids = [page._id];
  1395. const paths = [page.path];
  1396. logger.debug('Deleting completely', paths);
  1397. // 1. update descendantCount
  1398. if (isRecursively) {
  1399. const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
  1400. await this.updateDescendantCountOfAncestors(page.parent, inc, true);
  1401. }
  1402. else {
  1403. // replace with an empty page
  1404. const shouldReplace = await Page.exists({ parent: page._id });
  1405. let pageToUpdateDescendantCount = page;
  1406. if (shouldReplace) {
  1407. pageToUpdateDescendantCount = await Page.replaceTargetWithPage(page);
  1408. }
  1409. await this.updateDescendantCountOfAncestors(pageToUpdateDescendantCount.parent, -1, true);
  1410. }
  1411. // 2. then delete target completely
  1412. await this.deleteCompletelyOperation(ids, paths);
  1413. // delete leaf empty pages
  1414. await Page.removeLeafEmptyPagesRecursively(page.parent);
  1415. if (!page.isEmpty && !preventEmitting) {
  1416. this.pageEvent.emit('deleteCompletely', page, user);
  1417. }
  1418. if (isRecursively) {
  1419. let pageOp;
  1420. try {
  1421. pageOp = await PageOperation.create({
  1422. actionType: PageActionType.DeleteCompletely,
  1423. actionStage: PageActionStage.Main,
  1424. page,
  1425. user,
  1426. fromPath: page.path,
  1427. options,
  1428. });
  1429. }
  1430. catch (err) {
  1431. logger.error('Failed to create PageOperation document.', err);
  1432. throw err;
  1433. }
  1434. /*
  1435. * Main Operation
  1436. */
  1437. this.deleteCompletelyRecursivelyMainOperation(page, user, options, pageOp._id);
  1438. }
  1439. return;
  1440. }
  1441. async deleteCompletelyRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike): Promise<void> {
  1442. await this.deleteCompletelyDescendantsWithStream(page, user, options, false);
  1443. await PageOperation.findByIdAndDelete(pageOpId);
  1444. // no sub operation available
  1445. }
  1446. private async deleteCompletelyV4(page, user, options = {}, isRecursively = false, preventEmitting = false) {
  1447. const ids = [page._id];
  1448. const paths = [page.path];
  1449. logger.debug('Deleting completely', paths);
  1450. await this.deleteCompletelyOperation(ids, paths);
  1451. if (isRecursively) {
  1452. this.deleteCompletelyDescendantsWithStream(page, user, options);
  1453. }
  1454. if (!page.isEmpty && !preventEmitting) {
  1455. this.pageEvent.emit('deleteCompletely', page, user);
  1456. }
  1457. return;
  1458. }
  1459. async emptyTrashPage(user, options = {}) {
  1460. return this.deleteCompletelyDescendantsWithStream({ path: '/trash' }, user, options);
  1461. }
  1462. /**
  1463. * Create delete completely stream
  1464. */
  1465. private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true): Promise<number> {
  1466. let readStream;
  1467. if (shouldUseV4Process) { // pages don't have parents
  1468. readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1469. }
  1470. else {
  1471. const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
  1472. readStream = await factory.generateReadable();
  1473. }
  1474. let count = 0;
  1475. let nDeletedNonEmptyPages = 0; // used for updating descendantCount
  1476. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  1477. const writeStream = new Writable({
  1478. objectMode: true,
  1479. async write(batch, encoding, callback) {
  1480. nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
  1481. try {
  1482. count += batch.length;
  1483. await deleteMultipleCompletely(batch, user, options);
  1484. logger.debug(`Adding pages progressing: (count=${count})`);
  1485. }
  1486. catch (err) {
  1487. logger.error('addAllPages error on add anyway: ', err);
  1488. }
  1489. callback();
  1490. },
  1491. final(callback) {
  1492. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  1493. callback();
  1494. },
  1495. });
  1496. readStream
  1497. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1498. .pipe(writeStream);
  1499. await streamToPromise(writeStream);
  1500. return nDeletedNonEmptyPages;
  1501. }
  1502. // no need to separate Main Sub since it is devided into single page operations
  1503. async deleteMultiplePages(pagesToDelete, user, options): Promise<void> {
  1504. const { isRecursively, isCompletely } = options;
  1505. if (pagesToDelete.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1506. throw Error(`The maximum number of pages is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1507. }
  1508. // omit duplicate paths if isRecursively true, omit empty pages if isRecursively false
  1509. const pages = isRecursively ? omitDuplicateAreaPageFromPages(pagesToDelete) : pagesToDelete.filter(p => !p.isEmpty);
  1510. if (isCompletely) {
  1511. for await (const page of pages) {
  1512. await this.deleteCompletely(page, user, {}, isRecursively);
  1513. }
  1514. }
  1515. else {
  1516. for await (const page of pages) {
  1517. await this.deletePage(page, user, {}, isRecursively);
  1518. }
  1519. }
  1520. }
  1521. // use the same process in both v4 and v5
  1522. private async revertDeletedDescendants(pages, user) {
  1523. const Page = this.crowi.model('Page');
  1524. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  1525. const revertPageOperations: any[] = [];
  1526. const fromPathsToDelete: string[] = [];
  1527. pages.forEach((page) => {
  1528. // e.g. page.path = /trash/test, toPath = /test
  1529. const toPath = Page.getRevertDeletedPageName(page.path);
  1530. revertPageOperations.push({
  1531. updateOne: {
  1532. filter: { _id: page._id },
  1533. update: {
  1534. $set: {
  1535. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1536. },
  1537. },
  1538. },
  1539. });
  1540. fromPathsToDelete.push(page.path);
  1541. });
  1542. try {
  1543. await Page.bulkWrite(revertPageOperations);
  1544. await PageRedirect.deleteMany({ fromPath: { $in: fromPathsToDelete } });
  1545. }
  1546. catch (err) {
  1547. if (err.code !== 11000) {
  1548. throw new Error(`Failed to revert pages: ${err}`);
  1549. }
  1550. }
  1551. }
  1552. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  1553. /*
  1554. * Common Operation
  1555. */
  1556. const Page = this.crowi.model('Page');
  1557. const PageTagRelation = this.crowi.model('PageTagRelation');
  1558. // 1. Separate v4 & v5 process
  1559. const shouldUseV4Process = this.shouldUseV4ProcessForRevert(page);
  1560. if (shouldUseV4Process) {
  1561. return this.revertDeletedPageV4(page, user, options, isRecursively);
  1562. }
  1563. const newPath = Page.getRevertDeletedPageName(page.path);
  1564. const canOperate = await this.crowi.pageOperationService.canOperate(isRecursively, page.path, newPath);
  1565. if (!canOperate) {
  1566. throw Error(`Cannot operate revert from path "${page.path}" right now.`);
  1567. }
  1568. const includeEmpty = true;
  1569. const originPage = await Page.findByPath(newPath, includeEmpty);
  1570. // throw if any page already exists
  1571. if (originPage != null) {
  1572. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1573. }
  1574. // 2. Revert target
  1575. const parent = await Page.getParentAndFillAncestors(newPath, user);
  1576. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1577. $set: {
  1578. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null, parent: parent._id, descendantCount: 0,
  1579. },
  1580. }, { new: true });
  1581. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1582. this.pageEvent.emit('revert', page, user);
  1583. if (!isRecursively) {
  1584. await this.updateDescendantCountOfAncestors(parent._id, 1, true);
  1585. }
  1586. else {
  1587. let pageOp;
  1588. try {
  1589. pageOp = await PageOperation.create({
  1590. actionType: PageActionType.Revert,
  1591. actionStage: PageActionStage.Main,
  1592. page,
  1593. user,
  1594. fromPath: page.path,
  1595. toPath: newPath,
  1596. options,
  1597. });
  1598. }
  1599. catch (err) {
  1600. logger.error('Failed to create PageOperation document.', err);
  1601. throw err;
  1602. }
  1603. /*
  1604. * Resumable Operation
  1605. */
  1606. this.revertRecursivelyMainOperation(page, user, options, pageOp._id);
  1607. }
  1608. return updatedPage;
  1609. }
  1610. async revertRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike): Promise<void> {
  1611. const Page = mongoose.model('Page') as unknown as PageModel;
  1612. await this.revertDeletedDescendantsWithStream(page, user, options, false);
  1613. const newPath = Page.getRevertDeletedPageName(page.path);
  1614. // normalize parent of descendant pages
  1615. const shouldNormalize = this.shouldNormalizeParent(page);
  1616. if (shouldNormalize) {
  1617. try {
  1618. await this.normalizeParentAndDescendantCountOfDescendants(newPath, user);
  1619. logger.info(`Successfully normalized reverted descendant pages under "${newPath}"`);
  1620. }
  1621. catch (err) {
  1622. logger.error('Failed to normalize descendants afrer revert:', err);
  1623. throw err;
  1624. }
  1625. }
  1626. // Set to Sub
  1627. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  1628. if (pageOp == null) {
  1629. throw Error('PageOperation document not found');
  1630. }
  1631. /*
  1632. * Sub Operation
  1633. */
  1634. await this.revertRecursivelySubOperation(newPath, pageOp._id);
  1635. }
  1636. async revertRecursivelySubOperation(newPath: string, pageOpId: ObjectIdLike): Promise<void> {
  1637. const Page = mongoose.model('Page') as unknown as PageModel;
  1638. const newTarget = await Page.findOne({ path: newPath }); // only one page will be found since duplicating to existing path is forbidden
  1639. if (newTarget == null) {
  1640. throw Error('No reverted page found. Something might have gone wrong in revertRecursivelyMainOperation.');
  1641. }
  1642. // update descendantCount of ancestors'
  1643. await this.updateDescendantCountOfAncestors(newTarget.parent as ObjectIdLike, newTarget.descendantCount + 1, true);
  1644. await PageOperation.findByIdAndDelete(pageOpId);
  1645. }
  1646. private async revertDeletedPageV4(page, user, options = {}, isRecursively = false) {
  1647. const Page = this.crowi.model('Page');
  1648. const PageTagRelation = this.crowi.model('PageTagRelation');
  1649. const newPath = Page.getRevertDeletedPageName(page.path);
  1650. const originPage = await Page.findByPath(newPath);
  1651. if (originPage != null) {
  1652. throw new PathAlreadyExistsError('already_exists', originPage.path);
  1653. }
  1654. if (isRecursively) {
  1655. this.revertDeletedDescendantsWithStream(page, user, options);
  1656. }
  1657. page.status = Page.STATUS_PUBLISHED;
  1658. page.lastUpdateUser = user;
  1659. debug('Revert deleted the page', page, newPath);
  1660. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  1661. $set: {
  1662. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  1663. },
  1664. }, { new: true });
  1665. await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
  1666. this.pageEvent.emit('revert', page, user);
  1667. return updatedPage;
  1668. }
  1669. /**
  1670. * Create revert stream
  1671. */
  1672. private async revertDeletedDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true): Promise<number> {
  1673. if (shouldUseV4Process) {
  1674. return this.revertDeletedDescendantsWithStreamV4(targetPage, user, options);
  1675. }
  1676. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1677. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1678. let count = 0;
  1679. const writeStream = new Writable({
  1680. objectMode: true,
  1681. async write(batch, encoding, callback) {
  1682. try {
  1683. count += batch.length;
  1684. await revertDeletedDescendants(batch, user);
  1685. logger.debug(`Reverting pages progressing: (count=${count})`);
  1686. }
  1687. catch (err) {
  1688. logger.error('revertPages error on add anyway: ', err);
  1689. }
  1690. callback();
  1691. },
  1692. async final(callback) {
  1693. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1694. callback();
  1695. },
  1696. });
  1697. readStream
  1698. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1699. .pipe(writeStream);
  1700. await streamToPromise(writeStream);
  1701. return count;
  1702. }
  1703. private async revertDeletedDescendantsWithStreamV4(targetPage, user, options = {}) {
  1704. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  1705. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  1706. let count = 0;
  1707. const writeStream = new Writable({
  1708. objectMode: true,
  1709. async write(batch, encoding, callback) {
  1710. try {
  1711. count += batch.length;
  1712. await revertDeletedDescendants(batch, user);
  1713. logger.debug(`Reverting pages progressing: (count=${count})`);
  1714. }
  1715. catch (err) {
  1716. logger.error('revertPages error on add anyway: ', err);
  1717. }
  1718. callback();
  1719. },
  1720. final(callback) {
  1721. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  1722. callback();
  1723. },
  1724. });
  1725. readStream
  1726. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  1727. .pipe(writeStream);
  1728. await streamToPromise(readStream);
  1729. return count;
  1730. }
  1731. async handlePrivatePagesForGroupsToDelete(groupsToDelete, action, transferToUserGroupId, user) {
  1732. const Page = this.crowi.model('Page');
  1733. const pages = await Page.find({ grantedGroup: { $in: groupsToDelete } });
  1734. switch (action) {
  1735. case 'public':
  1736. await Page.publicizePages(pages);
  1737. break;
  1738. case 'delete':
  1739. return this.deleteMultipleCompletely(pages, user);
  1740. case 'transfer':
  1741. await Page.transferPagesToGroup(pages, transferToUserGroupId);
  1742. break;
  1743. default:
  1744. throw new Error('Unknown action for private pages');
  1745. }
  1746. }
  1747. private extractStringIds(refs: Ref<HasObjectId>[]) {
  1748. return refs.map((ref: Ref<HasObjectId>) => {
  1749. return (typeof ref === 'string') ? ref : ref._id.toString();
  1750. });
  1751. }
  1752. constructBasicPageInfo(page: IPage, isGuestUser?: boolean): IPageInfo | IPageInfoForEntity {
  1753. const isMovable = isGuestUser ? false : isMovablePage(page.path);
  1754. if (page.isEmpty) {
  1755. return {
  1756. isV5Compatible: true,
  1757. isEmpty: true,
  1758. isMovable,
  1759. isDeletable: true,
  1760. isAbleToDeleteCompletely: true,
  1761. isRevertible: false,
  1762. };
  1763. }
  1764. const likers = page.liker.slice(0, 15) as Ref<IUserHasId>[];
  1765. const seenUsers = page.seenUsers.slice(0, 15) as Ref<IUserHasId>[];
  1766. return {
  1767. isV5Compatible: isTopPage(page.path) || page.parent != null,
  1768. isEmpty: false,
  1769. sumOfLikers: page.liker.length,
  1770. likerIds: this.extractStringIds(likers),
  1771. seenUserIds: this.extractStringIds(seenUsers),
  1772. sumOfSeenUsers: page.seenUsers.length,
  1773. isMovable,
  1774. isDeletable: isMovable,
  1775. isAbleToDeleteCompletely: false,
  1776. isRevertible: isTrashPage(page.path),
  1777. };
  1778. }
  1779. async shortBodiesMapByPageIds(pageIds: ObjectId[] = [], user): Promise<Record<string, string | null>> {
  1780. const Page = mongoose.model('Page') as unknown as PageModel;
  1781. const MAX_LENGTH = 350;
  1782. // aggregation options
  1783. let userGroups;
  1784. if (user != null && userGroups == null) {
  1785. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // Typescriptize model
  1786. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  1787. }
  1788. const viewerCondition = Page.generateGrantCondition(user, userGroups);
  1789. const filterByIds = {
  1790. _id: { $in: pageIds },
  1791. };
  1792. let pages;
  1793. try {
  1794. pages = await Page
  1795. .aggregate([
  1796. // filter by pageIds
  1797. {
  1798. $match: filterByIds,
  1799. },
  1800. // filter by viewer
  1801. {
  1802. $match: viewerCondition,
  1803. },
  1804. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  1805. {
  1806. $lookup: {
  1807. from: 'revisions',
  1808. let: { localRevision: '$revision' },
  1809. pipeline: [
  1810. {
  1811. $match: {
  1812. $expr: {
  1813. $eq: ['$_id', '$$localRevision'],
  1814. },
  1815. },
  1816. },
  1817. {
  1818. $project: {
  1819. // What is $substrCP?
  1820. // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
  1821. revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
  1822. },
  1823. },
  1824. ],
  1825. as: 'revisionData',
  1826. },
  1827. },
  1828. // projection
  1829. {
  1830. $project: {
  1831. _id: 1,
  1832. revisionData: 1,
  1833. },
  1834. },
  1835. ]).exec();
  1836. }
  1837. catch (err) {
  1838. logger.error('Error occurred while generating shortBodiesMap');
  1839. throw err;
  1840. }
  1841. const shortBodiesMap = {};
  1842. pages.forEach((page) => {
  1843. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  1844. });
  1845. return shortBodiesMap;
  1846. }
  1847. private async createAndSendNotifications(page, user, action) {
  1848. const { activityService, inAppNotificationService } = this.crowi;
  1849. const snapshot = stringifySnapshot(page);
  1850. // Create activity
  1851. const parameters = {
  1852. user: user._id,
  1853. targetModel: SUPPORTED_TARGET_MODEL_TYPE.MODEL_PAGE,
  1854. target: page,
  1855. action,
  1856. };
  1857. const activity = await activityService.createByParameters(parameters);
  1858. // Get user to be notified
  1859. const targetUsers = await activity.getNotificationTargetUsers();
  1860. // Create and send notifications
  1861. await inAppNotificationService.upsertByActivity(targetUsers, activity, snapshot);
  1862. await inAppNotificationService.emitSocketIo(targetUsers);
  1863. }
  1864. async normalizeParentByPath(path: string, user): Promise<void> {
  1865. const Page = mongoose.model('Page') as unknown as PageModel;
  1866. const pages = await Page.findByPathAndViewer(path, user, null, false);
  1867. if (pages == null || !Array.isArray(pages)) {
  1868. throw Error('Something went wrong while converting pages.');
  1869. }
  1870. if (pages.length === 0) {
  1871. throw new V5ConversionError(`Could not find the page "${path}" to convert.`, V5ConversionErrCode.PAGE_NOT_FOUND);
  1872. }
  1873. if (pages.length > 1) {
  1874. throw new V5ConversionError(
  1875. `There are more than two pages at the path "${path}". Please rename or delete the page first.`,
  1876. V5ConversionErrCode.DUPLICATE_PAGES_FOUND,
  1877. );
  1878. }
  1879. const page = pages[0];
  1880. const {
  1881. grant, grantedUsers: grantedUserIds, grantedGroup: grantedGroupId,
  1882. } = page;
  1883. /*
  1884. * UserGroup & Owner validation
  1885. */
  1886. let isGrantNormalized = false;
  1887. try {
  1888. const shouldCheckDescendants = true;
  1889. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  1890. }
  1891. catch (err) {
  1892. logger.error(`Failed to validate grant of page at "${path}"`, err);
  1893. throw err;
  1894. }
  1895. if (!isGrantNormalized) {
  1896. throw new V5ConversionError(
  1897. 'This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.',
  1898. V5ConversionErrCode.GRANT_INVALID,
  1899. );
  1900. }
  1901. let pageOp;
  1902. try {
  1903. pageOp = await PageOperation.create({
  1904. actionType: PageActionType.NormalizeParent,
  1905. actionStage: PageActionStage.Main,
  1906. page,
  1907. user,
  1908. fromPath: page.path,
  1909. toPath: page.path,
  1910. });
  1911. }
  1912. catch (err) {
  1913. logger.error('Failed to create PageOperation document.', err);
  1914. throw err;
  1915. }
  1916. // no await
  1917. this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  1918. }
  1919. async normalizeParentByPageIdsRecursively(pageIds: ObjectIdLike[], user): Promise<void> {
  1920. const Page = mongoose.model('Page') as unknown as PageModel;
  1921. const pages = await Page.findByIdsAndViewer(pageIds, user, null);
  1922. if (pages == null || pages.length === 0) {
  1923. throw Error('pageIds is null or 0 length.');
  1924. }
  1925. if (pages.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
  1926. throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
  1927. }
  1928. this.normalizeParentRecursivelyByPages(pages, user);
  1929. return;
  1930. }
  1931. async normalizeParentByPageIds(pageIds: ObjectIdLike[], user): Promise<void> {
  1932. const Page = await mongoose.model('Page') as unknown as PageModel;
  1933. const socket = this.crowi.socketIoService.getDefaultSocket();
  1934. for await (const pageId of pageIds) {
  1935. const page = await Page.findById(pageId);
  1936. if (page == null) {
  1937. continue;
  1938. }
  1939. const errorData: PageMigrationErrorData = { paths: [page.path] };
  1940. try {
  1941. const canOperate = await this.crowi.pageOperationService.canOperate(false, page.path, page.path);
  1942. if (!canOperate) {
  1943. throw Error(`Cannot operate normalizeParent to path "${page.path}" right now.`);
  1944. }
  1945. const normalizedPage = await this.normalizeParentByPage(page, user);
  1946. if (normalizedPage == null) {
  1947. socket.emit(SocketEventName.PageMigrationError, errorData);
  1948. logger.error(`Failed to update descendantCount of page of id: "${pageId}"`);
  1949. }
  1950. }
  1951. catch (err) {
  1952. socket.emit(SocketEventName.PageMigrationError, errorData);
  1953. logger.error('Something went wrong while normalizing parent.', err);
  1954. }
  1955. }
  1956. socket.emit(SocketEventName.PageMigrationSuccess);
  1957. }
  1958. private async normalizeParentByPage(page, user) {
  1959. const Page = mongoose.model('Page') as unknown as PageModel;
  1960. const {
  1961. path, grant, grantedUsers: grantedUserIds, grantedGroup: grantedGroupId,
  1962. } = page;
  1963. // check if any page exists at target path already
  1964. const existingPage = await Page.findOne({ path, parent: { $ne: null } });
  1965. if (existingPage != null && !existingPage.isEmpty) {
  1966. throw Error('Page already exists. Please rename the page to continue.');
  1967. }
  1968. /*
  1969. * UserGroup & Owner validation
  1970. */
  1971. if (grant !== Page.GRANT_RESTRICTED) {
  1972. let isGrantNormalized = false;
  1973. try {
  1974. const shouldCheckDescendants = true;
  1975. isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(user, path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
  1976. }
  1977. catch (err) {
  1978. logger.error(`Failed to validate grant of page at "${path}"`, err);
  1979. throw err;
  1980. }
  1981. if (!isGrantNormalized) {
  1982. throw Error('This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.');
  1983. }
  1984. }
  1985. else {
  1986. throw Error('Restricted pages can not be migrated');
  1987. }
  1988. let normalizedPage;
  1989. // replace if empty page exists
  1990. if (existingPage != null && existingPage.isEmpty) {
  1991. // Inherit descendantCount from the empty page
  1992. const updatedPage = await Page.findOneAndUpdate({ _id: page._id }, { descendantCount: existingPage.descendantCount }, { new: true });
  1993. await Page.replaceTargetWithPage(existingPage, updatedPage, true);
  1994. normalizedPage = await Page.findById(page._id);
  1995. }
  1996. else {
  1997. const parent = await Page.getParentAndFillAncestors(page.path, user);
  1998. normalizedPage = await Page.findOneAndUpdate({ _id: page._id }, { parent: parent._id }, { new: true });
  1999. }
  2000. // Update descendantCount
  2001. const inc = 1;
  2002. await this.updateDescendantCountOfAncestors(normalizedPage.parent, inc, true);
  2003. return normalizedPage;
  2004. }
  2005. async normalizeParentRecursivelyByPages(pages, user): Promise<void> {
  2006. /*
  2007. * Main Operation
  2008. */
  2009. const socket = this.crowi.socketIoService.getDefaultSocket();
  2010. const pagesToNormalize = omitDuplicateAreaPageFromPages(pages);
  2011. let normalizablePages;
  2012. let nonNormalizablePages;
  2013. try {
  2014. [normalizablePages, nonNormalizablePages] = await this.crowi.pageGrantService.separateNormalizableAndNotNormalizablePages(user, pagesToNormalize);
  2015. }
  2016. catch (err) {
  2017. socket.emit(SocketEventName.PageMigrationError);
  2018. throw err;
  2019. }
  2020. if (normalizablePages.length === 0) {
  2021. socket.emit(SocketEventName.PageMigrationError);
  2022. return;
  2023. }
  2024. if (nonNormalizablePages.length !== 0) {
  2025. const nonNormalizablePagePaths: string[] = nonNormalizablePages.map(p => p.path);
  2026. socket.emit(SocketEventName.PageMigrationError, { paths: nonNormalizablePagePaths });
  2027. logger.debug('Some pages could not be converted.', nonNormalizablePagePaths);
  2028. }
  2029. /*
  2030. * Main Operation (s)
  2031. */
  2032. const errorPagePaths: string[] = [];
  2033. for await (const page of normalizablePages) {
  2034. const canOperate = await this.crowi.pageOperationService.canOperate(true, page.path, page.path);
  2035. if (!canOperate) {
  2036. errorPagePaths.push(page.path);
  2037. throw Error(`Cannot operate normalizeParentRecursiively to path "${page.path}" right now.`);
  2038. }
  2039. const Page = mongoose.model('Page') as unknown as PageModel;
  2040. const { PageQueryBuilder } = Page;
  2041. const builder = new PageQueryBuilder(Page.findOne());
  2042. builder.addConditionAsMigrated();
  2043. builder.addConditionToListByPathsArray([page.path]);
  2044. const existingPage = await builder.query.exec();
  2045. if (existingPage?.parent != null) {
  2046. errorPagePaths.push(page.path);
  2047. throw Error('This page has already converted.');
  2048. }
  2049. let pageOp;
  2050. try {
  2051. pageOp = await PageOperation.create({
  2052. actionType: PageActionType.NormalizeParent,
  2053. actionStage: PageActionStage.Main,
  2054. page,
  2055. user,
  2056. fromPath: page.path,
  2057. toPath: page.path,
  2058. });
  2059. }
  2060. catch (err) {
  2061. errorPagePaths.push(page.path);
  2062. logger.error('Failed to create PageOperation document.', err);
  2063. throw err;
  2064. }
  2065. try {
  2066. await this.normalizeParentRecursivelyMainOperation(page, user, pageOp._id);
  2067. }
  2068. catch (err) {
  2069. errorPagePaths.push(page.path);
  2070. logger.err('Failed to run normalizeParentRecursivelyMainOperation.', err);
  2071. throw err;
  2072. }
  2073. }
  2074. if (errorPagePaths.length === 0) {
  2075. socket.emit(SocketEventName.PageMigrationSuccess);
  2076. }
  2077. else {
  2078. socket.emit(SocketEventName.PageMigrationError, { paths: errorPagePaths });
  2079. }
  2080. }
  2081. async normalizeParentRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike): Promise<void> {
  2082. // Save prevDescendantCount for sub-operation
  2083. const Page = mongoose.model('Page') as unknown as PageModel;
  2084. const { PageQueryBuilder } = Page;
  2085. const builder = new PageQueryBuilder(Page.findOne(), true);
  2086. builder.addConditionAsMigrated();
  2087. builder.addConditionToListByPathsArray([page.path]);
  2088. const exPage = await builder.query.exec();
  2089. const options = { prevDescendantCount: exPage?.descendantCount ?? 0 };
  2090. try {
  2091. await this.normalizeParentRecursively([page.path], user);
  2092. }
  2093. catch (err) {
  2094. logger.error('V5 initial miration failed.', err);
  2095. // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
  2096. throw err;
  2097. }
  2098. // Set to Sub
  2099. const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
  2100. if (pageOp == null) {
  2101. throw Error('PageOperation document not found');
  2102. }
  2103. await this.normalizeParentRecursivelySubOperation(page, user, pageOp._id, options);
  2104. }
  2105. async normalizeParentRecursivelySubOperation(page, user, pageOpId: ObjectIdLike, options: {prevDescendantCount: number}): Promise<void> {
  2106. const Page = mongoose.model('Page') as unknown as PageModel;
  2107. try {
  2108. // update descendantCount of self and descendant pages first
  2109. await this.updateDescendantCountOfSelfAndDescendants(page.path);
  2110. // find pages again to get updated descendantCount
  2111. // then calculate inc
  2112. const pageAfterUpdatingDescendantCount = await Page.findByIdAndViewer(page._id, user);
  2113. if (pageAfterUpdatingDescendantCount == null) {
  2114. throw Error('Page not found after updating descendantCount');
  2115. }
  2116. const { prevDescendantCount } = options;
  2117. const newDescendantCount = pageAfterUpdatingDescendantCount.descendantCount;
  2118. let inc = newDescendantCount - prevDescendantCount;
  2119. const isAlreadyConverted = page.parent != null;
  2120. if (!isAlreadyConverted) {
  2121. inc += 1;
  2122. }
  2123. await this.updateDescendantCountOfAncestors(page._id, inc, false);
  2124. }
  2125. catch (err) {
  2126. logger.error('Failed to update descendantCount after normalizing parent:', err);
  2127. throw Error(`Failed to update descendantCount after normalizing parent: ${err}`);
  2128. }
  2129. await PageOperation.findByIdAndDelete(pageOpId);
  2130. }
  2131. async _isPagePathIndexUnique() {
  2132. const Page = this.crowi.model('Page');
  2133. const now = (new Date()).toString();
  2134. const path = `growi_check_is_path_index_unique_${now}`;
  2135. let isUnique = false;
  2136. try {
  2137. await Page.insertMany([
  2138. { path },
  2139. { path },
  2140. ]);
  2141. }
  2142. catch (err) {
  2143. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  2144. isUnique = true;
  2145. logger.info('Page path index is unique.');
  2146. }
  2147. else {
  2148. throw err;
  2149. }
  2150. }
  2151. finally {
  2152. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  2153. }
  2154. return isUnique;
  2155. }
  2156. // TODO: use socket to send status to the client
  2157. async normalizeAllPublicPages() {
  2158. // const socket = this.crowi.socketIoService.getAdminSocket();
  2159. let isUnique;
  2160. try {
  2161. isUnique = await this._isPagePathIndexUnique();
  2162. }
  2163. catch (err) {
  2164. logger.error('Failed to check path index status', err);
  2165. throw err;
  2166. }
  2167. // drop unique index first
  2168. if (isUnique) {
  2169. try {
  2170. await this._v5NormalizeIndex();
  2171. }
  2172. catch (err) {
  2173. logger.error('V5 index normalization failed.', err);
  2174. // socket.emit('v5IndexNormalizationFailed', { error: err.message });
  2175. throw err;
  2176. }
  2177. }
  2178. // then migrate
  2179. try {
  2180. await this.normalizeParentRecursively(['/'], null);
  2181. }
  2182. catch (err) {
  2183. logger.error('V5 initial miration failed.', err);
  2184. // socket.emit('v5InitialMirationFailed', { error: err.message });
  2185. throw err;
  2186. }
  2187. // update descendantCount of all public pages
  2188. try {
  2189. await this.updateDescendantCountOfSelfAndDescendants('/');
  2190. logger.info('Successfully updated all descendantCount of public pages.');
  2191. }
  2192. catch (err) {
  2193. logger.error('Failed updating descendantCount of public pages.', err);
  2194. throw err;
  2195. }
  2196. await this._setIsV5CompatibleTrue();
  2197. }
  2198. private async _setIsV5CompatibleTrue() {
  2199. try {
  2200. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  2201. 'app:isV5Compatible': true,
  2202. });
  2203. logger.info('Successfully migrated all public pages.');
  2204. }
  2205. catch (err) {
  2206. logger.warn('Failed to update app:isV5Compatible to true.');
  2207. throw err;
  2208. }
  2209. }
  2210. private async normalizeParentAndDescendantCountOfDescendants(path: string, user): Promise<void> {
  2211. await this.normalizeParentRecursively([path], user);
  2212. // update descendantCount of descendant pages
  2213. await this.updateDescendantCountOfSelfAndDescendants(path);
  2214. }
  2215. /**
  2216. * Normalize parent attribute by passing paths and user.
  2217. * @param paths Pages under this paths value will be updated.
  2218. * @param user To be used to filter pages to update. If null, only public pages will be updated.
  2219. * @returns Promise<void>
  2220. */
  2221. async normalizeParentRecursively(paths: string[], user: any | null): Promise<void> {
  2222. const Page = mongoose.model('Page') as unknown as PageModel;
  2223. const ancestorPaths = paths.flatMap(p => collectAncestorPaths(p, []));
  2224. // targets' descendants
  2225. const pathAndRegExpsToNormalize: (RegExp | string)[] = paths
  2226. .map(p => new RegExp(`^${escapeStringRegexp(addTrailingSlash(p))}`, 'i'));
  2227. // include targets' path
  2228. pathAndRegExpsToNormalize.push(...paths);
  2229. // determine UserGroup condition
  2230. let userGroups = null;
  2231. if (user != null) {
  2232. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model
  2233. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  2234. }
  2235. const grantFiltersByUser: { $or: any[] } = Page.generateGrantCondition(user, userGroups);
  2236. return this._normalizeParentRecursively(pathAndRegExpsToNormalize, ancestorPaths, grantFiltersByUser, user);
  2237. }
  2238. private buildFilterForNormalizeParentRecursively(pathOrRegExps: (RegExp | string)[], publicPathsToNormalize: string[], grantFiltersByUser: { $or: any[] }) {
  2239. const Page = mongoose.model('Page') as unknown as PageModel;
  2240. const andFilter: any = {
  2241. $and: [
  2242. {
  2243. parent: null,
  2244. status: Page.STATUS_PUBLISHED,
  2245. path: { $ne: '/' },
  2246. },
  2247. ],
  2248. };
  2249. const orFilter: any = { $or: [] };
  2250. // specified pathOrRegExps
  2251. if (pathOrRegExps.length > 0) {
  2252. orFilter.$or.push(
  2253. {
  2254. path: { $in: pathOrRegExps },
  2255. },
  2256. );
  2257. }
  2258. // not specified but ancestors of specified pathOrRegExps
  2259. if (publicPathsToNormalize.length > 0) {
  2260. orFilter.$or.push(
  2261. {
  2262. path: { $in: publicPathsToNormalize },
  2263. grant: Page.GRANT_PUBLIC, // use only public pages to complete the tree
  2264. },
  2265. );
  2266. }
  2267. // Merge filters
  2268. const mergedFilter = {
  2269. $and: [
  2270. { $and: [grantFiltersByUser, ...andFilter.$and] },
  2271. { $or: orFilter.$or },
  2272. ],
  2273. };
  2274. return mergedFilter;
  2275. }
  2276. private async _normalizeParentRecursively(
  2277. pathOrRegExps: (RegExp | string)[], publicPathsToNormalize: string[], grantFiltersByUser: { $or: any[] }, user, count = 0, skiped = 0, isFirst = true,
  2278. ): Promise<void> {
  2279. const BATCH_SIZE = 100;
  2280. const PAGES_LIMIT = 1000;
  2281. const socket = this.crowi.socketIoService.getAdminSocket();
  2282. const Page = mongoose.model('Page') as unknown as PageModel;
  2283. const { PageQueryBuilder } = Page;
  2284. // Build filter
  2285. const matchFilter = this.buildFilterForNormalizeParentRecursively(pathOrRegExps, publicPathsToNormalize, grantFiltersByUser);
  2286. let baseAggregation = Page
  2287. .aggregate([
  2288. { $match: matchFilter },
  2289. {
  2290. $project: { // minimize data to fetch
  2291. _id: 1,
  2292. path: 1,
  2293. },
  2294. },
  2295. ]);
  2296. // Limit pages to get
  2297. const total = await Page.countDocuments(matchFilter);
  2298. if (isFirst) {
  2299. socket.emit(SocketEventName.PMStarted, { total });
  2300. }
  2301. if (total > PAGES_LIMIT) {
  2302. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  2303. }
  2304. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  2305. const batchStream = createBatchStream(BATCH_SIZE);
  2306. let shouldContinue = true;
  2307. let nextCount = count;
  2308. let nextSkiped = skiped;
  2309. const migratePagesStream = new Writable({
  2310. objectMode: true,
  2311. async write(pages, encoding, callback) {
  2312. const parentPaths = Array.from(new Set<string>(pages.map(p => pathlib.dirname(p.path))));
  2313. // 1. Remove unnecessary empty pages & reset parent for pages which had had those empty pages
  2314. const pageIdsToNotDelete = pages.map(p => p._id);
  2315. const emptyPagePathsToDelete = pages.map(p => p.path);
  2316. const builder1 = new PageQueryBuilder(Page.find({ isEmpty: true }, { _id: 1 }), true);
  2317. builder1.addConditionToListByPathsArray(emptyPagePathsToDelete);
  2318. builder1.addConditionToExcludeByPageIdsArray(pageIdsToNotDelete);
  2319. const emptyPagesToDelete = await builder1.query.lean().exec();
  2320. const resetParentOperations = emptyPagesToDelete.map((p) => {
  2321. return {
  2322. updateOne: {
  2323. filter: {
  2324. parent: p._id,
  2325. },
  2326. update: {
  2327. parent: null,
  2328. },
  2329. },
  2330. };
  2331. });
  2332. await Page.bulkWrite(resetParentOperations);
  2333. await Page.removeEmptyPages(pageIdsToNotDelete, emptyPagePathsToDelete);
  2334. // 2. Create lacking parents as empty pages
  2335. const orFilters = [
  2336. { path: '/' },
  2337. { path: { $in: publicPathsToNormalize }, grant: Page.GRANT_PUBLIC, status: Page.STATUS_PUBLISHED },
  2338. { path: { $in: publicPathsToNormalize }, parent: { $ne: null }, status: Page.STATUS_PUBLISHED },
  2339. { path: { $nin: publicPathsToNormalize }, status: Page.STATUS_PUBLISHED },
  2340. ];
  2341. const filterForApplicableAncestors = { $or: orFilters };
  2342. await Page.createEmptyPagesByPaths(parentPaths, user, false, filterForApplicableAncestors);
  2343. // 3. Find parents
  2344. const addGrantCondition = (builder) => {
  2345. builder.query = builder.query.and(grantFiltersByUser);
  2346. return builder;
  2347. };
  2348. const builder2 = new PageQueryBuilder(Page.find(), true);
  2349. addGrantCondition(builder2);
  2350. const parents = await builder2
  2351. .addConditionToListByPathsArray(parentPaths)
  2352. .addConditionToFilterByApplicableAncestors(publicPathsToNormalize)
  2353. .query
  2354. .lean()
  2355. .exec();
  2356. // Normalize all siblings for each page
  2357. const updateManyOperations = parents.map((parent) => {
  2358. const parentId = parent._id;
  2359. // Build filter
  2360. const parentPathEscaped = escapeStringRegexp(parent.path === '/' ? '' : parent.path); // adjust the path for RegExp
  2361. const filter: any = {
  2362. $and: [
  2363. {
  2364. path: { $regex: new RegExp(`^${parentPathEscaped}(\\/[^/]+)\\/?$`, 'i') }, // see: regexr.com/6889f (e.g. /parent/any_child or /any_level1)
  2365. },
  2366. {
  2367. path: { $in: pathOrRegExps.concat(publicPathsToNormalize) },
  2368. },
  2369. filterForApplicableAncestors,
  2370. grantFiltersByUser,
  2371. ],
  2372. };
  2373. return {
  2374. updateMany: {
  2375. filter,
  2376. update: {
  2377. parent: parentId,
  2378. },
  2379. },
  2380. };
  2381. });
  2382. try {
  2383. const res = await Page.bulkWrite(updateManyOperations);
  2384. nextCount += res.result.nModified;
  2385. nextSkiped += res.result.writeErrors.length;
  2386. logger.info(`Page migration processing: (migratedPages=${res.result.nModified})`);
  2387. socket.emit(SocketEventName.PMMigrating, { count: nextCount });
  2388. socket.emit(SocketEventName.PMErrorCount, { skip: nextSkiped });
  2389. // Throw if any error is found
  2390. if (res.result.writeErrors.length > 0) {
  2391. logger.error('Failed to migrate some pages', res.result.writeErrors);
  2392. socket.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2393. throw Error('Failed to migrate some pages');
  2394. }
  2395. // Finish migration if no modification occurred
  2396. if (res.result.nModified === 0 && res.result.nMatched === 0) {
  2397. shouldContinue = false;
  2398. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  2399. socket.emit(SocketEventName.PMEnded, { isSucceeded: false });
  2400. }
  2401. }
  2402. catch (err) {
  2403. logger.error('Failed to update page.parent.', err);
  2404. throw err;
  2405. }
  2406. callback();
  2407. },
  2408. final(callback) {
  2409. callback();
  2410. },
  2411. });
  2412. pagesStream
  2413. .pipe(batchStream)
  2414. .pipe(migratePagesStream);
  2415. await streamToPromise(migratePagesStream);
  2416. if (await Page.exists(matchFilter) && shouldContinue) {
  2417. return this._normalizeParentRecursively(pathOrRegExps, publicPathsToNormalize, grantFiltersByUser, user, nextCount, nextSkiped, false);
  2418. }
  2419. // End
  2420. socket.emit(SocketEventName.PMEnded, { isSucceeded: true });
  2421. }
  2422. private async _v5NormalizeIndex() {
  2423. const collection = mongoose.connection.collection('pages');
  2424. try {
  2425. // drop pages.path_1 indexes
  2426. await collection.dropIndex('path_1');
  2427. logger.info('Succeeded to drop unique indexes from pages.path.');
  2428. }
  2429. catch (err) {
  2430. logger.warn('Failed to drop unique indexes from pages.path.', err);
  2431. throw err;
  2432. }
  2433. try {
  2434. // create indexes without
  2435. await collection.createIndex({ path: 1 }, { unique: false });
  2436. logger.info('Succeeded to create non-unique indexes on pages.path.');
  2437. }
  2438. catch (err) {
  2439. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  2440. throw err;
  2441. }
  2442. }
  2443. async countPagesCanNormalizeParentByUser(user): Promise<number> {
  2444. if (user == null) {
  2445. throw Error('user is required');
  2446. }
  2447. const Page = mongoose.model('Page') as unknown as PageModel;
  2448. const { PageQueryBuilder } = Page;
  2449. const builder = new PageQueryBuilder(Page.count(), false);
  2450. await builder.addConditionAsMigratablePages(user);
  2451. const nMigratablePages = await builder.query.exec();
  2452. return nMigratablePages;
  2453. }
  2454. /**
  2455. * update descendantCount of the following pages
  2456. * - page that has the same path as the provided path
  2457. * - pages that are descendants of the above page
  2458. */
  2459. async updateDescendantCountOfSelfAndDescendants(path: string): Promise<void> {
  2460. const BATCH_SIZE = 200;
  2461. const Page = this.crowi.model('Page');
  2462. const { PageQueryBuilder } = Page;
  2463. const builder = new PageQueryBuilder(Page.find(), true);
  2464. builder.addConditionAsMigrated();
  2465. builder.addConditionToListWithDescendants(path);
  2466. builder.addConditionToSortPagesByDescPath();
  2467. const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
  2468. const recountWriteStream = new Writable({
  2469. objectMode: true,
  2470. async write(pageDocuments, encoding, callback) {
  2471. for await (const document of pageDocuments) {
  2472. const descendantCount = await Page.recountDescendantCount(document._id);
  2473. await Page.findByIdAndUpdate(document._id, { descendantCount });
  2474. }
  2475. callback();
  2476. },
  2477. final(callback) {
  2478. callback();
  2479. },
  2480. });
  2481. aggregatedPages
  2482. .pipe(createBatchStream(BATCH_SIZE))
  2483. .pipe(recountWriteStream);
  2484. await streamToPromise(recountWriteStream);
  2485. }
  2486. // update descendantCount of all pages that are ancestors of a provided pageId by count
  2487. async updateDescendantCountOfAncestors(pageId: ObjectIdLike, inc: number, shouldIncludeTarget: boolean): Promise<void> {
  2488. const Page = this.crowi.model('Page');
  2489. const ancestors = await Page.findAncestorsUsingParentRecursively(pageId, shouldIncludeTarget);
  2490. const ancestorPageIds = ancestors.map(p => p._id);
  2491. await Page.incrementDescendantCountOfPageIds(ancestorPageIds, inc);
  2492. const updateDescCountData: UpdateDescCountRawData = Object.fromEntries(ancestors.map(p => [p._id.toString(), p.descendantCount + inc]));
  2493. this.emitUpdateDescCount(updateDescCountData);
  2494. }
  2495. private emitUpdateDescCount(data: UpdateDescCountRawData): void {
  2496. const socket = this.crowi.socketIoService.getDefaultSocket();
  2497. socket.emit(SocketEventName.UpdateDescCount, data);
  2498. }
  2499. }
  2500. export default PageService;