page.ts 117 KB

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