page.ts 93 KB

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