54 lines
2.5 KiB
JavaScript
54 lines
2.5 KiB
JavaScript
function createMessageActionService({ imapClient, folderPath, findSpecialMailbox, updateAccountStore }) {
|
|
async function applyMessageAction(account, input) {
|
|
const uid = Number(input?.uid);
|
|
const folder = String(input?.folder || 'Inbox');
|
|
const action = String(input?.action || '');
|
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
|
if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
|
|
const client = await imapClient(account);
|
|
try {
|
|
await client.connect();
|
|
const sourcePath = await folderPath(client, folder);
|
|
if (!sourcePath) throw new Error('That mail folder could not be found.');
|
|
const lock = await client.getMailboxLock(sourcePath);
|
|
try {
|
|
if (action === 'star') {
|
|
if (input.enabled) await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
|
|
else await client.messageFlagsRemove(uid, ['\\Flagged'], { uid: true });
|
|
} else if (action === 'unread') {
|
|
if (input.enabled) await client.messageFlagsRemove(uid, ['\\Seen'], { uid: true });
|
|
else await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true });
|
|
} else {
|
|
const target = action === 'archive'
|
|
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
|
|
: action === 'delete'
|
|
? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
|
|
: 'INBOX';
|
|
if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
|
|
if (action === 'delete') await client.messageDelete(uid, { uid: true });
|
|
}
|
|
else await client.messageMove(uid, target, { uid: true });
|
|
}
|
|
} finally {
|
|
lock.release();
|
|
}
|
|
if (action === 'archive' || action === 'delete' || action === 'inbox') {
|
|
await updateAccountStore(store => {
|
|
const saved = store.accounts.find(item => item.id === account.id);
|
|
if (saved) {
|
|
saved.snoozedMessages = (saved.snoozedMessages || [])
|
|
.filter(item => Number(item.uid) !== uid || item.folder !== folder);
|
|
}
|
|
});
|
|
}
|
|
return { ok: true };
|
|
} finally {
|
|
if (client.usable) await client.logout().catch(() => {});
|
|
}
|
|
}
|
|
|
|
return { applyMessageAction };
|
|
}
|
|
|
|
module.exports = { createMessageActionService };
|