courrier multi account restore compose

This commit is contained in:
alma 2025-04-28 15:06:52 +02:00
parent 098075010f
commit 7e18722d3c

View File

@ -274,6 +274,11 @@ export async function getEmails(
): Promise<EmailListResult> { ): Promise<EmailListResult> {
console.log(`Fetching emails for user ${userId}${accountId ? ` account ${accountId}` : ''} in folder ${folder}`); console.log(`Fetching emails for user ${userId}${accountId ? ` account ${accountId}` : ''} in folder ${folder}`);
// Extract the base folder name if it's an account-specific folder
const baseFolder = accountId && folder.endsWith(`-${accountId}`)
? folder.slice(0, -accountId.length - 1)
: folder;
// Try to get from cache first // Try to get from cache first
const cached = await getCachedEmailList(userId, accountId || 'default', folder, page, perPage); const cached = await getCachedEmailList(userId, accountId || 'default', folder, page, perPage);
if (cached) { if (cached) {
@ -288,11 +293,11 @@ export async function getEmails(
} }
try { try {
// Open the mailbox // Open the mailbox using the base folder name
await client.mailboxOpen(folder); await client.mailboxOpen(baseFolder);
// Get total count of messages // Get total count of messages
const status = await client.status(folder, { messages: true }); const status = await client.status(baseFolder, { messages: true });
const totalEmails = status.messages || 0; const totalEmails = status.messages || 0;
const totalPages = Math.ceil(totalEmails / perPage); const totalPages = Math.ceil(totalEmails / perPage);
@ -334,7 +339,7 @@ export async function getEmails(
}, },
size: message.size || 0, size: message.size || 0,
hasAttachments: message.bodyStructure?.childNodes?.some(node => node.disposition === 'attachment') || false, hasAttachments: message.bodyStructure?.childNodes?.some(node => node.disposition === 'attachment') || false,
folder: folder, folder: folder, // Use the original folder name with account ID
contentFetched: false, contentFetched: false,
accountId: accountId, accountId: accountId,
content: '', content: '',
@ -351,26 +356,13 @@ export async function getEmails(
perPage, perPage,
totalPages, totalPages,
folder, folder,
mailboxes: await getMailboxes(client) mailboxes: await getMailboxes(client, accountId) // Pass accountId to getMailboxes
}; };
// Cache the result with the correct accountId // Cache the result with the account-specific folder
await cacheEmailList(userId, accountId || 'default', folder, page, perPage, result); await cacheEmailList(userId, accountId || 'default', folder, page, perPage, result);
// Invalidate cache for other accounts' folders to prevent stale data // No need to invalidate other accounts' caches since folders are now account-specific
if (accountId) {
const accounts = await prisma.mailCredentials.findMany({
where: { userId },
select: { id: true }
});
for (const account of accounts) {
if (account.id !== accountId) {
await invalidateFolderCache(userId, account.id, folder);
}
}
}
return result; return result;
} finally { } finally {
try { try {
@ -594,11 +586,11 @@ export async function sendEmail(
/** /**
* Get list of mailboxes from an IMAP connection * Get list of mailboxes from an IMAP connection
*/ */
export async function getMailboxes(client: ImapFlow): Promise<string[]> { export async function getMailboxes(client: ImapFlow, accountId?: string): Promise<string[]> {
try { try {
const mailboxes = await client.list(); const mailboxes = await client.list();
// Map special folders to standard names // Map special folders to standard names, but keep account-specific paths
const specialFolders = new Map<string, string>([ const specialFolders = new Map<string, string>([
['Sent Messages', 'Sent'], ['Sent Messages', 'Sent'],
['Sent Items', 'Sent'], ['Sent Items', 'Sent'],
@ -608,27 +600,35 @@ export async function getMailboxes(client: ImapFlow): Promise<string[]> {
['Spam', 'Junk'] ['Spam', 'Junk']
]); ]);
// Process mailboxes and map special folders // Process mailboxes and map special folders while preserving account-specific paths
const processedMailboxes = mailboxes.map(mailbox => { const processedMailboxes = mailboxes.map(mailbox => {
const path = mailbox.path; const path = mailbox.path;
// Check if this is a special folder // Check if this is a special folder
for (const [special, standard] of specialFolders) { for (const [special, standard] of specialFolders) {
if (path.includes(special)) { if (path.includes(special)) {
return standard; // Include accountId in the folder name to make it unique per account
return accountId ? `${standard}-${accountId}` : standard;
} }
} }
return path; // Include accountId in the folder name to make it unique per account
return accountId ? `${path}-${accountId}` : path;
}); });
// Ensure we have all standard folders // Ensure we have all standard folders with account-specific names
const standardFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; const standardFolders = accountId
? ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'].map(f => `${f}-${accountId}`)
: ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'];
const uniqueFolders = new Set([...standardFolders, ...processedMailboxes]); const uniqueFolders = new Set([...standardFolders, ...processedMailboxes]);
return Array.from(uniqueFolders); return Array.from(uniqueFolders);
} catch (error) { } catch (error) {
console.error('Error fetching mailboxes:', error); console.error('Error fetching mailboxes:', error);
// Return default folders on error // Return default folders on error, with account-specific names if accountId is provided
return ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk']; const defaultFolders = ['INBOX', 'Sent', 'Drafts', 'Trash', 'Junk'];
return accountId
? defaultFolders.map(f => `${f}-${accountId}`)
: defaultFolders;
} }
} }