page.ts 95 KB

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