page.ts 90 KB

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