page.ts 90 KB

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