mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-09-21 21:50:49 +02:00
🚀 feat: Banner (#3952)
* feat: Add banner schema and model * feat: Add optional JwtAuth To handle the conditional logic with and without authentication within the model. * feat: Add an endpoint to retrieve a banner * feat: Add implementation for client to use banner and access API * feat: Display a banner on UI * feat: Script for updating and deleting banners * style: Update banner style * fix: Adjust the height when the banner is displayed * fix: failed specs
This commit is contained in:
parent
07e5531b5b
commit
aea01f0bc5
26 changed files with 453 additions and 4 deletions
27
api/models/Banner.js
Normal file
27
api/models/Banner.js
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
const Banner = require('./schema/banner');
|
||||||
|
const logger = require('~/config/winston');
|
||||||
|
/**
|
||||||
|
* Retrieves the current active banner.
|
||||||
|
* @returns {Promise<Object|null>} The active banner object or null if no active banner is found.
|
||||||
|
*/
|
||||||
|
const getBanner = async (user) => {
|
||||||
|
try {
|
||||||
|
const now = new Date();
|
||||||
|
const banner = await Banner.findOne({
|
||||||
|
displayFrom: { $lte: now },
|
||||||
|
$or: [{ displayTo: { $gte: now } }, { displayTo: null }],
|
||||||
|
type: 'banner',
|
||||||
|
}).lean();
|
||||||
|
|
||||||
|
if (!banner || banner.isPublic || user) {
|
||||||
|
return banner;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('[getBanners] Error getting banners', error);
|
||||||
|
throw new Error('Error getting banners');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = { getBanner };
|
36
api/models/schema/banner.js
Normal file
36
api/models/schema/banner.js
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
const mongoose = require('mongoose');
|
||||||
|
|
||||||
|
const bannerSchema = mongoose.Schema(
|
||||||
|
{
|
||||||
|
bannerId: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
message: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
displayFrom: {
|
||||||
|
type: Date,
|
||||||
|
required: true,
|
||||||
|
default: Date.now,
|
||||||
|
},
|
||||||
|
displayTo: {
|
||||||
|
type: Date,
|
||||||
|
},
|
||||||
|
type: {
|
||||||
|
type: String,
|
||||||
|
enum: ['banner', 'popup'],
|
||||||
|
default: 'banner',
|
||||||
|
},
|
||||||
|
isPublic: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
{ timestamps: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
const Banner = mongoose.model('Banner', bannerSchema);
|
||||||
|
module.exports = Banner;
|
|
@ -106,6 +106,7 @@ const startServer = async () => {
|
||||||
app.use('/api/share', routes.share);
|
app.use('/api/share', routes.share);
|
||||||
app.use('/api/roles', routes.roles);
|
app.use('/api/roles', routes.roles);
|
||||||
app.use('/api/agents', routes.agents);
|
app.use('/api/agents', routes.agents);
|
||||||
|
app.use('/api/banner', routes.banner);
|
||||||
app.use('/api/bedrock', routes.bedrock);
|
app.use('/api/bedrock', routes.bedrock);
|
||||||
|
|
||||||
app.use('/api/tags', routes.tags);
|
app.use('/api/tags', routes.tags);
|
||||||
|
|
17
api/server/middleware/optionalJwtAuth.js
Normal file
17
api/server/middleware/optionalJwtAuth.js
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
const passport = require('passport');
|
||||||
|
|
||||||
|
// This middleware does not require authentication,
|
||||||
|
// but if the user is authenticated, it will set the user object.
|
||||||
|
const optionalJwtAuth = (req, res, next) => {
|
||||||
|
passport.authenticate('jwt', { session: false }, (err, user) => {
|
||||||
|
if (err) {
|
||||||
|
return next(err);
|
||||||
|
}
|
||||||
|
if (user) {
|
||||||
|
req.user = user;
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
})(req, res, next);
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = optionalJwtAuth;
|
15
api/server/routes/banner.js
Normal file
15
api/server/routes/banner.js
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
const express = require('express');
|
||||||
|
|
||||||
|
const { getBanner } = require('~/models/Banner');
|
||||||
|
const optionalJwtAuth = require('~/server/middleware/optionalJwtAuth');
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.get('/', optionalJwtAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
res.status(200).send(await getBanner(req.user));
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ message: 'Error getting banner' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
|
@ -24,6 +24,7 @@ const edit = require('./edit');
|
||||||
const keys = require('./keys');
|
const keys = require('./keys');
|
||||||
const user = require('./user');
|
const user = require('./user');
|
||||||
const ask = require('./ask');
|
const ask = require('./ask');
|
||||||
|
const banner = require('./banner');
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
ask,
|
ask,
|
||||||
|
@ -52,4 +53,5 @@ module.exports = {
|
||||||
assistants,
|
assistants,
|
||||||
categories,
|
categories,
|
||||||
staticRoute,
|
staticRoute,
|
||||||
|
banner,
|
||||||
};
|
};
|
||||||
|
|
|
@ -3,6 +3,7 @@ import { BlinkAnimation } from './BlinkAnimation';
|
||||||
import { TStartupConfig } from 'librechat-data-provider';
|
import { TStartupConfig } from 'librechat-data-provider';
|
||||||
import SocialLoginRender from './SocialLoginRender';
|
import SocialLoginRender from './SocialLoginRender';
|
||||||
import { ThemeSelector } from '~/components/ui';
|
import { ThemeSelector } from '~/components/ui';
|
||||||
|
import { Banner } from '../Banners';
|
||||||
import Footer from './Footer';
|
import Footer from './Footer';
|
||||||
|
|
||||||
const ErrorRender = ({ children }: { children: React.ReactNode }) => (
|
const ErrorRender = ({ children }: { children: React.ReactNode }) => (
|
||||||
|
@ -56,6 +57,7 @@ function AuthLayout({
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative flex min-h-screen flex-col bg-white dark:bg-gray-900">
|
<div className="relative flex min-h-screen flex-col bg-white dark:bg-gray-900">
|
||||||
|
<Banner />
|
||||||
<BlinkAnimation active={isFetching}>
|
<BlinkAnimation active={isFetching}>
|
||||||
<div className="mt-6 h-10 w-full bg-cover">
|
<div className="mt-6 h-10 w-full bg-cover">
|
||||||
<img src="/assets/logo.svg" className="h-full w-full object-contain" alt="Logo" />
|
<img src="/assets/logo.svg" className="h-full w-full object-contain" alt="Logo" />
|
||||||
|
|
|
@ -54,6 +54,11 @@ const setup = ({
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
useGetStartupConfigReturnValue = mockStartupConfig,
|
useGetStartupConfigReturnValue = mockStartupConfig,
|
||||||
|
useGetBannerQueryReturnValue = {
|
||||||
|
isLoading: false,
|
||||||
|
isError: false,
|
||||||
|
data: {},
|
||||||
|
},
|
||||||
} = {}) => {
|
} = {}) => {
|
||||||
const mockUseLoginUser = jest
|
const mockUseLoginUser = jest
|
||||||
.spyOn(mockDataProvider, 'useLoginUserMutation')
|
.spyOn(mockDataProvider, 'useLoginUserMutation')
|
||||||
|
@ -71,6 +76,10 @@ const setup = ({
|
||||||
.spyOn(mockDataProvider, 'useRefreshTokenMutation')
|
.spyOn(mockDataProvider, 'useRefreshTokenMutation')
|
||||||
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
|
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
|
||||||
.mockReturnValue(useRefreshTokenMutationReturnValue);
|
.mockReturnValue(useRefreshTokenMutationReturnValue);
|
||||||
|
const mockUseGetBannerQuery = jest
|
||||||
|
.spyOn(mockDataProvider, 'useGetBannerQuery')
|
||||||
|
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
|
||||||
|
.mockReturnValue(useGetBannerQueryReturnValue);
|
||||||
const mockUseOutletContext = jest.spyOn(reactRouter, 'useOutletContext').mockReturnValue({
|
const mockUseOutletContext = jest.spyOn(reactRouter, 'useOutletContext').mockReturnValue({
|
||||||
startupConfig: useGetStartupConfigReturnValue.data,
|
startupConfig: useGetStartupConfigReturnValue.data,
|
||||||
});
|
});
|
||||||
|
@ -93,6 +102,7 @@ const setup = ({
|
||||||
mockUseOutletContext,
|
mockUseOutletContext,
|
||||||
mockUseGetStartupConfig,
|
mockUseGetStartupConfig,
|
||||||
mockUseRefreshTokenMutation,
|
mockUseRefreshTokenMutation,
|
||||||
|
mockUseGetBannerQuery,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -59,6 +59,11 @@ const setup = ({
|
||||||
isError: false,
|
isError: false,
|
||||||
data: mockStartupConfig,
|
data: mockStartupConfig,
|
||||||
},
|
},
|
||||||
|
useGetBannerQueryReturnValue = {
|
||||||
|
isLoading: false,
|
||||||
|
isError: false,
|
||||||
|
data: {},
|
||||||
|
},
|
||||||
} = {}) => {
|
} = {}) => {
|
||||||
const mockUseLoginUser = jest
|
const mockUseLoginUser = jest
|
||||||
.spyOn(mockDataProvider, 'useLoginUserMutation')
|
.spyOn(mockDataProvider, 'useLoginUserMutation')
|
||||||
|
@ -76,11 +81,16 @@ const setup = ({
|
||||||
.spyOn(mockDataProvider, 'useRefreshTokenMutation')
|
.spyOn(mockDataProvider, 'useRefreshTokenMutation')
|
||||||
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
|
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
|
||||||
.mockReturnValue(useRefreshTokenMutationReturnValue);
|
.mockReturnValue(useRefreshTokenMutationReturnValue);
|
||||||
|
const mockUseGetBannerQuery = jest
|
||||||
|
.spyOn(mockDataProvider, 'useGetBannerQuery')
|
||||||
|
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
|
||||||
|
.mockReturnValue(useGetBannerQueryReturnValue);
|
||||||
return {
|
return {
|
||||||
mockUseLoginUser,
|
mockUseLoginUser,
|
||||||
mockUseGetUserQuery,
|
mockUseGetUserQuery,
|
||||||
mockUseGetStartupConfig,
|
mockUseGetStartupConfig,
|
||||||
mockUseRefreshTokenMutation,
|
mockUseRefreshTokenMutation,
|
||||||
|
mockUseGetBannerQuery,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -50,6 +50,11 @@ const setup = ({
|
||||||
user: {},
|
user: {},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
useGetBannerQueryReturnValue = {
|
||||||
|
isLoading: false,
|
||||||
|
isError: false,
|
||||||
|
data: {},
|
||||||
|
},
|
||||||
useGetStartupConfigReturnValue = mockStartupConfig,
|
useGetStartupConfigReturnValue = mockStartupConfig,
|
||||||
} = {}) => {
|
} = {}) => {
|
||||||
const mockUseRegisterUserMutation = jest
|
const mockUseRegisterUserMutation = jest
|
||||||
|
@ -71,6 +76,10 @@ const setup = ({
|
||||||
const mockUseOutletContext = jest.spyOn(reactRouter, 'useOutletContext').mockReturnValue({
|
const mockUseOutletContext = jest.spyOn(reactRouter, 'useOutletContext').mockReturnValue({
|
||||||
startupConfig: useGetStartupConfigReturnValue.data,
|
startupConfig: useGetStartupConfigReturnValue.data,
|
||||||
});
|
});
|
||||||
|
const mockUseGetBannerQuery = jest
|
||||||
|
.spyOn(mockDataProvider, 'useGetBannerQuery')
|
||||||
|
//@ts-ignore - we don't need all parameters of the QueryObserverSuccessResult
|
||||||
|
.mockReturnValue(useGetBannerQueryReturnValue);
|
||||||
const renderResult = render(
|
const renderResult = render(
|
||||||
<AuthLayout
|
<AuthLayout
|
||||||
startupConfig={useGetStartupConfigReturnValue.data as TStartupConfig}
|
startupConfig={useGetStartupConfigReturnValue.data as TStartupConfig}
|
||||||
|
|
48
client/src/components/Banners/Banner.tsx
Normal file
48
client/src/components/Banners/Banner.tsx
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
import { XIcon } from 'lucide-react';
|
||||||
|
import { useRecoilState } from 'recoil';
|
||||||
|
import { useGetBannerQuery } from 'librechat-data-provider/react-query';
|
||||||
|
import store from '~/store';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
|
||||||
|
export const Banner = ({ onHeightChange }: { onHeightChange?: (height: number) => void }) => {
|
||||||
|
const { data: banner } = useGetBannerQuery();
|
||||||
|
const [hideBannerHint, setHideBannerHint] = useRecoilState<string[]>(store.hideBannerHint);
|
||||||
|
const bannerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (onHeightChange && bannerRef.current) {
|
||||||
|
onHeightChange(bannerRef.current.offsetHeight);
|
||||||
|
}
|
||||||
|
}, [banner, hideBannerHint, onHeightChange]);
|
||||||
|
|
||||||
|
if (!banner || (banner.bannerId && hideBannerHint.includes(banner.bannerId))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const onClick = () => {
|
||||||
|
setHideBannerHint([...hideBannerHint, banner.bannerId]);
|
||||||
|
if (onHeightChange) {
|
||||||
|
onHeightChange(0); // Reset height when banner is closed
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={bannerRef}
|
||||||
|
className="sticky top-0 z-20 flex items-center bg-neutral-900 from-gray-700 to-gray-900 px-2 py-1 text-slate-50 dark:bg-gradient-to-r dark:text-white md:relative"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="w-full truncate px-4 text-center text-sm"
|
||||||
|
dangerouslySetInnerHTML={{ __html: banner.message }}
|
||||||
|
></div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Dismiss banner"
|
||||||
|
className="h-8 w-8 opacity-80 hover:opacity-100"
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
<XIcon className="mx-auto h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
1
client/src/components/Banners/index.ts
Normal file
1
client/src/components/Banners/index.ts
Normal file
|
@ -0,0 +1 @@
|
||||||
|
export { Banner } from './Banner';
|
|
@ -74,7 +74,7 @@ const OGDialogTemplate = forwardRef((props: DialogTemplateProps, ref: Ref<HTMLDi
|
||||||
<div>{leftButtons != null ? leftButtons : null}</div>
|
<div>{leftButtons != null ? leftButtons : null}</div>
|
||||||
<div className="flex h-auto gap-3">
|
<div className="flex h-auto gap-3">
|
||||||
{showCancelButton && (
|
{showCancelButton && (
|
||||||
<OGDialogClose className="btn btn-neutral border-token-border-light relative rounded-lg text-sm ring-offset-2 dark:ring-offset-0 focus:ring-2 focus:ring-black">
|
<OGDialogClose className="btn btn-neutral border-token-border-light relative rounded-lg text-sm ring-offset-2 focus:ring-2 focus:ring-black dark:ring-offset-0">
|
||||||
{Cancel}
|
{Cancel}
|
||||||
</OGDialogClose>
|
</OGDialogClose>
|
||||||
)}
|
)}
|
||||||
|
|
|
@ -8,6 +8,7 @@ import { AgentsMapContext, AssistantsMapContext, FileMapContext, SearchContext }
|
||||||
import { useAuthContext, useAssistantsMap, useAgentsMap, useFileMap, useSearch } from '~/hooks';
|
import { useAuthContext, useAssistantsMap, useAgentsMap, useFileMap, useSearch } from '~/hooks';
|
||||||
import { Nav, MobileNav } from '~/components/Nav';
|
import { Nav, MobileNav } from '~/components/Nav';
|
||||||
import TermsAndConditionsModal from '~/components/ui/TermsAndConditionsModal';
|
import TermsAndConditionsModal from '~/components/ui/TermsAndConditionsModal';
|
||||||
|
import { Banner } from '~/components/Banners';
|
||||||
|
|
||||||
export default function Root() {
|
export default function Root() {
|
||||||
const { isAuthenticated, logout, token } = useAuthContext();
|
const { isAuthenticated, logout, token } = useAuthContext();
|
||||||
|
@ -16,6 +17,7 @@ export default function Root() {
|
||||||
const savedNavVisible = localStorage.getItem('navVisible');
|
const savedNavVisible = localStorage.getItem('navVisible');
|
||||||
return savedNavVisible !== null ? JSON.parse(savedNavVisible) : true;
|
return savedNavVisible !== null ? JSON.parse(savedNavVisible) : true;
|
||||||
});
|
});
|
||||||
|
const [bannerHeight, setBannerHeight] = useState(0);
|
||||||
|
|
||||||
const search = useSearch({ isAuthenticated });
|
const search = useSearch({ isAuthenticated });
|
||||||
const fileMap = useFileMap({ isAuthenticated });
|
const fileMap = useFileMap({ isAuthenticated });
|
||||||
|
@ -24,7 +26,6 @@ export default function Root() {
|
||||||
|
|
||||||
const [showTerms, setShowTerms] = useState(false);
|
const [showTerms, setShowTerms] = useState(false);
|
||||||
const { data: config } = useGetStartupConfig();
|
const { data: config } = useGetStartupConfig();
|
||||||
|
|
||||||
const { data: termsData } = useUserTermsQuery({
|
const { data: termsData } = useUserTermsQuery({
|
||||||
enabled: isAuthenticated && !!config?.interface?.termsOfService?.modalAcceptance,
|
enabled: isAuthenticated && !!config?.interface?.termsOfService?.modalAcceptance,
|
||||||
});
|
});
|
||||||
|
@ -54,7 +55,8 @@ export default function Root() {
|
||||||
<FileMapContext.Provider value={fileMap}>
|
<FileMapContext.Provider value={fileMap}>
|
||||||
<AssistantsMapContext.Provider value={assistantsMap}>
|
<AssistantsMapContext.Provider value={assistantsMap}>
|
||||||
<AgentsMapContext.Provider value={agentsMap}>
|
<AgentsMapContext.Provider value={agentsMap}>
|
||||||
<div className="flex h-dvh">
|
<Banner onHeightChange={setBannerHeight} />
|
||||||
|
<div className="flex" style={{ height: `calc(100dvh - ${bannerHeight}px)` }}>
|
||||||
<div className="relative z-0 flex h-full w-full overflow-hidden">
|
<div className="relative z-0 flex h-full w-full overflow-hidden">
|
||||||
<Nav navVisible={navVisible} setNavVisible={setNavVisible} />
|
<Nav navVisible={navVisible} setNavVisible={setNavVisible} />
|
||||||
<div className="relative flex h-full max-w-full flex-1 flex-col overflow-hidden">
|
<div className="relative flex h-full max-w-full flex-1 flex-col overflow-hidden">
|
||||||
|
|
5
client/src/store/banner.ts
Normal file
5
client/src/store/banner.ts
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
import { atomWithLocalStorage } from './utils';
|
||||||
|
|
||||||
|
const hideBannerHint = atomWithLocalStorage('hideBannerHint', [] as string[]);
|
||||||
|
|
||||||
|
export default { hideBannerHint };
|
|
@ -12,7 +12,7 @@ import preset from './preset';
|
||||||
import prompts from './prompts';
|
import prompts from './prompts';
|
||||||
import lang from './language';
|
import lang from './language';
|
||||||
import settings from './settings';
|
import settings from './settings';
|
||||||
|
import banner from './banner';
|
||||||
export default {
|
export default {
|
||||||
...artifacts,
|
...artifacts,
|
||||||
...families,
|
...families,
|
||||||
|
@ -28,4 +28,5 @@ export default {
|
||||||
...preset,
|
...preset,
|
||||||
...lang,
|
...lang,
|
||||||
...settings,
|
...settings,
|
||||||
|
...banner,
|
||||||
};
|
};
|
||||||
|
|
61
config/delete-banner.js
Normal file
61
config/delete-banner.js
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
const path = require('path');
|
||||||
|
require('module-alias')({ base: path.resolve(__dirname, '..', 'api') });
|
||||||
|
const { askQuestion, silentExit } = require('./helpers');
|
||||||
|
const Banner = require('~/models/schema/banner');
|
||||||
|
const connect = require('./connect');
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await connect();
|
||||||
|
|
||||||
|
console.purple('--------------------------');
|
||||||
|
console.purple('Delete the banner!');
|
||||||
|
console.purple('--------------------------');
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const banner = await Banner.findOne({
|
||||||
|
displayFrom: { $lte: now },
|
||||||
|
$or: [{ displayTo: { $gte: now } }, { displayTo: null }],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!banner) {
|
||||||
|
console.yellow('No banner found to delete.');
|
||||||
|
silentExit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.purple('Current banner:');
|
||||||
|
console.log(`Message: ${banner.message}`);
|
||||||
|
console.log(`Display From: ${banner.displayFrom}`);
|
||||||
|
console.log(`Display To: ${banner.displayTo || 'Not specified'}`);
|
||||||
|
console.log(`Is Public: ${banner.isPublic}`);
|
||||||
|
|
||||||
|
const confirmDelete = await askQuestion('Do you want to delete this banner? (y/N): ');
|
||||||
|
|
||||||
|
if (confirmDelete.toLowerCase() === 'y') {
|
||||||
|
await Banner.findByIdAndDelete(banner._id);
|
||||||
|
console.green('Banner deleted successfully!');
|
||||||
|
} else {
|
||||||
|
console.yellow('Banner deletion cancelled.');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.red('Error: ' + error.message);
|
||||||
|
console.error(error);
|
||||||
|
silentExit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
silentExit(0);
|
||||||
|
})();
|
||||||
|
|
||||||
|
process.on('uncaughtException', (err) => {
|
||||||
|
if (!err.message.includes('fetch failed')) {
|
||||||
|
console.error('There was an uncaught error:');
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.message.includes('fetch failed')) {
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
});
|
|
@ -21,6 +21,27 @@ const askQuestion = (query) => {
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const askMultiLineQuestion = (query) => {
|
||||||
|
const rl = readline.createInterface({
|
||||||
|
input: process.stdin,
|
||||||
|
output: process.stdout,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.cyan(query);
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let lines = [];
|
||||||
|
rl.on('line', (line) => {
|
||||||
|
if (line.trim() === '.') {
|
||||||
|
rl.close();
|
||||||
|
resolve(lines.join('\n'));
|
||||||
|
} else {
|
||||||
|
lines.push(line);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
function isDockerRunning() {
|
function isDockerRunning() {
|
||||||
try {
|
try {
|
||||||
execSync('docker info');
|
execSync('docker info');
|
||||||
|
@ -56,6 +77,7 @@ console.gray = (msg) => console.log('\x1b[90m%s\x1b[0m', msg);
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
askQuestion,
|
askQuestion,
|
||||||
|
askMultiLineQuestion,
|
||||||
silentExit,
|
silentExit,
|
||||||
isDockerRunning,
|
isDockerRunning,
|
||||||
deleteNodeModules,
|
deleteNodeModules,
|
||||||
|
|
147
config/update-banner.js
Normal file
147
config/update-banner.js
Normal file
|
@ -0,0 +1,147 @@
|
||||||
|
const path = require('path');
|
||||||
|
const { v5: uuidv5 } = require('uuid');
|
||||||
|
require('module-alias')({ base: path.resolve(__dirname, '..', 'api') });
|
||||||
|
const { askQuestion, askMultiLineQuestion, silentExit } = require('./helpers');
|
||||||
|
const Banner = require('~/models/schema/banner');
|
||||||
|
const connect = require('./connect');
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await connect();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show the welcome / help menu
|
||||||
|
*/
|
||||||
|
console.purple('--------------------------');
|
||||||
|
console.purple('Update the banner!');
|
||||||
|
console.purple('--------------------------');
|
||||||
|
/**
|
||||||
|
* Set up the variables we need and get the arguments if they were passed in
|
||||||
|
*/
|
||||||
|
let displayFrom = '';
|
||||||
|
let displayTo = '';
|
||||||
|
let message = '';
|
||||||
|
let isPublic = undefined;
|
||||||
|
// If we have the right number of arguments, lets use them
|
||||||
|
if (process.argv.length >= 3) {
|
||||||
|
displayFrom = process.argv[2];
|
||||||
|
displayTo = process.argv[3];
|
||||||
|
message = process.argv[4];
|
||||||
|
isPublic = process.argv[5] === undefined ? undefined : process.argv[5] === 'true';
|
||||||
|
} else {
|
||||||
|
console.orange(
|
||||||
|
'Usage: npm run update-banner <displayFrom(Format: yyyy-mm-ddTHH:MM:SSZ)> <displayTo(Format: yyyy-mm-ddTHH:MM:SSZ)> <message> <isPublic(true/false)>',
|
||||||
|
);
|
||||||
|
console.orange('Note: if you do not pass in the arguments, you will be prompted for them.');
|
||||||
|
console.purple('--------------------------');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If we don't have the right number of arguments, lets prompt the user for them
|
||||||
|
*/
|
||||||
|
if (!displayFrom) {
|
||||||
|
displayFrom = await askQuestion('Display From (Format: yyyy-mm-ddTHH:MM:SSZ, Default: now):');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the displayFrom format (ISO 8601)
|
||||||
|
const dateTimeRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
|
||||||
|
if (displayFrom && !dateTimeRegex.test(displayFrom)) {
|
||||||
|
console.red('Error: Invalid date format for displayFrom. Please use yyyy-mm-ddTHH:MM:SSZ.');
|
||||||
|
silentExit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
displayFrom = displayFrom ? new Date(displayFrom) : new Date();
|
||||||
|
|
||||||
|
if (!displayTo) {
|
||||||
|
displayTo = await askQuestion(
|
||||||
|
'Display To (Format: yyyy-mm-ddTHH:MM:SSZ, Default: not specified):',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (displayTo && !dateTimeRegex.test(displayTo)) {
|
||||||
|
console.red('Error: Invalid date format for displayTo. Please use yyyy-mm-ddTHH:MM:SSZ.');
|
||||||
|
silentExit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
displayTo = displayTo ? new Date(displayTo) : null;
|
||||||
|
|
||||||
|
if (!message) {
|
||||||
|
message = await askMultiLineQuestion(
|
||||||
|
'Enter your message ((Enter a single dot "." on a new line to finish)):',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.trim() === '') {
|
||||||
|
console.red('Error: Message cannot be empty!');
|
||||||
|
silentExit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isPublic === undefined) {
|
||||||
|
const isPublicInput = await askQuestion('Is public (y/N):');
|
||||||
|
isPublic = isPublicInput.toLowerCase() === 'y' ? true : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate the same bannerId for the same message
|
||||||
|
// This allows us to display only messages that haven't been shown yet
|
||||||
|
const NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // Use an arbitrary namespace UUID
|
||||||
|
const bannerId = uuidv5(message, NAMESPACE);
|
||||||
|
|
||||||
|
let result;
|
||||||
|
try {
|
||||||
|
// There is always only one Banner record in the DB.
|
||||||
|
// If a Banner exists in the DB, it will be updated.
|
||||||
|
// If it doesn't exist, a new one will be added.
|
||||||
|
const existingBanner = await Banner.findOne();
|
||||||
|
if (existingBanner) {
|
||||||
|
result = await Banner.findByIdAndUpdate(
|
||||||
|
existingBanner._id,
|
||||||
|
{
|
||||||
|
displayFrom,
|
||||||
|
displayTo,
|
||||||
|
message,
|
||||||
|
bannerId,
|
||||||
|
isPublic,
|
||||||
|
},
|
||||||
|
{ new: true },
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
result = await Banner.create({
|
||||||
|
displayFrom,
|
||||||
|
displayTo,
|
||||||
|
message,
|
||||||
|
bannerId,
|
||||||
|
isPublic,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.red('Error: ' + error.message);
|
||||||
|
console.error(error);
|
||||||
|
silentExit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
console.red('Error: Something went wrong while updating the banner!');
|
||||||
|
console.error(result);
|
||||||
|
silentExit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.green('Banner updated successfully!');
|
||||||
|
console.purple(`bannerId: ${bannerId}`);
|
||||||
|
console.purple(`from: ${displayFrom}`);
|
||||||
|
console.purple(`to: ${displayTo || 'not specified'}`);
|
||||||
|
console.purple(`Banner: ${message}`);
|
||||||
|
console.purple(`isPublic: ${isPublic}`);
|
||||||
|
silentExit(0);
|
||||||
|
})();
|
||||||
|
|
||||||
|
process.on('uncaughtException', (err) => {
|
||||||
|
if (!err.message.includes('fetch failed')) {
|
||||||
|
console.error('There was an uncaught error:');
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.message.includes('fetch failed')) {
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
});
|
|
@ -29,6 +29,8 @@
|
||||||
"invite-user": "node config/invite-user.js",
|
"invite-user": "node config/invite-user.js",
|
||||||
"ban-user": "node config/ban-user.js",
|
"ban-user": "node config/ban-user.js",
|
||||||
"delete-user": "node config/delete-user.js",
|
"delete-user": "node config/delete-user.js",
|
||||||
|
"update-banner": "node config/update-banner.js",
|
||||||
|
"delete-banner": "node config/delete-banner.js",
|
||||||
"backend": "cross-env NODE_ENV=production node api/server/index.js",
|
"backend": "cross-env NODE_ENV=production node api/server/index.js",
|
||||||
"backend:dev": "cross-env NODE_ENV=development npx nodemon api/server/index.js",
|
"backend:dev": "cross-env NODE_ENV=development npx nodemon api/server/index.js",
|
||||||
"backend:stop": "node config/stop-backend.js",
|
"backend:stop": "node config/stop-backend.js",
|
||||||
|
|
|
@ -220,3 +220,4 @@ export const addTagToConversation = (conversationId: string) =>
|
||||||
|
|
||||||
export const userTerms = () => '/api/user/terms';
|
export const userTerms = () => '/api/user/terms';
|
||||||
export const acceptUserTerms = () => '/api/user/terms/accept';
|
export const acceptUserTerms = () => '/api/user/terms/accept';
|
||||||
|
export const banner = () => '/api/banner';
|
||||||
|
|
|
@ -691,3 +691,7 @@ export function getUserTerms(): Promise<t.TUserTermsResponse> {
|
||||||
export function acceptTerms(): Promise<t.TAcceptTermsResponse> {
|
export function acceptTerms(): Promise<t.TAcceptTermsResponse> {
|
||||||
return request.post(endpoints.acceptUserTerms());
|
return request.post(endpoints.acceptUserTerms());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getBanner(): Promise<t.TBannerResponse> {
|
||||||
|
return request.get(endpoints.banner());
|
||||||
|
}
|
||||||
|
|
|
@ -43,6 +43,7 @@ export enum QueryKeys {
|
||||||
conversationTags = 'conversationTags',
|
conversationTags = 'conversationTags',
|
||||||
health = 'health',
|
health = 'health',
|
||||||
userTerms = 'userTerms',
|
userTerms = 'userTerms',
|
||||||
|
banner = 'banner',
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum MutationKeys {
|
export enum MutationKeys {
|
||||||
|
|
|
@ -451,3 +451,14 @@ export const useGetCustomConfigSpeechQuery = (
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const useGetBannerQuery = (
|
||||||
|
config?: UseQueryOptions<t.TBannerResponse>,
|
||||||
|
): QueryObserverResult<t.TBannerResponse> => {
|
||||||
|
return useQuery<t.TBannerResponse>([QueryKeys.banner], () => dataService.getBanner(), {
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
refetchOnReconnect: false,
|
||||||
|
refetchOnMount: false,
|
||||||
|
...config,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
|
@ -1212,6 +1212,17 @@ export const compactPluginsSchema = tConversationSchema
|
||||||
})
|
})
|
||||||
.catch(() => ({}));
|
.catch(() => ({}));
|
||||||
|
|
||||||
|
const tBannerSchema = z.object({
|
||||||
|
bannerId: z.string(),
|
||||||
|
message: z.string(),
|
||||||
|
displayFrom: z.string(),
|
||||||
|
displayTo: z.string(),
|
||||||
|
createdAt: z.string(),
|
||||||
|
updatedAt: z.string(),
|
||||||
|
isPublic: z.boolean(),
|
||||||
|
});
|
||||||
|
export type TBanner = z.infer<typeof tBannerSchema>;
|
||||||
|
|
||||||
export const compactAgentsSchema = tConversationSchema
|
export const compactAgentsSchema = tConversationSchema
|
||||||
.pick({
|
.pick({
|
||||||
model: true,
|
model: true,
|
||||||
|
|
|
@ -8,6 +8,7 @@ import type {
|
||||||
TConversation,
|
TConversation,
|
||||||
EModelEndpoint,
|
EModelEndpoint,
|
||||||
TConversationTag,
|
TConversationTag,
|
||||||
|
TBanner,
|
||||||
} from './schemas';
|
} from './schemas';
|
||||||
import type { TSpecsConfig } from './models';
|
import type { TSpecsConfig } from './models';
|
||||||
export type TOpenAIMessage = OpenAI.Chat.ChatCompletionMessageParam;
|
export type TOpenAIMessage = OpenAI.Chat.ChatCompletionMessageParam;
|
||||||
|
@ -518,3 +519,5 @@ export type TUserTermsResponse = {
|
||||||
export type TAcceptTermsResponse = {
|
export type TAcceptTermsResponse = {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type TBannerResponse = TBanner | null;
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue