73 lines
2.1 KiB
TypeScript
73 lines
2.1 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getImapClient } from '@/lib/imap';
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const { emailIds, action } = await request.json();
|
|
|
|
if (!emailIds || !Array.isArray(emailIds) || !action) {
|
|
return NextResponse.json(
|
|
{ error: 'Invalid request parameters' },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Get the current folder from the request URL
|
|
const url = new URL(request.url);
|
|
const folder = url.searchParams.get('folder') || 'INBOX';
|
|
|
|
// Get the IMAP client using the same method as the mail endpoint
|
|
const imap = await getImapClient();
|
|
if (!imap) {
|
|
return NextResponse.json(
|
|
{ error: 'Failed to connect to mail server' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
// Convert string IDs to numbers
|
|
const numericIds = emailIds.map(id => parseInt(id, 10));
|
|
|
|
// Get mailbox lock for the current folder
|
|
const lock = await imap.getMailboxLock(folder);
|
|
|
|
try {
|
|
// Fetch messages to get their UIDs
|
|
const messages = await imap.fetch({
|
|
seq: numericIds.map(id => id.toString()),
|
|
uid: true,
|
|
envelope: true
|
|
});
|
|
|
|
// Process each message based on the action
|
|
for await (const message of messages) {
|
|
if (!message.uid) continue;
|
|
|
|
switch (action) {
|
|
case 'delete':
|
|
await imap.messageMove(message.uid, 'Trash');
|
|
break;
|
|
case 'mark-read':
|
|
await imap.messageFlagsAdd(message.uid, ['\\Seen'], { uid: true });
|
|
break;
|
|
case 'mark-unread':
|
|
await imap.messageFlagsRemove(message.uid, ['\\Seen'], { uid: true });
|
|
break;
|
|
case 'archive':
|
|
await imap.messageMove(message.uid, 'Archive');
|
|
break;
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({ success: true });
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
} catch (error) {
|
|
console.error('Error in bulk actions:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to perform bulk action' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|