page.ts 79 KB

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