page.ts 111 KB

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