page.ts 70 KB

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