page.ts 73 KB

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