diff --git a/app/api/courrier/login/route.ts b/app/api/courrier/login/route.ts index 3de134ec..d09853e4 100644 --- a/app/api/courrier/login/route.ts +++ b/app/api/courrier/login/route.ts @@ -3,9 +3,23 @@ import { ImapFlow } from 'imapflow'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { prisma } from '@/lib/prisma'; +import { LRUCache } from 'lru-cache'; -export async function POST(request: Request) { +// Simple in-memory cache for email content +const emailContentCache = new LRUCache({ + max: 100, + ttl: 1000 * 60 * 15, // 15 minutes +}); + +export async function GET( + request: Request, + { params }: { params: { id: string } } +) { try { + // 1. Properly await params to avoid Next.js error + const { id } = await Promise.resolve(params); + + // 2. Authentication check const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json( @@ -14,121 +28,104 @@ export async function POST(request: Request) { ); } - const { email, password, host, port } = await request.json(); - - if (!email || !password || !host || !port) { - return NextResponse.json( - { error: 'Missing required fields' }, - { status: 400 } - ); - } - - // Test IMAP connection - const client = new ImapFlow({ - host: host, - port: parseInt(port), - secure: true, - auth: { - user: email, - pass: password, - }, - logger: false, - emitLogs: false, - tls: { - rejectUnauthorized: false - } - }); - - try { - await client.connect(); - await client.mailboxOpen('INBOX'); - - // Store or update credentials in database - await prisma.mailCredentials.upsert({ - where: { - userId: session.user.id - }, - update: { - email, - password, - host, - port: parseInt(port) - }, - create: { - userId: session.user.id, - email, - password, - host, - port: parseInt(port) - } - }); - - return NextResponse.json({ success: true }); - } catch (error) { - if (error instanceof Error) { - if (error.message.includes('Invalid login')) { - return NextResponse.json( - { error: 'Invalid login or password' }, - { status: 401 } - ); - } - return NextResponse.json( - { error: `IMAP connection error: ${error.message}` }, - { status: 500 } - ); - } - return NextResponse.json( - { error: 'Failed to connect to email server' }, - { status: 500 } - ); - } finally { - try { - await client.logout(); - } catch (e) { - console.error('Error during logout:', e); - } - } - } catch (error) { - console.error('Error in login handler:', error); - return NextResponse.json( - { error: 'An unexpected error occurred' }, - { status: 500 } - ); - } -} - -export async function GET() { - try { - const session = await getServerSession(authOptions); - if (!session?.user?.id) { - return NextResponse.json( - { error: 'Unauthorized' }, - { status: 401 } - ); + // 3. Check cache first + const cacheKey = `email:${session.user.id}:${id}`; + const cachedEmail = emailContentCache.get(cacheKey); + if (cachedEmail) { + return NextResponse.json(cachedEmail); } + // 4. Get credentials from database const credentials = await prisma.mailCredentials.findUnique({ where: { userId: session.user.id - }, - select: { - email: true, - host: true, - port: true } }); if (!credentials) { return NextResponse.json( - { error: 'No stored credentials found' }, - { status: 404 } + { error: 'No mail credentials found. Please configure your email account.' }, + { status: 401 } ); } - return NextResponse.json(credentials); + // 5. Create IMAP client + const client = new ImapFlow({ + host: credentials.host, + port: credentials.port, + secure: true, + auth: { + user: credentials.email, + pass: credentials.password, + }, + logger: false, + emitLogs: false, + tls: { + rejectUnauthorized: false + }, + disableAutoIdle: true + }); + + try { + await client.connect(); + + // 6. Open INBOX + await client.mailboxOpen('INBOX'); + + // 7. Fetch the email with UID search + const options = { + uid: true, // This is crucial - we must specify uid:true to fetch by UID + source: true, + envelope: true, + bodyStructure: true, + flags: true + }; + + // Fetch by UID + console.log('Fetching email with UID:', id); + const message = await client.fetchOne(id, options); + + if (!message) { + console.error('Email not found with UID:', id); + return NextResponse.json( + { error: 'Email not found' }, + { status: 404 } + ); + } + + // 8. Parse the email content + const emailContent = { + id: message.uid.toString(), + from: message.envelope.from?.[0]?.address || '', + fromName: message.envelope.from?.[0]?.name || + message.envelope.from?.[0]?.address?.split('@')[0] || '', + to: message.envelope.to?.map((addr: any) => addr.address).join(', ') || '', + subject: message.envelope.subject || '(No subject)', + date: message.envelope.date?.toISOString() || new Date().toISOString(), + content: message.source?.toString() || '', + read: message.flags.has('\\Seen'), + starred: message.flags.has('\\Flagged'), + flags: Array.from(message.flags), + hasAttachments: message.bodyStructure?.type === 'multipart') + }; + + // 9. Cache the email content + emailContentCache.set(cacheKey, emailContent); + + // 10. Return the email content + return NextResponse.json(emailContent); + } finally { + // 11. Close the connection + try { + await client.logout(); + } catch (e) { + console.error('Error during IMAP logout:', e); + } + } } catch (error) { + console.error('Error fetching email:', error); return NextResponse.json( - { error: 'Failed to retrieve credentials' }, + { error: 'Failed to fetch email content' }, { status: 500 } ); } diff --git a/app/api/courrier/route.ts b/app/api/courrier/route.ts index 806bde31..bd0f93f5 100644 --- a/app/api/courrier/route.ts +++ b/app/api/courrier/route.ts @@ -100,15 +100,9 @@ function getCacheKey(userId: string, folder: string, page: number, limit: number return `${userId}:${folder}:${page}:${limit}`; } -export async function GET( - request: Request, - { params }: { params: { id: string } } -) { +export async function GET(request: Request) { try { - // 1. Properly await params to avoid Next.js error - const { id } = await Promise.resolve(params); - - // 2. Authentication check + // 1. Authentication const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json( @@ -117,14 +111,24 @@ export async function GET( ); } - // 3. Check cache first - const cacheKey = `email:${session.user.id}:${id}`; - const cachedEmail = emailContentCache.get(cacheKey); - if (cachedEmail) { - return NextResponse.json(cachedEmail); + // 2. Parse request parameters + const url = new URL(request.url); + const folder = url.searchParams.get('folder') || 'INBOX'; + const page = parseInt(url.searchParams.get('page') || '1'); + const limit = parseInt(url.searchParams.get('limit') || '20'); + const preview = url.searchParams.get('preview') === 'true'; + const forceRefresh = url.searchParams.get('refresh') === 'true'; + + // 3. Check cache first (unless refresh requested) + const cacheKey = getCacheKey(session.user.id, folder, page, limit); + if (!forceRefresh) { + const cachedData = emailCache.get(cacheKey); + if (cachedData) { + return NextResponse.json(cachedData); + } } - // 4. Get credentials from database + // 4. Get credentials const credentials = await prisma.mailCredentials.findUnique({ where: { userId: session.user.id @@ -138,83 +142,109 @@ export async function GET( ); } - // 5. Create IMAP client - const client = new ImapFlow({ - host: credentials.host, - port: credentials.port, - secure: true, - auth: { - user: credentials.email, - pass: credentials.password, - }, - logger: false, - emitLogs: false, - tls: { - rejectUnauthorized: false - }, - disableAutoIdle: true - }); + // 5. Get IMAP client from pool (or create new) + const client = await getImapClient(session.user.id, credentials); try { - await client.connect(); + // 6. Get mailboxes (with caching) + let availableFolders: string[]; + const foldersCacheKey = `folders:${session.user.id}`; + const cachedFolders = emailCache.get(foldersCacheKey); - // 6. Open INBOX - await client.mailboxOpen('INBOX'); + if (cachedFolders) { + availableFolders = cachedFolders; + } else { + const mailboxes = await client.list(); + availableFolders = mailboxes.map(box => box.path); + emailCache.set(foldersCacheKey, availableFolders); + } - // 7. Fetch the email with UID search - const options = { - uid: true, // This is crucial - we must specify uid:true to fetch by UID - source: true, - envelope: true, - bodyStructure: true, - flags: true - }; + // 7. Open mailbox + const mailbox = await client.mailboxOpen(folder); - // Fetch by UID - console.log('Fetching email with UID:', id); - const message = await client.fetchOne(id, options); + const result: Email[] = []; - if (!message) { - console.error('Email not found with UID:', id); - return NextResponse.json( - { error: 'Email not found' }, - { status: 404 } - ); + // 8. Fetch emails (if any exist) + // Define start and end variables HERE + let start = 1; + let end = 0; + + if (mailbox.exists > 0) { + // Calculate range with boundaries + start = Math.min((page - 1) * limit + 1, mailbox.exists); + end = Math.min(start + limit - 1, mailbox.exists); + + // Use sequence numbers in descending order for newest first + const range = `${mailbox.exists - end + 1}:${mailbox.exists - start + 1}`; + + // Fetch messages with optimized options + const options: any = { + envelope: true, + flags: true, + bodyStructure: true + }; + + // Only fetch preview if requested + if (preview) { + options.bodyParts = ['TEXT', 'HTML']; + } + + const messages = await client.fetch(range, options); + + // Process messages + for await (const message of messages) { + // Extract preview content correctly + let previewContent = null; + if (preview && message.bodyParts) { + // Try HTML first, then TEXT + const htmlPart = message.bodyParts.get('HTML'); + const textPart = message.bodyParts.get('TEXT'); + previewContent = htmlPart?.toString() || textPart?.toString() || null; + } + + const email: Email = { + id: message.uid.toString(), + from: message.envelope.from?.[0]?.address || '', + fromName: message.envelope.from?.[0]?.name || + message.envelope.from?.[0]?.address?.split('@')[0] || '', + to: message.envelope.to?.map((addr: any) => addr.address).join(', ') || '', + subject: message.envelope.subject || '(No subject)', + date: message.envelope.date?.toISOString() || new Date().toISOString(), + read: message.flags.has('\\Seen'), + starred: message.flags.has('\\Flagged'), + folder: mailbox.path, + hasAttachments: message.bodyStructure?.type === 'multipart', + flags: Array.from(message.flags), + preview: previewContent + }; + + result.push(email); + } } - // 8. Parse the email content - const emailContent = { - id: message.uid.toString(), - from: message.envelope.from?.[0]?.address || '', - fromName: message.envelope.from?.[0]?.name || - message.envelope.from?.[0]?.address?.split('@')[0] || '', - to: message.envelope.to?.map((addr: any) => addr.address).join(', ') || '', - subject: message.envelope.subject || '(No subject)', - date: message.envelope.date?.toISOString() || new Date().toISOString(), - content: message.source?.toString() || '', - read: message.flags.has('\\Seen'), - starred: message.flags.has('\\Flagged'), - flags: Array.from(message.flags), - hasAttachments: message.bodyStructure?.type === 'multipart' + // 9. Prepare response data + const responseData = { + emails: result, + folders: availableFolders, + total: mailbox.exists, + hasMore: end < mailbox.exists, + page, + limit }; + + // 10. Cache the results + emailCache.set(cacheKey, responseData); - // 9. Cache the email content - emailContentCache.set(cacheKey, emailContent); - - // 10. Return the email content - return NextResponse.json(emailContent); - } finally { - // 11. Close the connection - try { - await client.logout(); - } catch (e) { - console.error('Error during IMAP logout:', e); - } + return NextResponse.json(responseData); + } catch (error) { + // Connection error - remove from pool + connectionPool.delete(session.user.id); + throw error; } } catch (error) { - console.error('Error fetching email:', error); + console.error('Error in courrier route:', error); return NextResponse.json( - { error: 'Failed to fetch email content' }, + { error: 'An unexpected error occurred' }, { status: 500 } ); }