page.ts 93 KB

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