Files
ep-mail-client/desktop/mail/sync-service.cjs
T

153 lines
6.9 KiB
JavaScript

function backgroundFolderLabel(mailbox) {
const specialUse = String(mailbox.specialUse || '').toLowerCase();
if (specialUse === '\\sent') return 'Sent';
if (specialUse === '\\archive') return 'Archive';
if (specialUse === '\\trash') return 'Trash';
if (mailbox.path.toLowerCase() === 'inbox') return 'Inbox';
const finalPart = mailbox.path.toLowerCase().split(/[./]/).pop();
if (['sent', 'sent items', 'sent mail', 'sent messages'].includes(finalPart)) return 'Sent';
if (['archive', 'archives', 'all mail'].includes(finalPart)) return 'Archive';
if (['trash', 'deleted items', 'deleted messages'].includes(finalPart)) return 'Trash';
return mailbox.path;
}
function createMailboxSyncService({
imapClient,
flushMailOutbox,
updateAccountStore,
saveAccountSyncState,
backgroundSyncGenerations,
flagSnapshots,
findSpecialMailbox,
folderPath,
logError = (...args) => console.error(...args)
}) {
async function syncAccountMailboxes(account) {
await flushMailOutbox(account);
const generation = backgroundSyncGenerations.get(account.id) || 0;
const client = imapClient(account);
try {
await client.connect();
const mailboxes = await client.list();
const states = { ...(account.syncState?.folders || {}) };
const accountSnapshots = new Map(flagSnapshots.get(account.id) || []);
let inboxNewCount = 0;
const changedFolders = [];
const ruleActions = [];
for (const listedMailbox of mailboxes) {
const mailbox = await client.mailboxOpen(listedMailbox.path, { readOnly: true });
const folder = listedMailbox.path;
const label = backgroundFolderLabel(listedMailbox);
const uidValidity = String(mailbox.uidValidity);
const uidCeiling = Math.max(0, Number(mailbox.uidNext) - 1);
const oldState = states[folder];
const cursorIsValid = oldState?.uidValidity === uidValidity && Number.isInteger(oldState.lastUid);
if (!cursorIsValid) {
states[folder] = {
uidValidity,
lastUid: uidCeiling,
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : null
};
if (!mailbox.highestModseq) {
const initialFlags = await client.fetchAll('1:*', { uid: true, flags: true });
accountSnapshots.set(folder, {
uidValidity,
flags: new Map(initialFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]))
});
}
continue;
}
const previousUid = Number(oldState.lastUid);
const added = uidCeiling > previousUid
? await client.fetchAll(`${previousUid + 1}:${uidCeiling}`, { uid: true, envelope: true, flags: true }, { uid: true })
: [];
if (label === 'Inbox' && account.rules?.length) {
for (const item of added) {
const rule = account.rules.find(candidate => {
const sender = (item.envelope?.from || []).map(address => `${address.name || ''} ${address.address || ''}`).join(' ').toLowerCase();
const subject = String(item.envelope?.subject || '').toLowerCase();
return (!candidate.senderContains || sender.includes(candidate.senderContains.toLowerCase())) &&
(!candidate.subjectContains || subject.includes(candidate.subjectContains.toLowerCase()));
});
if (rule) ruleActions.push({ uid: Number(item.uid), folder, rule });
}
}
let flagsChanged = false;
if (mailbox.highestModseq && oldState.highestModseq) {
const changed = await client.fetchAll('1:*', { uid: true, flags: true, modseq: true }, {
uid: true,
changedSince: BigInt(oldState.highestModseq)
});
flagsChanged = changed.some(item => Number(item.uid) <= previousUid);
} else if (!mailbox.highestModseq) {
const currentFlags = await client.fetchAll('1:*', { uid: true, flags: true });
const nextSnapshot = new Map(currentFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]));
const previousSnapshot = accountSnapshots.get(folder);
if (previousSnapshot?.uidValidity === uidValidity) {
flagsChanged = [...previousSnapshot.flags].some(([uid, flags]) => uid <= previousUid && nextSnapshot.get(uid) !== flags);
}
accountSnapshots.set(folder, { uidValidity, flags: nextSnapshot });
}
states[folder] = {
uidValidity,
lastUid: Math.max(previousUid, uidCeiling),
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : oldState.highestModseq || null
};
if (added.length && label === 'Inbox') inboxNewCount += added.length;
if (added.length || flagsChanged) changedFolders.push(label);
}
const ruleLabels = [];
for (const { uid, folder, rule } of ruleActions) {
const lock = await client.getMailboxLock(folder);
try {
if (rule.action === 'flag') {
await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
} else if (rule.action === 'archive' || rule.action === 'move') {
const target = rule.action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
: await folderPath(client, rule.value);
if (!target) throw new Error(`Rule destination mailbox "${rule.value}" was not found.`);
if (target !== folder) await client.messageMove(uid, target, { uid: true });
changedFolders.push(rule.action === 'archive' ? 'Archive' : backgroundFolderLabel({ path: target }));
} else if (rule.action === 'label') {
ruleLabels.push({ key: `${folder}:${uid}`, label: rule.value });
}
} catch (error) {
logError(`Could not apply mail rule "${rule.id}" to message ${uid}:`, error);
} finally {
lock.release();
}
}
if (ruleLabels.length) {
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) return;
saved.ruleLabels = saved.ruleLabels || {};
for (const { key, label } of ruleLabels) {
saved.ruleLabels[key] = [...new Set([...(saved.ruleLabels[key] || []), label])];
}
});
}
const saved = await saveAccountSyncState(account.id, generation, states);
if (!saved || backgroundSyncGenerations.get(account.id) !== generation) {
return { newCount: 0, changedFolders: [] };
}
flagSnapshots.set(account.id, accountSnapshots);
return { newCount: inboxNewCount, changedFolders: [...new Set(changedFolders)] };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
return { syncAccountMailboxes };
}
module.exports = { backgroundFolderLabel, createMailboxSyncService };