widget email
This commit is contained in:
parent
b2881c7242
commit
d65df5d0fa
@ -1,26 +1,26 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextResponse, NextRequest } from 'next/server';
|
||||||
import { getServerSession } from "next-auth/next";
|
import { getServerSession } from 'next-auth';
|
||||||
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const session = await getServerSession(authOptions);
|
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(
|
return NextResponse.json(
|
||||||
{ error: "Non authentifié" },
|
{ error: 'Nextcloud configuration is missing' },
|
||||||
{ status: 401 }
|
{ 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
|
// 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: {
|
headers: {
|
||||||
'Authorization': `Bearer ${session.accessToken}`,
|
'Authorization': `Bearer ${session.accessToken}`,
|
||||||
'Accept': 'application/json',
|
'Accept': 'application/json',
|
||||||
@ -30,38 +30,38 @@ export async function GET(req: NextRequest) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
console.error('Failed to fetch emails:', {
|
console.error('Nextcloud API error:', {
|
||||||
status: response.status,
|
status: response.status,
|
||||||
statusText: response.statusText
|
statusText: response.statusText,
|
||||||
|
url: response.url
|
||||||
});
|
});
|
||||||
|
|
||||||
// If token is expired or invalid, return 401
|
|
||||||
if (response.status === 401) {
|
if (response.status === 401) {
|
||||||
return NextResponse.json(
|
return NextResponse.json({ error: 'Nextcloud authentication failed' }, { status: 401 });
|
||||||
{ error: "Session expirée" },
|
|
||||||
{ status: 401 }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new Error('Failed to fetch emails from Nextcloud');
|
if (response.status === 404) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Mail app not available on Nextcloud' },
|
||||||
|
{ status: 404 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Failed to fetch emails: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
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) => ({
|
const emails = (data?.ocs?.data || []).map((email: any) => ({
|
||||||
id: email.id,
|
id: email.id,
|
||||||
subject: email.subject || '(No subject)',
|
subject: email.subject || '(No subject)',
|
||||||
sender: {
|
sender: {
|
||||||
name: email.from?.name || email.from?.email || 'Unknown',
|
name: email.from?.name || email.from?.email || 'Unknown',
|
||||||
email: email.from?.email || '',
|
email: email.from?.email || 'unknown@example.com'
|
||||||
},
|
},
|
||||||
date: email.sentDate,
|
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
|
// Sort by date (newest first) and limit to 5 messages
|
||||||
@ -73,7 +73,7 @@ export async function GET(req: NextRequest) {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching emails:', error);
|
console.error('Error fetching emails:', error);
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: "Erreur lors de la récupération des emails" },
|
{ error: 'Failed to fetch emails from Nextcloud' },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -5,8 +5,8 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { RefreshCw, Mail } from "lucide-react";
|
import { RefreshCw, Mail } from "lucide-react";
|
||||||
import { useSession, signIn } from "next-auth/react";
|
import { useSession, signIn } from "next-auth/react";
|
||||||
import { format, formatDistance } from "date-fns";
|
import { formatDistance } from 'date-fns';
|
||||||
import { fr } from "date-fns/locale/fr";
|
import { fr } from 'date-fns/locale';
|
||||||
|
|
||||||
interface Email {
|
interface Email {
|
||||||
id: string;
|
id: string;
|
||||||
@ -32,24 +32,29 @@ export function Email() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/emails');
|
const response = await fetch('/api/emails');
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
// Handle session expiration
|
// Handle session expiration
|
||||||
if (response.status === 401) {
|
if (response.status === 401) {
|
||||||
signIn(); // Redirect to login
|
signIn(); // Redirect to login
|
||||||
return;
|
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');
|
throw new Error(data.error || 'Failed to fetch emails');
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
setEmails(data);
|
setEmails(data);
|
||||||
setError(null);
|
setError(null);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError('Failed to fetch emails');
|
|
||||||
console.error('Error fetching emails:', err);
|
console.error('Error fetching emails:', err);
|
||||||
|
setError(err instanceof Error ? err.message : 'Erreur lors de la récupération des emails');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setRefreshing(false);
|
setRefreshing(false);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user