page.ts 85 KB

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