page.ts 96 KB

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