panel 2 courier api
This commit is contained in:
parent
801a90e42a
commit
ecb308d9fb
@ -4,22 +4,6 @@ import { getServerSession } from 'next-auth';
|
|||||||
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
|
|
||||||
// Define the Email type
|
|
||||||
interface Email {
|
|
||||||
id: string;
|
|
||||||
from: string;
|
|
||||||
fromName: string;
|
|
||||||
to: string;
|
|
||||||
subject: string;
|
|
||||||
date: string;
|
|
||||||
read: boolean;
|
|
||||||
starred: boolean;
|
|
||||||
folder: string;
|
|
||||||
hasAttachments: boolean;
|
|
||||||
flags: string[];
|
|
||||||
preview?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add caching for better performance
|
// Add caching for better performance
|
||||||
const cache = new Map();
|
const cache = new Map();
|
||||||
|
|
||||||
@ -49,23 +33,32 @@ export async function GET(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get credentials from database
|
||||||
const credentials = await prisma.mailCredentials.findUnique({
|
const credentials = await prisma.mailCredentials.findUnique({
|
||||||
where: { userId: session.user.id }
|
where: {
|
||||||
|
userId: session.user.id
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!credentials) {
|
if (!credentials) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'No mail credentials found' },
|
{ error: 'No mail credentials found. Please configure your email account.' },
|
||||||
{ status: 401 }
|
{ status: 401 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get query parameters
|
||||||
const url = new URL(request.url);
|
const url = new URL(request.url);
|
||||||
const folder = url.searchParams.get('folder') || 'INBOX';
|
const folder = url.searchParams.get('folder') || 'INBOX';
|
||||||
const page = parseInt(url.searchParams.get('page') || '1');
|
const page = parseInt(url.searchParams.get('page') || '1');
|
||||||
const limit = parseInt(url.searchParams.get('limit') || '20');
|
const limit = parseInt(url.searchParams.get('limit') || '20');
|
||||||
const preview = url.searchParams.get('preview') === 'true';
|
const preview = url.searchParams.get('preview') === 'true';
|
||||||
|
|
||||||
|
// Calculate start and end sequence numbers
|
||||||
|
const start = (page - 1) * limit + 1;
|
||||||
|
const end = start + limit - 1;
|
||||||
|
|
||||||
|
// Connect to IMAP server
|
||||||
const client = new ImapFlow({
|
const client = new ImapFlow({
|
||||||
host: credentials.host,
|
host: credentials.host,
|
||||||
port: credentials.port,
|
port: credentials.port,
|
||||||
@ -76,46 +69,50 @@ export async function GET(request: Request) {
|
|||||||
},
|
},
|
||||||
logger: false,
|
logger: false,
|
||||||
emitLogs: false,
|
emitLogs: false,
|
||||||
tls: { rejectUnauthorized: false }
|
tls: {
|
||||||
|
rejectUnauthorized: false
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
|
|
||||||
|
// Get list of all mailboxes first
|
||||||
const mailboxes = await client.list();
|
const mailboxes = await client.list();
|
||||||
const availableFolders = mailboxes.map(box => box.path);
|
const availableFolders = mailboxes.map(box => box.path);
|
||||||
|
|
||||||
|
// Open the requested mailbox
|
||||||
const mailbox = await client.mailboxOpen(folder);
|
const mailbox = await client.mailboxOpen(folder);
|
||||||
|
|
||||||
const start = (page - 1) * limit + 1;
|
const result = [];
|
||||||
const end = start + limit - 1;
|
|
||||||
|
|
||||||
const result: Email[] = [];
|
|
||||||
|
|
||||||
|
// Only try to fetch if the mailbox has messages
|
||||||
if (mailbox.exists > 0) {
|
if (mailbox.exists > 0) {
|
||||||
|
// Adjust start and end to be within bounds
|
||||||
const adjustedStart = Math.min(start, mailbox.exists);
|
const adjustedStart = Math.min(start, mailbox.exists);
|
||||||
const adjustedEnd = Math.min(end, mailbox.exists);
|
const adjustedEnd = Math.min(end, mailbox.exists);
|
||||||
|
|
||||||
|
// Fetch both metadata and preview content
|
||||||
const messages = await client.fetch(`${adjustedStart}:${adjustedEnd}`, {
|
const messages = await client.fetch(`${adjustedStart}:${adjustedEnd}`, {
|
||||||
envelope: true,
|
envelope: true,
|
||||||
flags: true,
|
flags: true,
|
||||||
bodyStructure: true,
|
bodyStructure: true,
|
||||||
|
// Only fetch preview content if requested
|
||||||
...(preview ? {
|
...(preview ? {
|
||||||
bodyParts: ['TEXT'],
|
bodyParts: ['TEXT'],
|
||||||
bodyPartsOptions: {
|
bodyPartsOptions: {
|
||||||
TEXT: {
|
TEXT: {
|
||||||
maxLength: 1000
|
maxLength: 1000 // Limit preview length
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} : {})
|
} : {})
|
||||||
});
|
});
|
||||||
|
|
||||||
for await (const message of messages) {
|
for await (const message of messages) {
|
||||||
const email: Email = {
|
result.push({
|
||||||
id: message.uid.toString(),
|
id: message.uid,
|
||||||
from: message.envelope.from?.[0]?.address || '',
|
from: message.envelope.from?.[0]?.address || '',
|
||||||
fromName: message.envelope.from?.[0]?.name ||
|
fromName: message.envelope.from?.[0]?.name || message.envelope.from?.[0]?.address?.split('@')[0] || '',
|
||||||
message.envelope.from?.[0]?.address?.split('@')[0] || '',
|
|
||||||
to: message.envelope.to?.map(addr => addr.address).join(', ') || '',
|
to: message.envelope.to?.map(addr => addr.address).join(', ') || '',
|
||||||
subject: message.envelope.subject || '(No subject)',
|
subject: message.envelope.subject || '(No subject)',
|
||||||
date: message.envelope.date?.toISOString() || new Date().toISOString(),
|
date: message.envelope.date?.toISOString() || new Date().toISOString(),
|
||||||
@ -124,9 +121,9 @@ export async function GET(request: Request) {
|
|||||||
folder: mailbox.path,
|
folder: mailbox.path,
|
||||||
hasAttachments: message.bodyStructure?.type === 'multipart',
|
hasAttachments: message.bodyStructure?.type === 'multipart',
|
||||||
flags: Array.from(message.flags),
|
flags: Array.from(message.flags),
|
||||||
preview: preview ? message.bodyParts?.get('TEXT')?.toString() : undefined
|
// Include preview content if available
|
||||||
};
|
preview: preview ? message.bodyParts?.TEXT?.toString() : null
|
||||||
result.push(email);
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -137,7 +134,11 @@ export async function GET(request: Request) {
|
|||||||
hasMore: end < mailbox.exists
|
hasMore: end < mailbox.exists
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
|
try {
|
||||||
await client.logout();
|
await client.logout();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error during logout:', e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error in courrier route:', error);
|
console.error('Error in courrier route:', error);
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user