page.ts 109 KB

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