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