panel 2 courier api
This commit is contained in:
parent
ecb308d9fb
commit
bd809be84f
@ -3,28 +3,94 @@ import { ImapFlow } from 'imapflow';
|
|||||||
import { getServerSession } from 'next-auth';
|
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';
|
||||||
|
import LRU from 'lru-cache';
|
||||||
|
|
||||||
// Add caching for better performance
|
// Define types
|
||||||
const cache = new Map();
|
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 | null;
|
||||||
|
}
|
||||||
|
|
||||||
const getCachedEmail = (id: string) => cache.get(id);
|
// Configure efficient caching with TTL
|
||||||
const setCachedEmail = (id: string, email: Email) => cache.set(id, email);
|
const emailCache = new LRU<string, Email>({
|
||||||
|
max: 500, // Store up to 500 emails
|
||||||
|
ttl: 1000 * 60 * 5, // Cache for 5 minutes
|
||||||
|
});
|
||||||
|
|
||||||
// Add debouncing for folder changes
|
// Keep IMAP connections per user with timeouts
|
||||||
const debouncedLoadEmails = debounce((folder: string) => {
|
const connectionPool = new Map<string, {
|
||||||
loadEmails(folder);
|
client: ImapFlow;
|
||||||
}, 300);
|
lastUsed: number;
|
||||||
|
}>();
|
||||||
|
|
||||||
// Add infinite scroll
|
// Clean up idle connections periodically
|
||||||
const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
|
setInterval(() => {
|
||||||
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
|
const now = Date.now();
|
||||||
if (scrollHeight - scrollTop === clientHeight) {
|
connectionPool.forEach((connection, userId) => {
|
||||||
// Load more emails
|
if (now - connection.lastUsed > 1000 * 60 * 2) { // 2 minutes idle
|
||||||
|
connection.client.logout().catch(console.error);
|
||||||
|
connectionPool.delete(userId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 60000); // Check every minute
|
||||||
|
|
||||||
|
// Get or create IMAP client for user
|
||||||
|
async function getImapClient(userId: string, credentials: any): Promise<ImapFlow> {
|
||||||
|
const existing = connectionPool.get(userId);
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
existing.lastUsed = Date.now();
|
||||||
|
return existing.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
|
||||||
|
},
|
||||||
|
// Add connection optimizations
|
||||||
|
disableAutoIdle: true,
|
||||||
|
idleTimeout: 30000,
|
||||||
|
connectTimeout: 10000,
|
||||||
|
greetingTimeout: 5000,
|
||||||
|
});
|
||||||
|
|
||||||
|
await client.connect();
|
||||||
|
|
||||||
|
connectionPool.set(userId, {
|
||||||
|
client,
|
||||||
|
lastUsed: Date.now()
|
||||||
|
});
|
||||||
|
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate cache key
|
||||||
|
function getCacheKey(userId: string, folder: string, page: number, limit: number): string {
|
||||||
|
return `${userId}:${folder}:${page}:${limit}`;
|
||||||
|
}
|
||||||
|
|
||||||
export async function GET(request: Request) {
|
export async function GET(request: Request) {
|
||||||
try {
|
try {
|
||||||
|
// 1. Authentication
|
||||||
const session = await getServerSession(authOptions);
|
const session = await getServerSession(authOptions);
|
||||||
if (!session?.user?.id) {
|
if (!session?.user?.id) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@ -33,7 +99,24 @@ export async function GET(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get credentials from database
|
// 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
|
||||||
const credentials = await prisma.mailCredentials.findUnique({
|
const credentials = await prisma.mailCredentials.findUnique({
|
||||||
where: {
|
where: {
|
||||||
userId: session.user.id
|
userId: session.user.id
|
||||||
@ -47,72 +130,69 @@ export async function GET(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get query parameters
|
// 5. Get IMAP client from pool (or create new)
|
||||||
const url = new URL(request.url);
|
const client = await getImapClient(session.user.id, credentials);
|
||||||
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';
|
|
||||||
|
|
||||||
// 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({
|
|
||||||
host: credentials.host,
|
|
||||||
port: credentials.port,
|
|
||||||
secure: true,
|
|
||||||
auth: {
|
|
||||||
user: credentials.email,
|
|
||||||
pass: credentials.password,
|
|
||||||
},
|
|
||||||
logger: false,
|
|
||||||
emitLogs: false,
|
|
||||||
tls: {
|
|
||||||
rejectUnauthorized: false
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
// 6. Get mailboxes (with caching)
|
||||||
|
let availableFolders: string[];
|
||||||
|
const foldersCacheKey = `folders:${session.user.id}`;
|
||||||
|
const cachedFolders = emailCache.get(foldersCacheKey);
|
||||||
|
|
||||||
// Get list of all mailboxes first
|
if (cachedFolders) {
|
||||||
const mailboxes = await client.list();
|
availableFolders = cachedFolders as unknown as string[];
|
||||||
const availableFolders = mailboxes.map(box => box.path);
|
} else {
|
||||||
|
const mailboxes = await client.list();
|
||||||
|
availableFolders = mailboxes.map(box => box.path);
|
||||||
|
emailCache.set(foldersCacheKey, availableFolders);
|
||||||
|
}
|
||||||
|
|
||||||
// Open the requested mailbox
|
// 7. Open mailbox
|
||||||
const mailbox = await client.mailboxOpen(folder);
|
const mailbox = await client.mailboxOpen(folder);
|
||||||
|
|
||||||
const result = [];
|
const result: Email[] = [];
|
||||||
|
|
||||||
// Only try to fetch if the mailbox has messages
|
// 8. Fetch emails (if any exist)
|
||||||
if (mailbox.exists > 0) {
|
if (mailbox.exists > 0) {
|
||||||
// Adjust start and end to be within bounds
|
// Calculate range with boundaries
|
||||||
const adjustedStart = Math.min(start, mailbox.exists);
|
const start = Math.min((page - 1) * limit + 1, mailbox.exists);
|
||||||
const adjustedEnd = Math.min(end, mailbox.exists);
|
const end = Math.min(start + limit - 1, mailbox.exists);
|
||||||
|
|
||||||
// Fetch both metadata and preview content
|
// Use sequence numbers in descending order for newest first
|
||||||
const messages = await client.fetch(`${adjustedStart}:${adjustedEnd}`, {
|
const range = mailbox.exists - end + 1 + ':' + (mailbox.exists - start + 1);
|
||||||
|
|
||||||
|
// Fetch messages with optimized options
|
||||||
|
const options = {
|
||||||
envelope: true,
|
envelope: true,
|
||||||
flags: true,
|
flags: true,
|
||||||
bodyStructure: true,
|
bodyStructure: true,
|
||||||
// Only fetch preview content if requested
|
// Only fetch preview if requested
|
||||||
...(preview ? {
|
...(preview ? {
|
||||||
bodyParts: ['TEXT'],
|
bodyParts: ['TEXT', 'HTML'],
|
||||||
bodyPartsOptions: {
|
bodyPartsOptions: {
|
||||||
TEXT: {
|
maxLength: 1000 // Limit preview length
|
||||||
maxLength: 1000 // Limit preview length
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} : {})
|
} : {})
|
||||||
});
|
};
|
||||||
|
|
||||||
|
const messages = await client.fetch(range, options);
|
||||||
|
|
||||||
|
// Process messages
|
||||||
for await (const message of messages) {
|
for await (const message of messages) {
|
||||||
result.push({
|
// Extract preview content correctly
|
||||||
id: message.uid,
|
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 || '',
|
from: message.envelope.from?.[0]?.address || '',
|
||||||
fromName: message.envelope.from?.[0]?.name || message.envelope.from?.[0]?.address?.split('@')[0] || '',
|
fromName: message.envelope.from?.[0]?.name ||
|
||||||
|
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(),
|
||||||
@ -121,24 +201,31 @@ 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),
|
||||||
// Include preview content if available
|
preview: previewContent
|
||||||
preview: preview ? message.bodyParts?.TEXT?.toString() : null
|
};
|
||||||
});
|
|
||||||
|
result.push(email);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
// 9. Prepare response data
|
||||||
|
const responseData = {
|
||||||
emails: result,
|
emails: result,
|
||||||
folders: availableFolders,
|
folders: availableFolders,
|
||||||
total: mailbox.exists,
|
total: mailbox.exists,
|
||||||
hasMore: end < mailbox.exists
|
hasMore: end < mailbox.exists,
|
||||||
});
|
page,
|
||||||
} finally {
|
limit
|
||||||
try {
|
};
|
||||||
await client.logout();
|
|
||||||
} catch (e) {
|
// 10. Cache the results
|
||||||
console.error('Error during logout:', e);
|
emailCache.set(cacheKey, responseData);
|
||||||
}
|
|
||||||
|
return NextResponse.json(responseData);
|
||||||
|
} catch (error) {
|
||||||
|
// Connection error - remove from pool
|
||||||
|
connectionPool.delete(session.user.id);
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error in courrier route:', error);
|
console.error('Error in courrier route:', error);
|
||||||
@ -148,3 +235,11 @@ export async function GET(request: Request) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Helper method to release connection when app shutting down
|
||||||
|
export async function cleanup() {
|
||||||
|
for (const [userId, connection] of connectionPool.entries()) {
|
||||||
|
await connection.client.logout().catch(console.error);
|
||||||
|
connectionPool.delete(userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user