update widget 3

This commit is contained in:
Alma 2025-04-09 22:43:54 +02:00
parent e65bb79034
commit af7b913d9a
2 changed files with 84 additions and 35 deletions

View File

@ -9,11 +9,19 @@ export async function GET() {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
// Get messages from Rocket.Chat // Get the access token from the session
const response = await fetch('https://parole.slm-lab.net/api/v1/channels.messages?roomName=general', { const accessToken = session.accessToken;
if (!accessToken) {
return NextResponse.json({ error: "No access token found" }, { status: 401 });
}
// Use the Keycloak token to authenticate with Rocket.Chat
const response = await fetch('https://parole.slm-lab.net/api/v1/channels.messages', {
headers: { headers: {
'Cookie': `rc_token=${session.accessToken}`, // Use the session token 'Authorization': `Bearer ${accessToken}`,
}, },
// Add cache control to prevent stale data
cache: 'no-store',
}); });
if (!response.ok) { if (!response.ok) {

View File

@ -2,6 +2,8 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";
interface Message { interface Message {
_id: string; _id: string;
@ -18,52 +20,91 @@ export function Parole() {
const [messages, setMessages] = useState<Message[]>([]); const [messages, setMessages] = useState<Message[]>([]);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const fetchMessages = async (isRefresh = false) => {
try {
if (isRefresh) {
setRefreshing(true);
}
const response = await fetch('/api/rocket-chat/messages', {
// Prevent caching
cache: 'no-store',
next: { revalidate: 0 },
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to fetch messages');
}
const data = await response.json();
if (Array.isArray(data.messages)) {
setMessages(data.messages);
} else {
console.warn('Unexpected data format:', data);
setMessages([]);
}
setError(null);
} catch (err) {
console.error('Error fetching messages:', err);
setError(err instanceof Error ? err.message : 'Failed to fetch messages');
} finally {
setLoading(false);
setRefreshing(false);
}
};
useEffect(() => { useEffect(() => {
const fetchMessages = async () => {
try {
const response = await fetch('/api/rocket-chat/messages');
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to fetch messages');
}
const data = await response.json();
setMessages(data.messages || []);
setError(null);
} catch (err) {
console.error('Error fetching messages:', err);
setError(err instanceof Error ? err.message : 'Failed to fetch messages');
} finally {
setLoading(false);
}
};
fetchMessages(); fetchMessages();
// Set up polling every 30 seconds // Set up polling every 30 seconds
const interval = setInterval(fetchMessages, 30000); const interval = setInterval(() => fetchMessages(), 30000);
return () => clearInterval(interval); return () => clearInterval(interval);
}, []); }, []);
return ( return (
<Card className="transition-transform duration-500 ease-in-out transform hover:scale-105"> <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105">
<CardHeader> <CardHeader className="flex flex-row items-center justify-between">
<CardTitle>Parole Messages</CardTitle> <CardTitle>Parole Messages</CardTitle>
<Button
variant="ghost"
size="icon"
onClick={() => fetchMessages(true)}
disabled={refreshing}
className={refreshing ? 'animate-spin' : ''}
>
<RefreshCw className="h-4 w-4" />
</Button>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{loading && <p>Loading messages...</p>} {loading && <p className="text-center text-muted-foreground">Loading messages...</p>}
{error && <p className="text-red-500">Error: {error}</p>} {error && (
<div className="text-center">
<p className="text-red-500">Error: {error}</p>
<Button
variant="outline"
onClick={() => fetchMessages(true)}
className="mt-2"
>
Try Again
</Button>
</div>
)}
{!loading && !error && ( {!loading && !error && (
<div className="space-y-4 max-h-[500px] overflow-y-auto"> <div className="space-y-4 max-h-[500px] overflow-y-auto">
{messages.map((message) => ( {messages.length === 0 ? (
<div key={message._id} className="border-b pb-2"> <p className="text-center text-muted-foreground">No messages found</p>
<p className="font-medium">{message.u.name || message.u.username}</p> ) : (
<p className="text-sm whitespace-pre-wrap">{message.msg}</p> messages.map((message) => (
<p className="text-xs text-gray-500"> <div key={message._id} className="border-b pb-2">
{new Date(message.ts).toLocaleString()} <p className="font-medium">{message.u.name || message.u.username}</p>
</p> <p className="text-sm whitespace-pre-wrap">{message.msg}</p>
</div> <p className="text-xs text-muted-foreground">
))} {new Date(message.ts).toLocaleString()}
</p>
</div>
))
)}
</div> </div>
)} )}
</CardContent> </CardContent>