page.ts 70 KB

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