page.ts 73 KB

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