| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564 |
- import { pagePathUtils } from '@growi/core';
- import mongoose, { ObjectId, QueryCursor } from 'mongoose';
- import escapeStringRegexp from 'escape-string-regexp';
- import streamToPromise from 'stream-to-promise';
- import pathlib from 'path';
- import { Readable, Writable } from 'stream';
- import { createBatchStream } from '~/server/util/batch-stream';
- import loggerFactory from '~/utils/logger';
- import {
- CreateMethod, generateGrantCondition, PageCreateOptions, PageModel, PageDocument,
- } from '~/server/models/page';
- import { stringifySnapshot } from '~/models/serializers/in-app-notification-snapshot/page';
- import {
- IPage, IPageInfo, IPageInfoForEntity, IPageWithMeta,
- } from '~/interfaces/page';
- import { serializePageSecurely } from '../models/serializers/page-serializer';
- import { PageRedirectModel } from '../models/page-redirect';
- import Subscription from '../models/subscription';
- import { ObjectIdLike } from '../interfaces/mongoose-utils';
- import { IUserHasId } from '~/interfaces/user';
- import { Ref } from '~/interfaces/common';
- import { HasObjectId } from '~/interfaces/has-object-id';
- import PageOperation, { PageActionStage, PageActionType } from '../models/page-operation';
- import ActivityDefine from '../util/activityDefine';
- const debug = require('debug')('growi:services:page');
- const logger = loggerFactory('growi:services:page');
- const {
- isTrashPage, isTopPage, omitDuplicateAreaPageFromPages,
- collectAncestorPaths, isMovablePage,
- } = pagePathUtils;
- const BULK_REINDEX_SIZE = 100;
- const LIMIT_FOR_MULTIPLE_PAGE_OP = 20;
- // TODO: improve type
- class PageCursorsForDescendantsFactory {
- private user: any; // TODO: Typescriptize model
- private rootPage: any; // TODO: wait for mongoose update
- private shouldIncludeEmpty: boolean;
- private initialCursor: QueryCursor<any>; // TODO: wait for mongoose update
- private Page: PageModel;
- constructor(user: any, rootPage: any, shouldIncludeEmpty: boolean) {
- this.user = user;
- this.rootPage = rootPage;
- this.shouldIncludeEmpty = shouldIncludeEmpty;
- this.Page = mongoose.model('Page') as unknown as PageModel;
- }
- // prepare initial cursor
- private async init() {
- const initialCursor = await this.generateCursorToFindChildren(this.rootPage);
- this.initialCursor = initialCursor;
- }
- /**
- * Returns Iterable that yields only descendant pages unorderedly
- * @returns Promise<AsyncGenerator>
- */
- async generateIterable(): Promise<AsyncGenerator> {
- // initialize cursor
- await this.init();
- return this.generateOnlyDescendants(this.initialCursor);
- }
- /**
- * Returns Readable that produces only descendant pages unorderedly
- * @returns Promise<Readable>
- */
- async generateReadable(): Promise<Readable> {
- return Readable.from(await this.generateIterable());
- }
- /**
- * Generator that unorderedly yields descendant pages
- */
- private async* generateOnlyDescendants(cursor: QueryCursor<any>) {
- for await (const page of cursor) {
- const nextCursor = await this.generateCursorToFindChildren(page);
- yield* this.generateOnlyDescendants(nextCursor); // recursively yield
- yield page;
- }
- }
- private async generateCursorToFindChildren(page: any): Promise<QueryCursor<any>> {
- const { PageQueryBuilder } = this.Page;
- const builder = new PageQueryBuilder(this.Page.find(), this.shouldIncludeEmpty);
- builder.addConditionToFilteringByParentId(page._id);
- // await this.Page.addConditionToFilteringByViewerToEdit(builder, this.user);
- const cursor = builder.query.lean().cursor({ batchSize: BULK_REINDEX_SIZE }) as QueryCursor<any>;
- return cursor;
- }
- }
- class PageService {
- crowi: any;
- pageEvent: any;
- tagEvent: any;
- constructor(crowi) {
- this.crowi = crowi;
- this.pageEvent = crowi.event('page');
- this.tagEvent = crowi.event('tag');
- // init
- this.initPageEvent();
- }
- private initPageEvent() {
- // create
- this.pageEvent.on('create', this.pageEvent.onCreate);
- // createMany
- this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
- this.pageEvent.on('addSeenUsers', this.pageEvent.onAddSeenUsers);
- // update
- this.pageEvent.on('update', async(page, user) => {
- this.pageEvent.onUpdate();
- try {
- await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_UPDATE);
- }
- catch (err) {
- logger.error(err);
- }
- });
- // rename
- this.pageEvent.on('rename', async(page, user) => {
- try {
- await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_RENAME);
- }
- catch (err) {
- logger.error(err);
- }
- });
- // delete
- this.pageEvent.on('delete', async(page, user) => {
- try {
- await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_DELETE);
- }
- catch (err) {
- logger.error(err);
- }
- });
- // delete completely
- this.pageEvent.on('deleteCompletely', async(page, user) => {
- try {
- await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_DELETE_COMPLETELY);
- }
- catch (err) {
- logger.error(err);
- }
- });
- // likes
- this.pageEvent.on('like', async(page, user) => {
- try {
- await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_LIKE);
- }
- catch (err) {
- logger.error(err);
- }
- });
- // bookmark
- this.pageEvent.on('bookmark', async(page, user) => {
- try {
- await this.createAndSendNotifications(page, user, ActivityDefine.ACTION_PAGE_BOOKMARK);
- }
- catch (err) {
- logger.error(err);
- }
- });
- }
- canDeleteCompletely(creatorId, operator) {
- const pageCompleteDeletionAuthority = this.crowi.configManager.getConfig('crowi', 'security:pageCompleteDeletionAuthority');
- if (operator.admin) {
- return true;
- }
- if (pageCompleteDeletionAuthority === 'anyOne' || pageCompleteDeletionAuthority == null) {
- return true;
- }
- if (pageCompleteDeletionAuthority === 'adminAndAuthor') {
- const operatorId = operator?._id;
- return (operatorId != null && operatorId.equals(creatorId));
- }
- return false;
- }
- filterPagesByCanDeleteCompletely(pages, user) {
- return pages.filter(p => p.isEmpty || this.canDeleteCompletely(p.creator, user));
- }
- // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
- async findPageAndMetaDataByViewer(pageId: string, path: string, user: IUserHasId, isSharedPage = false): Promise<IPageWithMeta|null> {
- const Page = this.crowi.model('Page');
- let pagePath = path;
- let page: PageModel & PageDocument & HasObjectId;
- if (pageId != null) { // prioritized
- page = await Page.findByIdAndViewer(pageId, user);
- pagePath = page.path;
- }
- else {
- page = await Page.findByPathAndViewer(pagePath, user);
- }
- if (page == null) {
- return null;
- }
- if (isSharedPage) {
- return {
- pageData: page,
- pageMeta: {
- isEmpty: page.isEmpty,
- isMovable: false,
- isDeletable: false,
- isAbleToDeleteCompletely: false,
- isRevertible: false,
- },
- };
- }
- const isGuestUser = user == null;
- const pageInfo = this.constructBasicPageInfo(page, isGuestUser);
- const Bookmark = this.crowi.model('Bookmark');
- const bookmarkCount = await Bookmark.countByPageId(pageId);
- const metadataForGuest = {
- ...pageInfo,
- bookmarkCount,
- };
- if (isGuestUser) {
- return {
- pageData: page,
- pageMeta: metadataForGuest,
- };
- }
- const isBookmarked = await Bookmark.findByPageIdAndUserId(pageId, user._id);
- const isLiked = page.isLiked(user);
- const isAbleToDeleteCompletely = this.canDeleteCompletely((page.creator as IUserHasId)?._id, user);
- const subscription = await Subscription.findByUserIdAndTargetId(user._id, pageId);
- return {
- pageData: page,
- pageMeta: {
- ...metadataForGuest,
- isAbleToDeleteCompletely,
- isBookmarked,
- isLiked,
- subscriptionStatus: subscription?.status,
- },
- };
- }
- private shouldUseV4Process(page): boolean {
- const Page = mongoose.model('Page') as unknown as PageModel;
- const isTrashPage = page.status === Page.STATUS_DELETED;
- const isPageMigrated = page.parent != null;
- const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
- const isRoot = isTopPage(page.path);
- const isPageRestricted = page.grant === Page.GRANT_RESTRICTED;
- const shouldUseV4Process = !isTrashPage && !isRoot && !isPageRestricted && (!isV5Compatible || !isPageMigrated);
- return shouldUseV4Process;
- }
- private shouldUseV4ProcessForRevert(page): boolean {
- const Page = mongoose.model('Page') as unknown as PageModel;
- const isV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
- const isPageRestricted = page.grant === Page.GRANT_RESTRICTED;
- const shouldUseV4Process = !isPageRestricted && !isV5Compatible;
- return shouldUseV4Process;
- }
- private shouldNormalizeParent(page): boolean {
- const Page = mongoose.model('Page') as unknown as PageModel;
- return page.grant !== Page.GRANT_RESTRICTED && page.grant !== Page.GRANT_SPECIFIED;
- }
- /**
- * Remove all empty pages at leaf position by page whose parent will change or which will be deleted.
- * @param page Page whose parent will change or which will be deleted
- */
- async removeLeafEmptyPages(page): Promise<void> {
- const Page = mongoose.model('Page') as unknown as PageModel;
- // delete leaf empty pages
- const isSiblingsOrChildrenExist = await Page.exists({ parent: { $in: [page.parent, page._id] }, _id: { $ne: page._id } });
- if (!isSiblingsOrChildrenExist) {
- await Page.removeLeafEmptyPagesRecursively(page.parent);
- }
- }
- /**
- * Generate read stream to operate descendants of the specified page path
- * @param {string} targetPagePath
- * @param {User} viewer
- */
- private async generateReadStreamToOperateOnlyDescendants(targetPagePath, userToOperate) {
- const Page = this.crowi.model('Page');
- const { PageQueryBuilder } = Page;
- const builder = new PageQueryBuilder(Page.find(), true)
- .addConditionAsNotMigrated() // to avoid affecting v5 pages
- .addConditionToListOnlyDescendants(targetPagePath);
- await Page.addConditionToFilteringByViewerToEdit(builder, userToOperate);
- return builder
- .query
- .lean()
- .cursor({ batchSize: BULK_REINDEX_SIZE });
- }
- async renamePage(page, newPagePath, user, options) {
- /*
- * Common Operation
- */
- const Page = mongoose.model('Page') as unknown as PageModel;
- const isExist = await Page.exists({ path: newPagePath });
- if (isExist) {
- // if page found, cannot rename to that path
- throw new Error('the path already exists');
- }
- if (isTopPage(page.path)) {
- throw Error('It is forbidden to rename the top page');
- }
- // Separate v4 & v5 process
- const shouldUseV4Process = this.shouldUseV4Process(page);
- if (shouldUseV4Process) {
- return this.renamePageV4(page, newPagePath, user, options);
- }
- /*
- * Resumable Operation
- */
- let pageOp;
- try {
- pageOp = await PageOperation.create({
- actionType: PageActionType.Rename,
- actionStage: PageActionStage.Main,
- page,
- user,
- fromPath: page.path,
- toPath: newPagePath,
- options,
- });
- }
- catch (err) {
- logger.error('Failed to create PageOperation document.', err);
- throw err;
- }
- const renamedPage = await this.renameMainOperation(page, newPagePath, user, options, pageOp._id);
- return renamedPage;
- }
- async renameMainOperation(page, newPagePath: string, user, options, pageOpId: ObjectIdLike) {
- const Page = mongoose.model('Page') as unknown as PageModel;
- const updateMetadata = options.updateMetadata || false;
- // sanitize path
- newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
- // UserGroup & Owner validation
- // use the parent's grant when target page is an empty page
- let grant;
- let grantedUserIds;
- let grantedGroupId;
- if (page.isEmpty) {
- const parent = await Page.findOne({ _id: page.parent });
- if (parent == null) {
- throw Error('parent not found');
- }
- grant = parent.grant;
- grantedUserIds = parent.grantedUsers;
- grantedGroupId = parent.grantedGroup;
- }
- else {
- grant = page.grant;
- grantedUserIds = page.grantedUsers;
- grantedGroupId = page.grantedGroup;
- }
- if (grant !== Page.GRANT_RESTRICTED) {
- let isGrantNormalized = false;
- try {
- const shouldCheckDescendants = false;
- isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(newPagePath, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
- }
- catch (err) {
- logger.error(`Failed to validate grant of page at "${newPagePath}" when renaming`, err);
- throw err;
- }
- if (!isGrantNormalized) {
- throw Error(`This page cannot be renamed to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
- }
- }
- // Rename target (update parent attr)
- const update: Partial<IPage> = {};
- // find or create parent
- const newParent = await Page.getParentAndFillAncestors(newPagePath);
- // update Page
- update.path = newPagePath;
- update.parent = newParent._id;
- if (updateMetadata) {
- update.lastUpdateUser = user;
- update.updatedAt = new Date();
- }
- const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
- this.pageEvent.emit('rename', page, user);
- // Set to Sub
- const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
- if (pageOp == null) {
- throw Error('PageOperation document not found');
- }
- /*
- * Sub Operation
- */
- this.renameSubOperation(page, newPagePath, user, options, renamedPage, pageOp._id);
- return renamedPage;
- }
- async renameSubOperation(page, newPagePath: string, user, options, renamedPage, pageOpId: ObjectIdLike): Promise<void> {
- const exParentId = page.parent;
- // update descendants first
- await this.renameDescendantsWithStream(page, newPagePath, user, options, false);
- // reduce ancestore's descendantCount
- const nToReduce = -1 * ((page.isEmpty ? 0 : 1) + page.descendantCount);
- await this.updateDescendantCountOfAncestors(exParentId, nToReduce, true);
- // increase ancestore's descendantCount
- const nToIncrease = (renamedPage.isEmpty ? 0 : 1) + page.descendantCount;
- await this.updateDescendantCountOfAncestors(renamedPage._id, nToIncrease, false);
- await PageOperation.findByIdAndDelete(pageOpId);
- }
- // !!renaming always include descendant pages!!
- private async renamePageV4(page, newPagePath, user, options) {
- const Page = this.crowi.model('Page');
- const Revision = this.crowi.model('Revision');
- const updateMetadata = options.updateMetadata || false;
- // sanitize path
- newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
- // create descendants first
- await this.renameDescendantsWithStream(page, newPagePath, user, options);
- const update: any = {};
- // update Page
- update.path = newPagePath;
- if (updateMetadata) {
- update.lastUpdateUser = user;
- update.updatedAt = Date.now();
- }
- const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
- // update Rivisions
- await Revision.updateRevisionListByPageId(renamedPage._id, { pageId: renamedPage._id });
- this.pageEvent.emit('rename', page, user);
- return renamedPage;
- }
- private async renameDescendants(pages, user, options, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = true) {
- // v4 compatible process
- if (shouldUseV4Process) {
- return this.renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix);
- }
- const Page = mongoose.model('Page') as unknown as PageModel;
- const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
- const { updateMetadata, createRedirectPage } = options;
- const updatePathOperations: any[] = [];
- const insertPageRedirectOperations: any[] = [];
- pages.forEach((page) => {
- const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
- // increment updatePathOperations
- let update;
- if (!page.isEmpty && updateMetadata) {
- update = {
- $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() },
- };
- }
- else {
- update = {
- $set: { path: newPagePath },
- };
- }
- if (!page.isEmpty && createRedirectPage) {
- // insert PageRedirect
- insertPageRedirectOperations.push({
- insertOne: {
- document: {
- fromPath: page.path,
- toPath: newPagePath,
- },
- },
- });
- }
- updatePathOperations.push({
- updateOne: {
- filter: {
- _id: page._id,
- },
- update,
- },
- });
- });
- try {
- await Page.bulkWrite(updatePathOperations);
- }
- catch (err) {
- if (err.code !== 11000) {
- throw new Error(`Failed to rename pages: ${err}`);
- }
- }
- try {
- await PageRedirect.bulkWrite(insertPageRedirectOperations);
- }
- catch (err) {
- if (err.code !== 11000) {
- throw Error(`Failed to create PageRedirect documents: ${err}`);
- }
- }
- this.pageEvent.emit('updateMany', pages, user);
- }
- private async renameDescendantsV4(pages, user, options, oldPagePathPrefix, newPagePathPrefix) {
- const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
- const pageCollection = mongoose.connection.collection('pages');
- const { updateMetadata, createRedirectPage } = options;
- const unorderedBulkOp = pageCollection.initializeUnorderedBulkOp();
- const insertPageRedirectOperations: any[] = [];
- pages.forEach((page) => {
- const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
- if (updateMetadata) {
- unorderedBulkOp
- .find({ _id: page._id })
- .update({ $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() } });
- }
- else {
- unorderedBulkOp.find({ _id: page._id }).update({ $set: { path: newPagePath } });
- }
- // insert PageRedirect
- if (!page.isEmpty && createRedirectPage) {
- insertPageRedirectOperations.push({
- insertOne: {
- document: {
- fromPath: page.path,
- toPath: newPagePath,
- },
- },
- });
- }
- });
- try {
- await unorderedBulkOp.execute();
- }
- catch (err) {
- if (err.code !== 11000) {
- throw new Error(`Failed to rename pages: ${err}`);
- }
- }
- try {
- await PageRedirect.bulkWrite(insertPageRedirectOperations);
- }
- catch (err) {
- if (err.code !== 11000) {
- throw Error(`Failed to create PageRedirect documents: ${err}`);
- }
- }
- this.pageEvent.emit('updateMany', pages, user);
- }
- private async renameDescendantsWithStream(targetPage, newPagePath, user, options = {}, shouldUseV4Process = true) {
- // v4 compatible process
- if (shouldUseV4Process) {
- return this.renameDescendantsWithStreamV4(targetPage, newPagePath, user, options);
- }
- const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
- const readStream = await factory.generateReadable();
- const newPagePathPrefix = newPagePath;
- const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
- const renameDescendants = this.renameDescendants.bind(this);
- const pageEvent = this.pageEvent;
- let count = 0;
- const writeStream = new Writable({
- objectMode: true,
- async write(batch, encoding, callback) {
- try {
- count += batch.length;
- await renameDescendants(
- batch, user, options, pathRegExp, newPagePathPrefix, shouldUseV4Process,
- );
- logger.debug(`Renaming pages progressing: (count=${count})`);
- }
- catch (err) {
- logger.error('Renaming error on add anyway: ', err);
- }
- callback();
- },
- async final(callback) {
- logger.debug(`Renaming pages has completed: (totalCount=${count})`);
- // update path
- targetPage.path = newPagePath;
- pageEvent.emit('syncDescendantsUpdate', targetPage, user);
- callback();
- },
- });
- readStream
- .pipe(createBatchStream(BULK_REINDEX_SIZE))
- .pipe(writeStream);
- await streamToPromise(writeStream);
- }
- private async renameDescendantsWithStreamV4(targetPage, newPagePath, user, options = {}) {
- const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
- const newPagePathPrefix = newPagePath;
- const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
- const renameDescendants = this.renameDescendants.bind(this);
- const pageEvent = this.pageEvent;
- let count = 0;
- const writeStream = new Writable({
- objectMode: true,
- async write(batch, encoding, callback) {
- try {
- count += batch.length;
- await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
- logger.debug(`Renaming pages progressing: (count=${count})`);
- }
- catch (err) {
- logger.error('renameDescendants error on add anyway: ', err);
- }
- callback();
- },
- final(callback) {
- logger.debug(`Renaming pages has completed: (totalCount=${count})`);
- // update path
- targetPage.path = newPagePath;
- pageEvent.emit('syncDescendantsUpdate', targetPage, user);
- callback();
- },
- });
- readStream
- .pipe(createBatchStream(BULK_REINDEX_SIZE))
- .pipe(writeStream);
- await streamToPromise(readStream);
- }
- /*
- * Duplicate
- */
- async duplicate(page, newPagePath, user, isRecursively) {
- /*
- * Common Operation
- */
- const isEmptyAndNotRecursively = page?.isEmpty && !isRecursively;
- if (page == null || isEmptyAndNotRecursively) {
- throw new Error('Cannot find or duplicate the empty page');
- }
- const Page = mongoose.model('Page') as unknown as PageModel;
- const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
- if (isRecursively && page.isEmpty) {
- throw Error('Page not found.');
- }
- newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
- // 1. Separate v4 & v5 process
- const shouldUseV4Process = this.shouldUseV4Process(page);
- if (shouldUseV4Process) {
- return this.duplicateV4(page, newPagePath, user, isRecursively);
- }
- // 2. UserGroup & Owner validation
- // use the parent's grant when target page is an empty page
- let grant;
- let grantedUserIds;
- let grantedGroupId;
- if (page.isEmpty) {
- const parent = await Page.findOne({ _id: page.parent });
- if (parent == null) {
- throw Error('parent not found');
- }
- grant = parent.grant;
- grantedUserIds = parent.grantedUsers;
- grantedGroupId = parent.grantedGroup;
- }
- else {
- grant = page.grant;
- grantedUserIds = page.grantedUsers;
- grantedGroupId = page.grantedGroup;
- }
- if (grant !== Page.GRANT_RESTRICTED) {
- let isGrantNormalized = false;
- try {
- const shouldCheckDescendants = false;
- isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(newPagePath, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
- }
- catch (err) {
- logger.error(`Failed to validate grant of page at "${newPagePath}" when duplicating`, err);
- throw err;
- }
- if (!isGrantNormalized) {
- throw Error(`This page cannot be duplicated to "${newPagePath}" since the selected grant or grantedGroup is not assignable to this page.`);
- }
- }
- // 3. Duplicate target
- const options: PageCreateOptions = {
- grant: page.grant,
- grantUserGroupId: page.grantedGroup,
- };
- let duplicatedTarget;
- if (page.isEmpty) {
- const parent = await Page.getParentAndFillAncestors(newPagePath);
- duplicatedTarget = await Page.createEmptyPage(newPagePath, parent);
- }
- else {
- // copy & populate (reason why copy: SubOperation only allows non-populated page document)
- const copyPage = { ...page };
- await copyPage.populate({ path: 'revision', model: 'Revision', select: 'body' });
- duplicatedTarget = await (Page.create as CreateMethod)(
- newPagePath, copyPage.revision.body, user, options,
- );
- }
- // 4. Take over tags
- const originTags = await page.findRelatedTagsById();
- let savedTags = [];
- if (originTags.length !== 0) {
- await PageTagRelation.updatePageTags(duplicatedTarget._id, originTags);
- savedTags = await PageTagRelation.listTagNamesByPage(duplicatedTarget._id);
- this.tagEvent.emit('update', duplicatedTarget, savedTags);
- }
- if (isRecursively) {
- /*
- * Resumable Operation
- */
- let pageOp;
- try {
- pageOp = await PageOperation.create({
- actionType: PageActionType.Duplicate,
- actionStage: PageActionStage.Main,
- page,
- user,
- fromPath: page.path,
- toPath: newPagePath,
- });
- }
- catch (err) {
- logger.error('Failed to create PageOperation document.', err);
- throw err;
- }
- this.duplicateRecursivelyMainOperation(page, newPagePath, user, pageOp._id);
- }
- const result = serializePageSecurely(duplicatedTarget);
- result.tags = savedTags;
- return result;
- }
- async duplicateRecursivelyMainOperation(page, newPagePath: string, user, pageOpId: ObjectIdLike): Promise<void> {
- const nDuplicatedPages = await this.duplicateDescendantsWithStream(page, newPagePath, user, false);
- // normalize parent of descendant pages
- const shouldNormalize = this.shouldNormalizeParent(page);
- if (shouldNormalize) {
- try {
- await this.normalizeParentAndDescendantCountOfDescendants(newPagePath);
- logger.info(`Successfully normalized duplicated descendant pages under "${newPagePath}"`);
- }
- catch (err) {
- logger.error('Failed to normalize descendants afrer duplicate:', err);
- throw err;
- }
- }
- // Set to Sub
- const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
- if (pageOp == null) {
- throw Error('PageOperation document not found');
- }
- /*
- * Sub Operation
- */
- await this.duplicateRecursivelySubOperation(newPagePath, nDuplicatedPages, pageOp._id);
- }
- async duplicateRecursivelySubOperation(newPagePath: string, nDuplicatedPages: number, pageOpId: ObjectIdLike): Promise<void> {
- const Page = mongoose.model('Page');
- const newTarget = await Page.findOne({ path: newPagePath }); // only one page will be found since duplicating to existing path is forbidden
- if (newTarget == null) {
- throw Error('No duplicated page found. Something might have gone wrong in duplicateRecursivelyMainOperation.');
- }
- await this.updateDescendantCountOfAncestors(newTarget._id, nDuplicatedPages, false);
- await PageOperation.findByIdAndDelete(pageOpId);
- }
- async duplicateV4(page, newPagePath, user, isRecursively) {
- const Page = this.crowi.model('Page');
- const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
- // populate
- await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
- // create option
- const options: any = { page };
- options.grant = page.grant;
- options.grantUserGroupId = page.grantedGroup;
- options.grantedUserIds = page.grantedUsers;
- newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
- const createdPage = await Page.create(
- newPagePath, page.revision.body, user, options,
- );
- if (isRecursively) {
- this.duplicateDescendantsWithStream(page, newPagePath, user);
- }
- // take over tags
- const originTags = await page.findRelatedTagsById();
- let savedTags = [];
- if (originTags != null) {
- await PageTagRelation.updatePageTags(createdPage.id, originTags);
- savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
- this.tagEvent.emit('update', createdPage, savedTags);
- }
- const result = serializePageSecurely(createdPage);
- result.tags = savedTags;
- return result;
- }
- /**
- * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
- * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
- */
- private async duplicateTags(pageIdMapping) {
- const PageTagRelation = mongoose.model('PageTagRelation');
- // convert pageId from string to ObjectId
- const pageIds = Object.keys(pageIdMapping);
- const stage = { $or: pageIds.map((pageId) => { return { relatedPage: new mongoose.Types.ObjectId(pageId) } }) };
- const pagesAssociatedWithTag = await PageTagRelation.aggregate([
- {
- $match: stage,
- },
- {
- $group: {
- _id: '$relatedTag',
- relatedPages: { $push: '$relatedPage' },
- },
- },
- ]);
- const newPageTagRelation: any[] = [];
- pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
- // relatedPages
- relatedPages.forEach((pageId) => {
- newPageTagRelation.push({
- relatedPage: pageIdMapping[pageId], // newPageId
- relatedTag: _id,
- });
- });
- });
- return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
- }
- private async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix, shouldUseV4Process = true) {
- if (shouldUseV4Process) {
- return this.duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix);
- }
- const Page = this.crowi.model('Page');
- const Revision = this.crowi.model('Revision');
- const pageIds = pages.map(page => page._id);
- const revisions = await Revision.find({ pageId: { $in: pageIds } });
- // Mapping to set to the body of the new revision
- const pageIdRevisionMapping = {};
- revisions.forEach((revision) => {
- pageIdRevisionMapping[revision.pageId] = revision;
- });
- // key: oldPageId, value: newPageId
- const pageIdMapping = {};
- const newPages: any[] = [];
- const newRevisions: any[] = [];
- // no need to save parent here
- pages.forEach((page) => {
- const newPageId = new mongoose.Types.ObjectId();
- const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
- const revisionId = new mongoose.Types.ObjectId();
- pageIdMapping[page._id] = newPageId;
- let newPage;
- if (!page.isEmpty) {
- newPage = {
- _id: newPageId,
- path: newPagePath,
- creator: user._id,
- grant: page.grant,
- grantedGroup: page.grantedGroup,
- grantedUsers: page.grantedUsers,
- lastUpdateUser: user._id,
- revision: revisionId,
- };
- newRevisions.push({
- _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
- });
- }
- newPages.push(newPage);
- });
- await Page.insertMany(newPages, { ordered: false });
- await Revision.insertMany(newRevisions, { ordered: false });
- await this.duplicateTags(pageIdMapping);
- }
- private async duplicateDescendantsV4(pages, user, oldPagePathPrefix, newPagePathPrefix) {
- const Page = this.crowi.model('Page');
- const Revision = this.crowi.model('Revision');
- const pageIds = pages.map(page => page._id);
- const revisions = await Revision.find({ pageId: { $in: pageIds } });
- // Mapping to set to the body of the new revision
- const pageIdRevisionMapping = {};
- revisions.forEach((revision) => {
- pageIdRevisionMapping[revision.pageId] = revision;
- });
- // key: oldPageId, value: newPageId
- const pageIdMapping = {};
- const newPages: any[] = [];
- const newRevisions: any[] = [];
- pages.forEach((page) => {
- const newPageId = new mongoose.Types.ObjectId();
- const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
- const revisionId = new mongoose.Types.ObjectId();
- pageIdMapping[page._id] = newPageId;
- newPages.push({
- _id: newPageId,
- path: newPagePath,
- creator: user._id,
- grant: page.grant,
- grantedGroup: page.grantedGroup,
- grantedUsers: page.grantedUsers,
- lastUpdateUser: user._id,
- revision: revisionId,
- });
- newRevisions.push({
- _id: revisionId, pageId: newPageId, body: pageIdRevisionMapping[page._id].body, author: user._id, format: 'markdown',
- });
- });
- await Page.insertMany(newPages, { ordered: false });
- await Revision.insertMany(newRevisions, { ordered: false });
- await this.duplicateTags(pageIdMapping);
- }
- private async duplicateDescendantsWithStream(page, newPagePath, user, shouldUseV4Process = true) {
- if (shouldUseV4Process) {
- return this.duplicateDescendantsWithStreamV4(page, newPagePath, user);
- }
- const iterableFactory = new PageCursorsForDescendantsFactory(user, page, true);
- const readStream = await iterableFactory.generateReadable();
- const newPagePathPrefix = newPagePath;
- const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
- const duplicateDescendants = this.duplicateDescendants.bind(this);
- const pageEvent = this.pageEvent;
- let count = 0;
- let nNonEmptyDuplicatedPages = 0;
- const writeStream = new Writable({
- objectMode: true,
- async write(batch, encoding, callback) {
- try {
- count += batch.length;
- nNonEmptyDuplicatedPages += batch.filter(page => !page.isEmpty).length;
- await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, shouldUseV4Process);
- logger.debug(`Adding pages progressing: (count=${count})`);
- }
- catch (err) {
- logger.error('addAllPages error on add anyway: ', err);
- }
- callback();
- },
- async final(callback) {
- logger.debug(`Adding pages has completed: (totalCount=${count})`);
- // update path
- page.path = newPagePath;
- pageEvent.emit('syncDescendantsUpdate', page, user);
- callback();
- },
- });
- readStream
- .pipe(createBatchStream(BULK_REINDEX_SIZE))
- .pipe(writeStream);
- await streamToPromise(writeStream);
- return nNonEmptyDuplicatedPages;
- }
- private async duplicateDescendantsWithStreamV4(page, newPagePath, user) {
- const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
- const newPagePathPrefix = newPagePath;
- const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
- const duplicateDescendants = this.duplicateDescendants.bind(this);
- const pageEvent = this.pageEvent;
- let count = 0;
- const writeStream = new Writable({
- objectMode: true,
- async write(batch, encoding, callback) {
- try {
- count += batch.length;
- await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix);
- logger.debug(`Adding pages progressing: (count=${count})`);
- }
- catch (err) {
- logger.error('addAllPages error on add anyway: ', err);
- }
- callback();
- },
- final(callback) {
- logger.debug(`Adding pages has completed: (totalCount=${count})`);
- // update path
- page.path = newPagePath;
- pageEvent.emit('syncDescendantsUpdate', page, user);
- callback();
- },
- });
- readStream
- .pipe(createBatchStream(BULK_REINDEX_SIZE))
- .pipe(writeStream);
- await streamToPromise(writeStream);
- return count;
- }
- /*
- * Delete
- */
- async deletePage(page, user, options = {}, isRecursively = false) {
- /*
- * Common Operation
- */
- const Page = mongoose.model('Page') as PageModel;
- // Separate v4 & v5 process
- const shouldUseV4Process = this.shouldUseV4Process(page);
- if (shouldUseV4Process) {
- return this.deletePageV4(page, user, options, isRecursively);
- }
- // Validate
- if (page.isEmpty && !isRecursively) {
- throw Error('Page not found.');
- }
- const isTrashed = isTrashPage(page.path);
- if (isTrashed) {
- throw new Error('This method does NOT support deleting trashed pages.');
- }
- if (!isMovablePage(page.path)) {
- throw new Error('Page is not deletable.');
- }
- // Replace with an empty page
- const isChildrenExist = await Page.exists({ parent: page._id });
- const shouldReplace = !isRecursively && isChildrenExist;
- if (shouldReplace) {
- await Page.replaceTargetWithPage(page, null, true);
- }
- // Delete target
- let deletedPage;
- if (!page.isEmpty) {
- deletedPage = await this.deleteNonEmptyTarget(page, user);
- }
- else { // always recursive
- deletedPage = page;
- await this.deleteEmptyTarget(page);
- }
- // 1. Update descendantCount
- if (isRecursively) {
- const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
- await this.updateDescendantCountOfAncestors(page.parent, inc, true);
- }
- else {
- // update descendantCount of ancestors'
- await this.updateDescendantCountOfAncestors(page.parent, -1, true);
- }
- // 2. Delete leaf empty pages
- const parent = await Page.findById(page.parent);
- await this.removeLeafEmptyPages(parent);
- if (isRecursively) {
- const newPath = Page.getDeletedPageName(page.path);
- let pageOp;
- try {
- pageOp = await PageOperation.create({
- actionType: PageActionType.Delete,
- actionStage: PageActionStage.Main,
- page,
- user,
- fromPath: page.path,
- toPath: newPath,
- });
- }
- catch (err) {
- logger.error('Failed to create PageOperation document.', err);
- throw err;
- }
- /*
- * Resumable Operation
- */
- this.deleteRecursivelyMainOperation(page, user, pageOp._id);
- }
- return deletedPage;
- }
- private async deleteNonEmptyTarget(page, user) {
- const Page = mongoose.model('Page') as unknown as PageModel;
- const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
- const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
- const newPath = Page.getDeletedPageName(page.path);
- const deletedPage = await Page.findByIdAndUpdate(page._id, {
- $set: {
- path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
- },
- }, { new: true });
- await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
- try {
- await PageRedirect.create({ fromPath: page.path, toPath: newPath });
- }
- catch (err) {
- if (err.code !== 11000) {
- throw err;
- }
- }
- this.pageEvent.emit('delete', page, user);
- this.pageEvent.emit('create', deletedPage, user);
- return deletedPage;
- }
- private async deleteEmptyTarget(page): Promise<void> {
- const Page = mongoose.model('Page') as unknown as PageModel;
- await Page.deleteOne({ _id: page._id, isEmpty: true });
- // update descendantCount of ancestors' before removeLeafEmptyPages
- await this.updateDescendantCountOfAncestors(page._id, -page.descendantCount, false);
- }
- async deleteRecursivelyMainOperation(page, user, pageOpId: ObjectIdLike): Promise<void> {
- await this.deleteDescendantsWithStream(page, user, false);
- await PageOperation.findByIdAndDelete(pageOpId);
- // no sub operation available
- }
- private async deletePageV4(page, user, options = {}, isRecursively = false) {
- const Page = mongoose.model('Page') as PageModel;
- const PageTagRelation = mongoose.model('PageTagRelation') as any; // TODO: Typescriptize model
- const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
- const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
- const newPath = Page.getDeletedPageName(page.path);
- const isTrashed = isTrashPage(page.path);
- if (isTrashed) {
- throw new Error('This method does NOT support deleting trashed pages.');
- }
- if (!isMovablePage(page.path)) {
- throw new Error('Page is not deletable.');
- }
- if (isRecursively) {
- this.deleteDescendantsWithStream(page, user);
- }
- // update Revisions
- await Revision.updateRevisionListByPageId(page._id, { pageId: page._id });
- const deletedPage = await Page.findByIdAndUpdate(page._id, {
- $set: {
- path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
- },
- }, { new: true });
- await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: true } });
- try {
- await PageRedirect.create({ fromPath: page.path, toPath: newPath });
- }
- catch (err) {
- if (err.code !== 11000) {
- throw err;
- }
- }
- this.pageEvent.emit('delete', page, user);
- this.pageEvent.emit('create', deletedPage, user);
- return deletedPage;
- }
- private async deleteDescendants(pages, user) {
- const Page = mongoose.model('Page') as unknown as PageModel;
- const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
- const deletePageOperations: any[] = [];
- const insertPageRedirectOperations: any[] = [];
- pages.forEach((page) => {
- const newPath = Page.getDeletedPageName(page.path);
- let operation;
- // if empty, delete completely
- if (page.isEmpty) {
- operation = {
- deleteOne: {
- filter: { _id: page._id },
- },
- };
- }
- // if not empty, set parent to null and update to trash
- else {
- operation = {
- updateOne: {
- filter: { _id: page._id },
- update: {
- $set: {
- path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(), parent: null, descendantCount: 0, // set parent as null
- },
- },
- },
- };
- insertPageRedirectOperations.push({
- insertOne: {
- document: {
- fromPath: page.path,
- toPath: newPath,
- },
- },
- });
- }
- deletePageOperations.push(operation);
- });
- try {
- await Page.bulkWrite(deletePageOperations);
- }
- catch (err) {
- if (err.code !== 11000) {
- throw new Error(`Failed to delete pages: ${err}`);
- }
- }
- finally {
- this.pageEvent.emit('syncDescendantsDelete', pages, user);
- }
- try {
- await PageRedirect.bulkWrite(insertPageRedirectOperations);
- }
- catch (err) {
- if (err.code !== 11000) {
- throw Error(`Failed to create PageRedirect documents: ${err}`);
- }
- }
- }
- /**
- * Create delete stream and return deleted document count
- */
- private async deleteDescendantsWithStream(targetPage, user, shouldUseV4Process = true): Promise<number> {
- let readStream;
- if (shouldUseV4Process) {
- readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
- }
- else {
- const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
- readStream = await factory.generateReadable();
- }
- const deleteDescendants = this.deleteDescendants.bind(this);
- let count = 0;
- let nDeletedNonEmptyPages = 0; // used for updating descendantCount
- const writeStream = new Writable({
- objectMode: true,
- async write(batch, encoding, callback) {
- nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
- try {
- count += batch.length;
- await deleteDescendants(batch, user);
- logger.debug(`Deleting pages progressing: (count=${count})`);
- }
- catch (err) {
- logger.error('deleteDescendants error on add anyway: ', err);
- }
- callback();
- },
- final(callback) {
- logger.debug(`Deleting pages has completed: (totalCount=${count})`);
- callback();
- },
- });
- readStream
- .pipe(createBatchStream(BULK_REINDEX_SIZE))
- .pipe(writeStream);
- await streamToPromise(writeStream);
- return nDeletedNonEmptyPages;
- }
- private async deleteCompletelyOperation(pageIds, pagePaths) {
- // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
- const Bookmark = this.crowi.model('Bookmark');
- const Comment = this.crowi.model('Comment');
- const Page = this.crowi.model('Page');
- const PageTagRelation = this.crowi.model('PageTagRelation');
- const ShareLink = this.crowi.model('ShareLink');
- const Revision = this.crowi.model('Revision');
- const Attachment = this.crowi.model('Attachment');
- const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
- const { attachmentService } = this.crowi;
- const attachments = await Attachment.find({ page: { $in: pageIds } });
- return Promise.all([
- Bookmark.deleteMany({ page: { $in: pageIds } }),
- Comment.deleteMany({ page: { $in: pageIds } }),
- PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
- ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
- Revision.deleteMany({ pageId: { $in: pageIds } }),
- Page.deleteMany({ $or: [{ path: { $in: pagePaths } }, { _id: { $in: pageIds } }] }),
- PageRedirect.deleteMany({ $or: [{ toPath: { $in: pagePaths } }] }),
- attachmentService.removeAllAttachments(attachments),
- ]);
- }
- // delete multiple pages
- private async deleteMultipleCompletely(pages, user, options = {}) {
- const ids = pages.map(page => (page._id));
- const paths = pages.map(page => (page.path));
- logger.debug('Deleting completely', paths);
- await this.deleteCompletelyOperation(ids, paths);
- this.pageEvent.emit('syncDescendantsDelete', pages, user); // update as renamed page
- return;
- }
- async deleteCompletely(page, user, options = {}, isRecursively = false, preventEmitting = false) {
- /*
- * Common Operation
- */
- const Page = mongoose.model('Page') as PageModel;
- if (isTopPage(page.path)) {
- throw Error('It is forbidden to delete the top page');
- }
- if (page.isEmpty && !isRecursively) {
- throw Error('Page not found.');
- }
- // v4 compatible process
- const shouldUseV4Process = this.shouldUseV4Process(page);
- if (shouldUseV4Process) {
- return this.deleteCompletelyV4(page, user, options, isRecursively, preventEmitting);
- }
- const ids = [page._id];
- const paths = [page.path];
- logger.debug('Deleting completely', paths);
- await this.deleteCompletelyOperation(ids, paths);
- // replace with an empty page
- const shouldReplace = !isRecursively && await Page.exists({ parent: page._id });
- if (shouldReplace) {
- await Page.replaceTargetWithPage(page);
- }
- // 1. update descendantCount
- if (isRecursively) {
- const inc = page.isEmpty ? -page.descendantCount : -(page.descendantCount + 1);
- await this.updateDescendantCountOfAncestors(page.parent, inc, true);
- }
- else {
- await this.updateDescendantCountOfAncestors(page.parent, -1, true);
- }
- // 2. then delete target completely
- await this.deleteCompletelyOperation(ids, paths);
- // delete leaf empty pages
- const parent = await Page.findById(page.parent);
- await this.removeLeafEmptyPages(parent);
- if (!page.isEmpty && !preventEmitting) {
- this.pageEvent.emit('deleteCompletely', page, user);
- }
- if (isRecursively) {
- let pageOp;
- try {
- pageOp = await PageOperation.create({
- actionType: PageActionType.DeleteCompletely,
- actionStage: PageActionStage.Main,
- page,
- user,
- fromPath: page.path,
- options,
- });
- }
- catch (err) {
- logger.error('Failed to create PageOperation document.', err);
- throw err;
- }
- /*
- * Main Operation
- */
- this.deleteCompletelyRecursivelyMainOperation(page, user, options, pageOp._id);
- }
- return;
- }
- async deleteCompletelyRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike): Promise<void> {
- await this.deleteCompletelyDescendantsWithStream(page, user, options, false);
- await PageOperation.findByIdAndDelete(pageOpId);
- // no sub operation available
- }
- private async deleteCompletelyV4(page, user, options = {}, isRecursively = false, preventEmitting = false) {
- const ids = [page._id];
- const paths = [page.path];
- logger.debug('Deleting completely', paths);
- await this.deleteCompletelyOperation(ids, paths);
- if (isRecursively) {
- this.deleteCompletelyDescendantsWithStream(page, user, options);
- }
- if (!page.isEmpty && !preventEmitting) {
- this.pageEvent.emit('deleteCompletely', page, user);
- }
- return;
- }
- async emptyTrashPage(user, options = {}) {
- return this.deleteCompletelyDescendantsWithStream({ path: '/trash' }, user, options);
- }
- /**
- * Create delete completely stream
- */
- private async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true): Promise<number> {
- let readStream;
- if (shouldUseV4Process) { // pages don't have parents
- readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
- }
- else {
- const factory = new PageCursorsForDescendantsFactory(user, targetPage, true);
- readStream = await factory.generateReadable();
- }
- let count = 0;
- let nDeletedNonEmptyPages = 0; // used for updating descendantCount
- const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
- const writeStream = new Writable({
- objectMode: true,
- async write(batch, encoding, callback) {
- nDeletedNonEmptyPages += batch.filter(d => !d.isEmpty).length;
- try {
- count += batch.length;
- await deleteMultipleCompletely(batch, user, options);
- logger.debug(`Adding pages progressing: (count=${count})`);
- }
- catch (err) {
- logger.error('addAllPages error on add anyway: ', err);
- }
- callback();
- },
- final(callback) {
- logger.debug(`Adding pages has completed: (totalCount=${count})`);
- callback();
- },
- });
- readStream
- .pipe(createBatchStream(BULK_REINDEX_SIZE))
- .pipe(writeStream);
- await streamToPromise(readStream);
- return nDeletedNonEmptyPages;
- }
- // no need to separate Main Sub since it is devided into single page operations
- async deleteMultiplePages(pagesToDelete, user, options): Promise<void> {
- const { isRecursively, isCompletely } = options;
- if (pagesToDelete.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
- throw Error(`The maximum number of pages is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
- }
- // omit duplicate paths if isRecursively true, omit empty pages if isRecursively false
- const pages = isRecursively ? omitDuplicateAreaPageFromPages(pagesToDelete) : pagesToDelete.filter(p => !p.isEmpty);
- if (isCompletely) {
- for await (const page of pages) {
- await this.deleteCompletely(page, user, {}, isRecursively);
- }
- }
- else {
- for await (const page of pages) {
- await this.deletePage(page, user, {}, isRecursively);
- }
- }
- }
- // use the same process in both v4 and v5
- private async revertDeletedDescendants(pages, user) {
- const Page = this.crowi.model('Page');
- const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
- const revertPageOperations: any[] = [];
- const fromPathsToDelete: string[] = [];
- pages.forEach((page) => {
- // e.g. page.path = /trash/test, toPath = /test
- const toPath = Page.getRevertDeletedPageName(page.path);
- revertPageOperations.push({
- updateOne: {
- filter: { _id: page._id },
- update: {
- $set: {
- path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
- },
- },
- },
- });
- fromPathsToDelete.push(page.path);
- });
- try {
- await Page.bulkWrite(revertPageOperations);
- await PageRedirect.deleteMany({ fromPath: { $in: fromPathsToDelete } });
- }
- catch (err) {
- if (err.code !== 11000) {
- throw new Error(`Failed to revert pages: ${err}`);
- }
- }
- }
- async revertDeletedPage(page, user, options = {}, isRecursively = false) {
- /*
- * Common Operation
- */
- const Page = this.crowi.model('Page');
- const PageTagRelation = this.crowi.model('PageTagRelation');
- // 1. Separate v4 & v5 process
- const shouldUseV4Process = this.shouldUseV4ProcessForRevert(page);
- if (shouldUseV4Process) {
- return this.revertDeletedPageV4(page, user, options, isRecursively);
- }
- const newPath = Page.getRevertDeletedPageName(page.path);
- const includeEmpty = true;
- const originPage = await Page.findByPath(newPath, includeEmpty);
- // throw if any page already exists
- if (originPage != null) {
- throw Error(`This page cannot be reverted since a page with path "${originPage.path}" already exists. Rename the existing pages first.`);
- }
- // 2. Revert target
- const parent = await Page.getParentAndFillAncestors(newPath);
- const updatedPage = await Page.findByIdAndUpdate(page._id, {
- $set: {
- path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null, parent: parent._id, descendantCount: 0,
- },
- }, { new: true });
- await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
- if (!isRecursively) {
- await this.updateDescendantCountOfAncestors(parent._id, 1, true);
- }
- else {
- let pageOp;
- try {
- pageOp = await PageOperation.create({
- actionType: PageActionType.Revert,
- actionStage: PageActionStage.Main,
- page,
- user,
- fromPath: page.path,
- toPath: newPath,
- options,
- });
- }
- catch (err) {
- logger.error('Failed to create PageOperation document.', err);
- throw err;
- }
- /*
- * Resumable Operation
- */
- this.revertRecursivelyMainOperation(page, user, options, pageOp._id);
- }
- return updatedPage;
- }
- async revertRecursivelyMainOperation(page, user, options, pageOpId: ObjectIdLike): Promise<void> {
- const Page = mongoose.model('Page') as unknown as PageModel;
- await this.revertDeletedDescendantsWithStream(page, user, options, false);
- const newPath = Page.getRevertDeletedPageName(page.path);
- // normalize parent of descendant pages
- const shouldNormalize = this.shouldNormalizeParent(page);
- if (shouldNormalize) {
- try {
- await this.normalizeParentAndDescendantCountOfDescendants(newPath);
- logger.info(`Successfully normalized reverted descendant pages under "${newPath}"`);
- }
- catch (err) {
- logger.error('Failed to normalize descendants afrer revert:', err);
- throw err;
- }
- }
- // Set to Sub
- const pageOp = await PageOperation.findByIdAndUpdatePageActionStage(pageOpId, PageActionStage.Sub);
- if (pageOp == null) {
- throw Error('PageOperation document not found');
- }
- /*
- * Sub Operation
- */
- await this.revertRecursivelySubOperation(page, newPath, pageOp._id);
- }
- async revertRecursivelySubOperation(page, newPath: string, pageOpId: ObjectIdLike): Promise<void> {
- const Page = mongoose.model('Page') as unknown as PageModel;
- const newTarget = await Page.findOne({ path: newPath }); // only one page will be found since duplicating to existing path is forbidden
- if (newTarget == null) {
- throw Error('No reverted page found. Something might have gone wrong in revertRecursivelyMainOperation.');
- }
- // update descendantCount of ancestors'
- await this.updateDescendantCountOfAncestors(page.parent, newTarget.descendantCount + 1, true);
- await PageOperation.findByIdAndDelete(pageOpId);
- }
- private async revertDeletedPageV4(page, user, options = {}, isRecursively = false) {
- const Page = this.crowi.model('Page');
- const PageTagRelation = this.crowi.model('PageTagRelation');
- const newPath = Page.getRevertDeletedPageName(page.path);
- const originPage = await Page.findByPath(newPath);
- if (originPage != null) {
- throw Error(`This page cannot be reverted since a page with path "${originPage.path}" already exists.`);
- }
- if (isRecursively) {
- this.revertDeletedDescendantsWithStream(page, user, options);
- }
- page.status = Page.STATUS_PUBLISHED;
- page.lastUpdateUser = user;
- debug('Revert deleted the page', page, newPath);
- const updatedPage = await Page.findByIdAndUpdate(page._id, {
- $set: {
- path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
- },
- }, { new: true });
- await PageTagRelation.updateMany({ relatedPage: page._id }, { $set: { isPageTrashed: false } });
- return updatedPage;
- }
- /**
- * Create revert stream
- */
- private async revertDeletedDescendantsWithStream(targetPage, user, options = {}, shouldUseV4Process = true): Promise<number> {
- if (shouldUseV4Process) {
- return this.revertDeletedDescendantsWithStreamV4(targetPage, user, options);
- }
- const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
- const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
- let count = 0;
- const writeStream = new Writable({
- objectMode: true,
- async write(batch, encoding, callback) {
- try {
- count += batch.length;
- await revertDeletedDescendants(batch, user);
- logger.debug(`Reverting pages progressing: (count=${count})`);
- }
- catch (err) {
- logger.error('revertPages error on add anyway: ', err);
- }
- callback();
- },
- async final(callback) {
- logger.debug(`Reverting pages has completed: (totalCount=${count})`);
- callback();
- },
- });
- readStream
- .pipe(createBatchStream(BULK_REINDEX_SIZE))
- .pipe(writeStream);
- await streamToPromise(readStream);
- return count;
- }
- private async revertDeletedDescendantsWithStreamV4(targetPage, user, options = {}) {
- const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
- const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
- let count = 0;
- const writeStream = new Writable({
- objectMode: true,
- async write(batch, encoding, callback) {
- try {
- count += batch.length;
- await revertDeletedDescendants(batch, user);
- logger.debug(`Reverting pages progressing: (count=${count})`);
- }
- catch (err) {
- logger.error('revertPages error on add anyway: ', err);
- }
- callback();
- },
- final(callback) {
- logger.debug(`Reverting pages has completed: (totalCount=${count})`);
- callback();
- },
- });
- readStream
- .pipe(createBatchStream(BULK_REINDEX_SIZE))
- .pipe(writeStream);
- await streamToPromise(readStream);
- return count;
- }
- async handlePrivatePagesForGroupsToDelete(groupsToDelete, action, transferToUserGroupId, user) {
- const Page = this.crowi.model('Page');
- const pages = await Page.find({ grantedGroup: { $in: groupsToDelete } });
- switch (action) {
- case 'public':
- await Page.publicizePages(pages);
- break;
- case 'delete':
- return this.deleteMultipleCompletely(pages, user);
- case 'transfer':
- await Page.transferPagesToGroup(pages, transferToUserGroupId);
- break;
- default:
- throw new Error('Unknown action for private pages');
- }
- }
- private extractStringIds(refs: Ref<HasObjectId>[]) {
- return refs.map((ref: Ref<HasObjectId>) => {
- return (typeof ref === 'string') ? ref : ref._id.toString();
- });
- }
- constructBasicPageInfo(page: IPage, isGuestUser?: boolean): IPageInfo | IPageInfoForEntity {
- const isMovable = isGuestUser ? false : isMovablePage(page.path);
- if (page.isEmpty) {
- return {
- isEmpty: true,
- isMovable,
- isDeletable: false,
- isAbleToDeleteCompletely: false,
- isRevertible: false,
- };
- }
- const likers = page.liker.slice(0, 15) as Ref<IUserHasId>[];
- const seenUsers = page.seenUsers.slice(0, 15) as Ref<IUserHasId>[];
- return {
- isEmpty: false,
- sumOfLikers: page.liker.length,
- likerIds: this.extractStringIds(likers),
- seenUserIds: this.extractStringIds(seenUsers),
- sumOfSeenUsers: page.seenUsers.length,
- isMovable,
- isDeletable: isMovable,
- isAbleToDeleteCompletely: false,
- isRevertible: isTrashPage(page.path),
- };
- }
- async shortBodiesMapByPageIds(pageIds: ObjectId[] = [], user): Promise<Record<string, string | null>> {
- const Page = mongoose.model('Page');
- const MAX_LENGTH = 350;
- // aggregation options
- const viewerCondition = await generateGrantCondition(user, null);
- const filterByIds = {
- _id: { $in: pageIds },
- };
- let pages;
- try {
- pages = await Page
- .aggregate([
- // filter by pageIds
- {
- $match: filterByIds,
- },
- // filter by viewer
- viewerCondition,
- // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
- {
- $lookup: {
- from: 'revisions',
- let: { localRevision: '$revision' },
- pipeline: [
- {
- $match: {
- $expr: {
- $eq: ['$_id', '$$localRevision'],
- },
- },
- },
- {
- $project: {
- // What is $substrCP?
- // see: https://stackoverflow.com/questions/43556024/mongodb-error-substrbytes-invalid-range-ending-index-is-in-the-middle-of-a-ut/43556249
- revision: { $substrCP: ['$body', 0, MAX_LENGTH] },
- },
- },
- ],
- as: 'revisionData',
- },
- },
- // projection
- {
- $project: {
- _id: 1,
- revisionData: 1,
- },
- },
- ]).exec();
- }
- catch (err) {
- logger.error('Error occurred while generating shortBodiesMap');
- throw err;
- }
- const shortBodiesMap = {};
- pages.forEach((page) => {
- shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
- });
- return shortBodiesMap;
- }
- private async createAndSendNotifications(page, user, action) {
- const { activityService, inAppNotificationService } = this.crowi;
- const snapshot = stringifySnapshot(page);
- // Create activity
- const parameters = {
- user: user._id,
- targetModel: ActivityDefine.MODEL_PAGE,
- target: page,
- action,
- };
- const activity = await activityService.createByParameters(parameters);
- // Get user to be notified
- const targetUsers = await activity.getNotificationTargetUsers();
- // Create and send notifications
- await inAppNotificationService.upsertByActivity(targetUsers, activity, snapshot);
- await inAppNotificationService.emitSocketIo(targetUsers);
- }
- async normalizeParentByPageIds(pageIds: ObjectIdLike[], user, isRecursively: boolean): Promise<void> {
- if (isRecursively) {
- const Page = mongoose.model('Page') as unknown as PageModel;
- const pages = await Page.findByPageIdsToEdit(pageIds, user, false);
- // DO NOT await !!
- this.normalizeParentRecursivelyByPages(pages, user);
- return;
- }
- for await (const pageId of pageIds) {
- try {
- const normalizedPage = await this.normalizeParentByPageId(pageId, user);
- if (normalizedPage == null) {
- logger.error(`Failed to update descendantCount of page of id: "${pageId}"`);
- }
- else {
- // update descendantCount of ancestors'
- await this.updateDescendantCountOfAncestors(pageId, normalizedPage.descendantCount, false);
- }
- }
- catch (err) {
- // socket.emit('normalizeParentByPageIds', { error: err.message }); TODO: use socket to tell user
- }
- }
- }
- private async normalizeParentByPageId(page, user) {
- const Page = mongoose.model('Page') as unknown as PageModel;
- const {
- path, grant, grantedUsers: grantedUserIds, grantedGroup: grantedGroupId,
- } = page;
- // check if any page exists at target path already
- const existingPage = await Page.findOne({ path });
- if (existingPage != null && !existingPage.isEmpty) {
- throw Error('Page already exists. Please rename the page to continue.');
- }
- /*
- * UserGroup & Owner validation
- */
- if (grant !== Page.GRANT_RESTRICTED) {
- let isGrantNormalized = false;
- try {
- const shouldCheckDescendants = true;
- isGrantNormalized = await this.crowi.pageGrantService.isGrantNormalized(path, grant, grantedUserIds, grantedGroupId, shouldCheckDescendants);
- }
- catch (err) {
- logger.error(`Failed to validate grant of page at "${path}"`, err);
- throw err;
- }
- if (!isGrantNormalized) {
- throw Error('This page cannot be migrated since the selected grant or grantedGroup is not assignable to this page.');
- }
- }
- else {
- throw Error('Restricted pages can not be migrated');
- }
- let updatedPage;
- // replace if empty page exists
- if (existingPage != null && existingPage.isEmpty) {
- await Page.replaceTargetWithPage(existingPage, page, true);
- updatedPage = await Page.findById(page._id);
- }
- else {
- // getParentAndFillAncestors
- const parent = await Page.getParentAndFillAncestors(page.path);
- updatedPage = await Page.findOneAndUpdate({ _id: page._id }, { parent: parent._id }, { new: true });
- }
- return updatedPage;
- }
- async normalizeParentRecursivelyByPages(pages, user): Promise<void> {
- /*
- * Main Operation
- */
- if (pages == null || pages.length === 0) {
- logger.error('pageIds is null or 0 length.');
- return;
- }
- if (pages.length > LIMIT_FOR_MULTIPLE_PAGE_OP) {
- throw Error(`The maximum number of pageIds allowed is ${LIMIT_FOR_MULTIPLE_PAGE_OP}.`);
- }
- const pagesToNormalize = omitDuplicateAreaPageFromPages(pages);
- let normalizablePages;
- let nonNormalizablePages;
- try {
- [normalizablePages, nonNormalizablePages] = await this.crowi.pageGrantService.separateNormalizableAndNotNormalizablePages(pagesToNormalize);
- }
- catch (err) {
- throw err;
- }
- if (normalizablePages.length === 0) {
- // socket.emit('normalizeParentRecursivelyByPages', { error: err.message }); TODO: use socket to tell user
- return;
- }
- if (nonNormalizablePages.length !== 0) {
- // TODO: iterate nonNormalizablePages and send socket error to client so that the user can know which path failed to migrate
- // socket.emit('normalizeParentRecursivelyByPages', { error: err.message }); TODO: use socket to tell user
- }
- /*
- * Main Operation (s)
- */
- for await (const page of normalizablePages) {
- await this.normalizeParentRecursivelyMainOperation(page, user);
- }
- }
- async normalizeParentRecursivelyMainOperation(page, user): Promise<void> {
- // TODO: insertOne PageOperationBlock
- try {
- await this.normalizeParentRecursively([page.path]);
- }
- catch (err) {
- logger.error('V5 initial miration failed.', err);
- // socket.emit('normalizeParentRecursivelyByPageIds', { error: err.message }); TODO: use socket to tell user
- throw err;
- }
- await this.normalizeParentRecursivelySubOperation(page, user);
- }
- async normalizeParentRecursivelySubOperation(page, user): Promise<void> {
- const Page = mongoose.model('Page') as unknown as PageModel;
- try {
- // update descendantCount of self and descendant pages first
- await this.updateDescendantCountOfSelfAndDescendants(page.path);
- // find pages again to get updated descendantCount
- // then calculate inc
- const pageAfterUpdatingDescendantCount = await Page.findByIdAndViewer(page._id, user);
- const exDescendantCount = page.descendantCount;
- const newDescendantCount = pageAfterUpdatingDescendantCount.descendantCount;
- const inc = newDescendantCount - exDescendantCount;
- await this.updateDescendantCountOfAncestors(page._id, inc, false);
- }
- catch (err) {
- logger.error('Failed to update descendantCount after normalizing parent:', err);
- throw Error(`Failed to update descendantCount after normalizing parent: ${err}`);
- }
- }
- async _isPagePathIndexUnique() {
- const Page = this.crowi.model('Page');
- const now = (new Date()).toString();
- const path = `growi_check_is_path_index_unique_${now}`;
- let isUnique = false;
- try {
- await Page.insertMany([
- { path },
- { path },
- ]);
- }
- catch (err) {
- if (err?.code === 11000) { // Error code 11000 indicates the index is unique
- isUnique = true;
- logger.info('Page path index is unique.');
- }
- else {
- throw err;
- }
- }
- finally {
- await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
- }
- return isUnique;
- }
- // TODO: use socket to send status to the client
- async normalizeAllPublicPages() {
- // const socket = this.crowi.socketIoService.getAdminSocket();
- let isUnique;
- try {
- isUnique = await this._isPagePathIndexUnique();
- }
- catch (err) {
- logger.error('Failed to check path index status', err);
- throw err;
- }
- // drop unique index first
- if (isUnique) {
- try {
- await this._v5NormalizeIndex();
- }
- catch (err) {
- logger.error('V5 index normalization failed.', err);
- // socket.emit('v5IndexNormalizationFailed', { error: err.message });
- throw err;
- }
- }
- // then migrate
- try {
- await this.normalizeParentRecursively(['/'], true);
- }
- catch (err) {
- logger.error('V5 initial miration failed.', err);
- // socket.emit('v5InitialMirationFailed', { error: err.message });
- throw err;
- }
- // update descendantCount of all public pages
- try {
- await this.updateDescendantCountOfSelfAndDescendants('/');
- logger.info('Successfully updated all descendantCount of public pages.');
- }
- catch (err) {
- logger.error('Failed updating descendantCount of public pages.', err);
- throw err;
- }
- await this._setIsV5CompatibleTrue();
- }
- private async _setIsV5CompatibleTrue() {
- try {
- await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
- 'app:isV5Compatible': true,
- });
- logger.info('Successfully migrated all public pages.');
- }
- catch (err) {
- logger.warn('Failed to update app:isV5Compatible to true.');
- throw err;
- }
- }
- private async normalizeParentAndDescendantCountOfDescendants(path: string): Promise<void> {
- await this.normalizeParentRecursively([path]);
- // update descendantCount of descendant pages
- await this.updateDescendantCountOfSelfAndDescendants(path);
- }
- async normalizeParentRecursively(paths: string[], publicOnly = false): Promise<void> {
- const ancestorPaths = paths.flatMap(p => collectAncestorPaths(p));
- const regexps = paths.map(p => new RegExp(`^${escapeStringRegexp(p)}`, 'i'));
- return this._normalizeParentRecursively(regexps, ancestorPaths, publicOnly);
- }
- // TODO: use websocket to show progress
- private async _normalizeParentRecursively(regexps: RegExp[], pathsToInclude: string[], publicOnly: boolean): Promise<void> {
- const BATCH_SIZE = 100;
- const PAGES_LIMIT = 1000;
- const Page = mongoose.model('Page') as unknown as PageModel;
- const { PageQueryBuilder } = Page;
- // GRANT_RESTRICTED and GRANT_SPECIFIED will never have parent
- const grantFilter: any = {
- $and: [
- { grant: { $ne: Page.GRANT_RESTRICTED } },
- { grant: { $ne: Page.GRANT_SPECIFIED } },
- ],
- };
- if (publicOnly) { // add grant condition if not null
- grantFilter.$and = [...grantFilter.$and, { grant: Page.GRANT_PUBLIC }];
- }
- // generate filter
- const filter: any = {
- $and: [
- {
- parent: null,
- status: Page.STATUS_PUBLISHED,
- path: { $ne: '/' },
- },
- ],
- };
- let pathCondition: (RegExp | string)[] = [];
- if (regexps.length > 0) {
- pathCondition = [...regexps];
- }
- if (pathsToInclude.length > 0) {
- pathCondition = [...pathCondition, ...pathsToInclude];
- }
- if (pathCondition.length > 0) {
- filter.$and.push({
- parent: null,
- status: Page.STATUS_PUBLISHED,
- path: { $in: pathCondition },
- });
- }
- const total = await Page.countDocuments(filter);
- let baseAggregation = Page
- .aggregate([
- { $match: grantFilter },
- { $match: filter },
- {
- $project: { // minimize data to fetch
- _id: 1,
- path: 1,
- },
- },
- ]);
- // limit pages to get
- if (total > PAGES_LIMIT) {
- baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
- }
- const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
- // use batch stream
- const batchStream = createBatchStream(BATCH_SIZE);
- let countPages = 0;
- let shouldContinue = true;
- // migrate all siblings for each page
- const migratePagesStream = new Writable({
- objectMode: true,
- async write(pages, encoding, callback) {
- // make list to create empty pages
- const parentPathsSet = new Set<string>(pages.map(page => pathlib.dirname(page.path)));
- const parentPaths = Array.from(parentPathsSet);
- // fill parents with empty pages
- await Page.createEmptyPagesByPaths(parentPaths, publicOnly);
- // find parents again
- const builder = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }), true);
- const parents = await builder
- .addConditionToListByPathsArray(parentPaths)
- .query
- .lean()
- .exec();
- // bulkWrite to update parent
- const updateManyOperations = parents.map((parent) => {
- const parentId = parent._id;
- // modify to adjust for RegExp
- let parentPath = parent.path === '/' ? '' : parent.path;
- parentPath = escapeStringRegexp(parentPath);
- const filter: any = {
- // regexr.com/6889f
- // ex. /parent/any_child OR /any_level1
- path: { $regex: new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`, 'i') },
- };
- if (publicOnly) {
- filter.grant = Page.GRANT_PUBLIC;
- }
- return {
- updateMany: {
- filter,
- update: {
- parent: parentId,
- },
- },
- };
- });
- try {
- const res = await Page.bulkWrite(updateManyOperations);
- countPages += res.result.nModified;
- logger.info(`Page migration processing: (count=${countPages})`);
- // throw
- if (res.result.writeErrors.length > 0) {
- logger.error('Failed to migrate some pages', res.result.writeErrors);
- throw Error('Failed to migrate some pages');
- }
- // finish migration
- if (res.result.nModified === 0 && res.result.nMatched === 0) {
- shouldContinue = false;
- logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
- }
- }
- catch (err) {
- logger.error('Failed to update page.parent.', err);
- throw err;
- }
- callback();
- },
- final(callback) {
- callback();
- },
- });
- pagesStream
- .pipe(batchStream)
- .pipe(migratePagesStream);
- await streamToPromise(migratePagesStream);
- const existsFilter = { $and: [...grantFilter.$and, ...filter.$and] };
- if (await Page.exists(existsFilter) && shouldContinue) {
- return this._normalizeParentRecursively(regexps, pathsToInclude, publicOnly);
- }
- }
- private async _v5NormalizeIndex() {
- const collection = mongoose.connection.collection('pages');
- try {
- // drop pages.path_1 indexes
- await collection.dropIndex('path_1');
- logger.info('Succeeded to drop unique indexes from pages.path.');
- }
- catch (err) {
- logger.warn('Failed to drop unique indexes from pages.path.', err);
- throw err;
- }
- try {
- // create indexes without
- await collection.createIndex({ path: 1 }, { unique: false });
- logger.info('Succeeded to create non-unique indexes on pages.path.');
- }
- catch (err) {
- logger.warn('Failed to create non-unique indexes on pages.path.', err);
- throw err;
- }
- }
- async countPagesCanNormalizeParentByUser(user): Promise<number> {
- if (user == null) {
- throw Error('user is required');
- }
- const Page = mongoose.model('Page') as unknown as PageModel;
- const { PageQueryBuilder } = Page;
- const builder = new PageQueryBuilder(Page.count(), false);
- await builder.addConditionAsMigratablePages(user);
- const nMigratablePages = await builder.query.exec();
- return nMigratablePages;
- }
- /**
- * update descendantCount of the following pages
- * - page that has the same path as the provided path
- * - pages that are descendants of the above page
- */
- async updateDescendantCountOfSelfAndDescendants(path: string): Promise<void> {
- const BATCH_SIZE = 200;
- const Page = this.crowi.model('Page');
- const { PageQueryBuilder } = Page;
- const builder = new PageQueryBuilder(Page.find(), true);
- builder.addConditionAsMigrated();
- builder.addConditionToListWithDescendants(path);
- builder.addConditionToSortPagesByDescPath();
- const aggregatedPages = await builder.query.lean().cursor({ batchSize: BATCH_SIZE });
- const recountWriteStream = new Writable({
- objectMode: true,
- async write(pageDocuments, encoding, callback) {
- for await (const document of pageDocuments) {
- const descendantCount = await Page.recountDescendantCount(document._id);
- await Page.findByIdAndUpdate(document._id, { descendantCount });
- }
- callback();
- },
- final(callback) {
- callback();
- },
- });
- aggregatedPages
- .pipe(createBatchStream(BATCH_SIZE))
- .pipe(recountWriteStream);
- await streamToPromise(recountWriteStream);
- }
- // update descendantCount of all pages that are ancestors of a provided pageId by count
- async updateDescendantCountOfAncestors(pageId: ObjectIdLike, inc: number, shouldIncludeTarget: boolean): Promise<void> {
- const Page = this.crowi.model('Page');
- const ancestors = await Page.findAncestorsUsingParentRecursively(pageId, shouldIncludeTarget);
- const ancestorPageIds = ancestors.map(p => p._id);
- await Page.incrementDescendantCountOfPageIds(ancestorPageIds, inc);
- }
- }
- export default PageService;
|