177 lines
5.5 KiB
TypeScript
177 lines
5.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?.user?.email) {
|
|
console.error('No session or email found');
|
|
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 }
|
|
);
|
|
}
|
|
|
|
// Get the Keycloak token from the session
|
|
const keycloakToken = session.accessToken;
|
|
if (!keycloakToken) {
|
|
console.error('Missing Keycloak token in session');
|
|
return NextResponse.json(
|
|
{ error: 'Authentication token is missing' },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
// First, try the unified inbox endpoint for unread messages
|
|
const unifiedResponse = await fetch(
|
|
`${nextcloudUrl}/index.php/apps/mail/api/messages?filter=is:unread`,
|
|
{
|
|
headers: {
|
|
'Authorization': `Bearer ${keycloakToken}`,
|
|
'Accept': 'application/json',
|
|
'OCS-APIRequest': 'true',
|
|
'X-Requested-With': 'XMLHttpRequest'
|
|
}
|
|
}
|
|
);
|
|
|
|
// Log the response status and headers for debugging
|
|
console.log('Unified inbox response status:', unifiedResponse.status);
|
|
console.log('Unified inbox response headers:', Object.fromEntries(unifiedResponse.headers.entries()));
|
|
|
|
if (unifiedResponse.ok) {
|
|
const unifiedData = await unifiedResponse.json();
|
|
console.log('Unified inbox data:', unifiedData);
|
|
const messages = unifiedData.data || [];
|
|
|
|
const unreadEmails = messages.map((msg: any) => ({
|
|
id: msg.id,
|
|
subject: msg.subject,
|
|
sender: {
|
|
name: msg.from[0].label || msg.from[0].email,
|
|
email: msg.from[0].email
|
|
},
|
|
date: msg.date,
|
|
isUnread: true
|
|
}));
|
|
|
|
return NextResponse.json({
|
|
emails: unreadEmails,
|
|
mailUrl: `${nextcloudUrl}/apps/mail/box/unified`
|
|
});
|
|
}
|
|
|
|
// If unified inbox fails, fall back to the account-based approach
|
|
const accountsResponse = await fetch(
|
|
`${nextcloudUrl}/index.php/apps/mail/api/accounts`,
|
|
{
|
|
headers: {
|
|
'Authorization': `Bearer ${keycloakToken}`,
|
|
'Accept': 'application/json',
|
|
'OCS-APIRequest': 'true',
|
|
'X-Requested-With': 'XMLHttpRequest'
|
|
}
|
|
}
|
|
);
|
|
|
|
// Log the response status and headers for debugging
|
|
console.log('Accounts response status:', accountsResponse.status);
|
|
console.log('Accounts response headers:', Object.fromEntries(accountsResponse.headers.entries()));
|
|
|
|
if (!accountsResponse.ok) {
|
|
const errorText = await accountsResponse.text();
|
|
console.error('Failed to fetch mail accounts. Response:', errorText);
|
|
return NextResponse.json(
|
|
{
|
|
error: "L'application Mail n'est pas disponible sur Nextcloud. Veuillez contacter votre administrateur.",
|
|
emails: []
|
|
},
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
const accountsData = await accountsResponse.json();
|
|
console.log('Accounts data:', accountsData);
|
|
const accounts = accountsData.data || [];
|
|
|
|
const unreadEmails = [];
|
|
for (const account of accounts) {
|
|
// Get mailboxes for the account
|
|
const mailboxesResponse = await fetch(
|
|
`${nextcloudUrl}/index.php/apps/mail/api/accounts/${account.id}/mailboxes`,
|
|
{
|
|
headers: {
|
|
'Authorization': `Bearer ${keycloakToken}`,
|
|
'Accept': 'application/json',
|
|
'OCS-APIRequest': 'true',
|
|
'X-Requested-With': 'XMLHttpRequest'
|
|
}
|
|
}
|
|
);
|
|
|
|
if (!mailboxesResponse.ok) {
|
|
console.error(`Failed to fetch mailboxes for account ${account.id}`);
|
|
continue;
|
|
}
|
|
|
|
const mailboxesData = await mailboxesResponse.json();
|
|
const mailboxes = mailboxesData.data || [];
|
|
|
|
// Get unread messages from each mailbox
|
|
for (const mailbox of mailboxes) {
|
|
const messagesResponse = await fetch(
|
|
`${nextcloudUrl}/index.php/apps/mail/api/accounts/${account.id}/mailboxes/${mailbox.id}/messages?filter=is:unread`,
|
|
{
|
|
headers: {
|
|
'Authorization': `Bearer ${keycloakToken}`,
|
|
'Accept': 'application/json',
|
|
'OCS-APIRequest': 'true',
|
|
'X-Requested-With': 'XMLHttpRequest'
|
|
}
|
|
}
|
|
);
|
|
|
|
if (!messagesResponse.ok) {
|
|
console.error(`Failed to fetch messages for mailbox ${mailbox.id}`);
|
|
continue;
|
|
}
|
|
|
|
const messagesData = await messagesResponse.json();
|
|
const messages = messagesData.data || [];
|
|
|
|
unreadEmails.push(...messages.map((msg: any) => ({
|
|
id: msg.id,
|
|
subject: msg.subject,
|
|
sender: {
|
|
name: msg.from[0].label || msg.from[0].email,
|
|
email: msg.from[0].email
|
|
},
|
|
date: msg.date,
|
|
isUnread: true
|
|
})));
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
emails: unreadEmails,
|
|
mailUrl: `${nextcloudUrl}/apps/mail/box/unified`
|
|
});
|
|
} catch (error) {
|
|
console.error('Error getting emails:', error);
|
|
return NextResponse.json(
|
|
{
|
|
error: "Une erreur est survenue. Veuillez contacter votre administrateur.",
|
|
emails: []
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|