80 lines
2.5 KiB
TypeScript
80 lines
2.5 KiB
TypeScript
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?.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: 'Nextcloud configuration is missing' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
// Fetch unread messages from Nextcloud Mail API using OIDC token
|
|
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',
|
|
'OCS-APIRequest': 'true',
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.error('Nextcloud API error:', {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
url: response.url
|
|
});
|
|
|
|
if (response.status === 401) {
|
|
return NextResponse.json({ error: 'Nextcloud authentication failed' }, { status: 401 });
|
|
}
|
|
|
|
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();
|
|
|
|
// 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 || 'unknown@example.com'
|
|
},
|
|
date: email.sentDate,
|
|
isUnread: true // Since we're only fetching unread messages
|
|
}));
|
|
|
|
// Sort by date (newest first) and limit to 5 messages
|
|
const sortedEmails = emails
|
|
.sort((a: any, b: any) => new Date(b.date).getTime() - new Date(a.date).getTime())
|
|
.slice(0, 5);
|
|
|
|
return NextResponse.json(sortedEmails);
|
|
} catch (error) {
|
|
console.error('Error fetching emails:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to fetch emails from Nextcloud' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|