widget email

This commit is contained in:
Alma 2025-04-13 20:43:17 +02:00
parent b2881c7242
commit d65df5d0fa
2 changed files with 40 additions and 35 deletions

View File

@ -1,26 +1,26 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { NextResponse, NextRequest } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
export async function GET(req: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.email || !session.accessToken) {
if (!session?.accessToken) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const nextcloudUrl = process.env.NEXTCLOUD_URL;
if (!nextcloudUrl) {
console.error('Missing Nextcloud URL');
return NextResponse.json(
{ error: "Non authentifié" },
{ status: 401 }
{ error: 'Nextcloud configuration is missing' },
{ status: 500 }
);
}
// Get Nextcloud base URL from environment variable
const nextcloudUrl = process.env.NEXTCLOUD_URL;
if (!nextcloudUrl) {
throw new Error("NEXTCLOUD_URL not configured");
}
// Fetch unread messages from Nextcloud Mail API using OIDC token
const response = await fetch(`${nextcloudUrl}/apps/mail/api/v1/messages?filter=unseen`, {
const response = await fetch(`${nextcloudUrl}/ocs/v2.php/apps/mail/api/v1/folders/inbox/messages?filter=unseen`, {
headers: {
'Authorization': `Bearer ${session.accessToken}`,
'Accept': 'application/json',
@ -30,38 +30,38 @@ export async function GET(req: NextRequest) {
});
if (!response.ok) {
console.error('Failed to fetch emails:', {
console.error('Nextcloud API error:', {
status: response.status,
statusText: response.statusText
statusText: response.statusText,
url: response.url
});
// If token is expired or invalid, return 401
if (response.status === 401) {
return NextResponse.json({ error: 'Nextcloud authentication failed' }, { status: 401 });
}
if (response.status === 404) {
return NextResponse.json(
{ error: "Session expirée" },
{ status: 401 }
{ error: 'Mail app not available on Nextcloud' },
{ status: 404 }
);
}
throw new Error('Failed to fetch emails from Nextcloud');
throw new Error(`Failed to fetch emails: ${response.status} ${response.statusText}`);
}
const data = await response.json();
console.log('Nextcloud mail response:', {
status: response.status,
dataLength: data?.ocs?.data?.length || 0
});
// Transform the response to match our Email interface
// Transform the data to match our Email interface
const emails = (data?.ocs?.data || []).map((email: any) => ({
id: email.id,
subject: email.subject || '(No subject)',
sender: {
name: email.from?.name || email.from?.email || 'Unknown',
email: email.from?.email || '',
email: email.from?.email || 'unknown@example.com'
},
date: email.sentDate,
isUnread: true, // Since we're only fetching unread messages
isUnread: true // Since we're only fetching unread messages
}));
// Sort by date (newest first) and limit to 5 messages
@ -73,7 +73,7 @@ export async function GET(req: NextRequest) {
} catch (error) {
console.error('Error fetching emails:', error);
return NextResponse.json(
{ error: "Erreur lors de la récupération des emails" },
{ error: 'Failed to fetch emails from Nextcloud' },
{ status: 500 }
);
}

View File

@ -5,8 +5,8 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw, Mail } from "lucide-react";
import { useSession, signIn } from "next-auth/react";
import { format, formatDistance } from "date-fns";
import { fr } from "date-fns/locale/fr";
import { formatDistance } from 'date-fns';
import { fr } from 'date-fns/locale';
interface Email {
id: string;
@ -32,24 +32,29 @@ export function Email() {
try {
const response = await fetch('/api/emails');
if (!response.ok) {
const data = await response.json();
if (!response.ok) {
// Handle session expiration
if (response.status === 401) {
signIn(); // Redirect to login
return;
}
// Handle specific error messages
if (response.status === 404) {
setError("L'application Mail n'est pas disponible sur Nextcloud. Veuillez contacter votre administrateur.");
return;
}
throw new Error(data.error || 'Failed to fetch emails');
}
const data = await response.json();
setEmails(data);
setError(null);
} catch (err) {
setError('Failed to fetch emails');
console.error('Error fetching emails:', err);
setError(err instanceof Error ? err.message : 'Erreur lors de la récupération des emails');
} finally {
setLoading(false);
setRefreshing(false);