page.ts 96 KB

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