page.ts 111 KB

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