page.ts 117 KB

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