Neah/app/api/courrier/account-folders/route.ts
2025-04-27 17:01:48 +02:00

160 lines
4.2 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { getMailboxes } from '@/lib/services/email-service';
import { ImapFlow } from 'imapflow';
import { prisma } from '@/lib/prisma';
import { getCachedEmailCredentials } from '@/lib/redis';
export async function GET(request: Request) {
// Verify auth
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { searchParams } = new URL(request.url);
const accountId = searchParams.get('accountId');
const userId = session.user.id;
try {
// If specific accountId is provided, get folders for that account
if (accountId) {
// Get account from database
const account = await prisma.mailCredentials.findFirst({
where: {
id: accountId,
userId
},
select: {
email: true,
password: true,
host: true,
port: true
}
});
if (!account) {
return NextResponse.json(
{ error: 'Account not found' },
{ status: 404 }
);
}
// Connect to IMAP server for this account
const client = new ImapFlow({
host: account.host,
port: account.port,
secure: true,
auth: {
user: account.email,
pass: account.password,
},
logger: false,
tls: {
rejectUnauthorized: false
}
});
try {
await client.connect();
// Get folders for this account
const folders = await getMailboxes(client);
// Close connection
await client.logout();
return NextResponse.json({
accountId,
email: account.email,
folders
});
} catch (error) {
return NextResponse.json(
{
error: 'Failed to connect to IMAP server',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
} else {
// Get folders for all accounts
const accounts = await prisma.mailCredentials.findMany({
where: { userId },
select: {
id: true,
email: true
}
});
// For demo purposes, rather than connecting to all accounts,
// get the default set of folders from the first cached account
const credentials = await getCachedEmailCredentials(userId);
if (!credentials) {
return NextResponse.json({
accounts: accounts.map(account => ({
id: account.id,
email: account.email,
folders: ['INBOX', 'Sent', 'Drafts', 'Trash'] // Fallback folders
}))
});
}
// Connect to IMAP server
const client = new ImapFlow({
host: credentials.host,
port: credentials.port,
secure: true,
auth: {
user: credentials.email,
pass: credentials.password,
},
logger: false,
tls: {
rejectUnauthorized: false
}
});
try {
await client.connect();
// Get folders
const folders = await getMailboxes(client);
// Close connection
await client.logout();
return NextResponse.json({
accounts: accounts.map(account => ({
id: account.id,
email: account.email,
folders
}))
});
} catch (error) {
return NextResponse.json({
accounts: accounts.map(account => ({
id: account.id,
email: account.email,
folders: ['INBOX', 'Sent', 'Drafts', 'Trash'] // Fallback folders on error
})),
error: error instanceof Error ? error.message : 'Unknown error'
});
}
}
} catch (error) {
return NextResponse.json(
{
error: 'Failed to get account folders',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}