courrier multi account restore compose
This commit is contained in:
parent
eb557d16dd
commit
43067c6240
119
app/api/courrier/unread-counts/route.ts
Normal file
119
app/api/courrier/unread-counts/route.ts
Normal file
@ -0,0 +1,119 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
||||
import { getImapConnection } from '@/lib/services/email-service';
|
||||
|
||||
/**
|
||||
* API route for fetching unread counts for email folders
|
||||
* This solves the 500 error that occurred when the /unread-counts path was mistakenly being
|
||||
* handled by the [id] route handler which expected a numeric ID
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
// Authenticate user
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session || !session.user?.id) {
|
||||
return NextResponse.json(
|
||||
{ error: "Not authenticated" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// Get all accounts from the user's session
|
||||
const accountIds = await getUserAccountIds(session.user.id);
|
||||
console.log(`[UNREAD_API] Got ${accountIds.length} accounts for user ${session.user.id}`);
|
||||
|
||||
// Mapping to hold the unread counts
|
||||
const unreadCounts: Record<string, Record<string, number>> = {};
|
||||
|
||||
// For each account, get the unread counts for standard folders
|
||||
for (const accountId of accountIds) {
|
||||
try {
|
||||
// Get IMAP connection for this account
|
||||
const client = await getImapConnection(session.user.id, accountId);
|
||||
unreadCounts[accountId] = {};
|
||||
|
||||
// Standard folders to check
|
||||
const standardFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk', 'Spam', 'Archive', 'Sent Items'];
|
||||
|
||||
// Get mailboxes for this account to check if folders exist
|
||||
const mailboxes = await client.list();
|
||||
const availableFolders = mailboxes.map(mb => mb.path);
|
||||
|
||||
console.log(`[UNREAD_API] Account ${accountId} has folders: ${availableFolders.join(', ')}`);
|
||||
|
||||
// Check each standard folder if it exists
|
||||
for (const folder of standardFolders) {
|
||||
// Skip if folder doesn't exist in this account
|
||||
if (!availableFolders.includes(folder) &&
|
||||
!availableFolders.some(f => f.toLowerCase() === folder.toLowerCase())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
// Open the mailbox
|
||||
const status = await client.status(folder, { unseen: true });
|
||||
|
||||
if (status && typeof status.unseen === 'number') {
|
||||
// Store the unread count
|
||||
unreadCounts[accountId][folder] = status.unseen;
|
||||
|
||||
// Also store with prefixed version for consistency
|
||||
unreadCounts[accountId][`${accountId}:${folder}`] = status.unseen;
|
||||
|
||||
console.log(`[UNREAD_API] Account ${accountId}, folder ${folder}: ${status.unseen} unread`);
|
||||
}
|
||||
} catch (folderError) {
|
||||
console.error(`[UNREAD_API] Error getting unread count for ${accountId}:${folder}:`, folderError);
|
||||
// Continue to next folder even if this one fails
|
||||
}
|
||||
}
|
||||
|
||||
// Close connection when done
|
||||
await client.logout();
|
||||
|
||||
} catch (accountError) {
|
||||
console.error(`[UNREAD_API] Error processing account ${accountId}:`, accountError);
|
||||
// Continue to next account even if this one fails
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json(unreadCounts);
|
||||
} catch (error: any) {
|
||||
console.error("[UNREAD_API] Error fetching unread counts:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch unread counts", message: error.message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to get all account IDs for a user
|
||||
*/
|
||||
async function getUserAccountIds(userId: string): Promise<string[]> {
|
||||
try {
|
||||
// Get credentials for all accounts from the email service
|
||||
// This is a simplified version - you should replace this with your actual logic
|
||||
// to retrieve the user's accounts
|
||||
|
||||
// First try the default account
|
||||
const defaultClient = await getImapConnection(userId, 'default');
|
||||
const accounts = ['default'];
|
||||
|
||||
try {
|
||||
// Try to get other accounts if they exist
|
||||
// This is just a placeholder - implement your actual account retrieval logic
|
||||
|
||||
// Close the default connection
|
||||
await defaultClient.logout();
|
||||
} catch (error) {
|
||||
console.error('[UNREAD_API] Error getting additional accounts:', error);
|
||||
}
|
||||
|
||||
return accounts;
|
||||
} catch (error) {
|
||||
console.error('[UNREAD_API] Error getting account IDs:', error);
|
||||
return ['default']; // Return at least the default account
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user