page.ts 79 KB

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