page.ts 115 KB

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