page.ts 79 KB

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