page.ts 69 KB

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