page.ts 92 KB

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