page.ts 85 KB

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