Add per-account mail rules and settings
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
+126
-17
@@ -10,7 +10,8 @@ const ICAL = require('ical.js');
|
||||
|
||||
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
|
||||
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
|
||||
const backgroundSyncIntervalMs = 2 * 60 * 1000;
|
||||
const backgroundSyncIntervalMs = 30 * 1000;
|
||||
const backgroundRetryIntervalMs = 2 * 60 * 1000;
|
||||
const backgroundSyncConcurrency = 2;
|
||||
const backgroundIdleConcurrency = 2;
|
||||
const snoozeCheckIntervalMs = 30 * 1000;
|
||||
@@ -22,6 +23,7 @@ const backgroundSyncGenerations = new Map();
|
||||
const backgroundSyncFailures = new Map();
|
||||
const flagSnapshots = new Map();
|
||||
const idleWatchers = new Map();
|
||||
const lastBackgroundSyncAt = new Map();
|
||||
|
||||
function updateAccountStore(update) {
|
||||
const operation = accountStoreQueue.then(async () => {
|
||||
@@ -57,7 +59,12 @@ async function checkSnoozeReminders() {
|
||||
const snoozes = account.snoozedMessages || [];
|
||||
const remaining = [];
|
||||
for (const item of snoozes) {
|
||||
if (Number(item.dueAt) <= Date.now()) reminders.push({ accountId: account.id, email: account.email, ...item });
|
||||
if (Number(item.dueAt) <= Date.now()) reminders.push({
|
||||
accountId: account.id,
|
||||
email: account.email,
|
||||
notificationsEnabled: account.notificationsEnabled !== false,
|
||||
...item
|
||||
});
|
||||
else remaining.push(item);
|
||||
}
|
||||
account.snoozedMessages = remaining;
|
||||
@@ -65,7 +72,7 @@ async function checkSnoozeReminders() {
|
||||
return reminders;
|
||||
});
|
||||
for (const reminder of due) {
|
||||
if (Notification.isSupported()) {
|
||||
if (reminder.notificationsEnabled !== false && Notification.isSupported()) {
|
||||
new Notification({
|
||||
title: 'Mail reminder',
|
||||
body: `${reminder.subject || 'A message'}${reminder.email ? ` · ${reminder.email}` : ''}`
|
||||
@@ -245,7 +252,37 @@ function normalizeAccount(input) {
|
||||
throw new Error('Enter a valid email, password, and both mail server names.');
|
||||
}
|
||||
if (!displayName) throw new Error('Enter a display name for this mail account.');
|
||||
return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
|
||||
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
|
||||
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
|
||||
throw new Error('Choose a supported mailbox sync interval.');
|
||||
}
|
||||
const inputRules = Array.isArray(input?.rules) ? input.rules : [];
|
||||
if (inputRules.length > 50) throw new Error('You can set up to 50 mail rules per account.');
|
||||
const rules = inputRules.map((rule, index) => {
|
||||
const senderContains = String(rule?.senderContains || '').trim().slice(0, 200);
|
||||
const subjectContains = String(rule?.subjectContains || '').trim().slice(0, 200);
|
||||
const action = String(rule?.action || '');
|
||||
const value = String(rule?.value || '').trim().slice(0, 200);
|
||||
if ((!senderContains && !subjectContains) || !['archive', 'move', 'label', 'flag'].includes(action)) {
|
||||
throw new Error(`Mail rule ${index + 1} needs a sender or subject condition and a valid action.`);
|
||||
}
|
||||
if ((action === 'move' || action === 'label') && !value) {
|
||||
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
|
||||
}
|
||||
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value)) {
|
||||
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash.`);
|
||||
}
|
||||
return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value };
|
||||
});
|
||||
return {
|
||||
email, password, displayName, imapHost, smtpHost,
|
||||
signature: String(input?.signature || '').slice(0, 5000),
|
||||
notificationsEnabled: input?.notificationsEnabled !== false,
|
||||
syncIntervalMinutes,
|
||||
rules,
|
||||
imapPort: 143,
|
||||
smtpPort: 587
|
||||
};
|
||||
}
|
||||
|
||||
function imapClient(account, options = {}) {
|
||||
@@ -316,7 +353,17 @@ async function readAccount(accountId = null) {
|
||||
}
|
||||
|
||||
function publicAccount(account) {
|
||||
return { id: account.id, email: account.email, displayName: account.displayName || '', imapHost: account.imapHost, smtpHost: account.smtpHost };
|
||||
return {
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
displayName: account.displayName || '',
|
||||
imapHost: account.imapHost,
|
||||
smtpHost: account.smtpHost,
|
||||
signature: account.signature || '',
|
||||
notificationsEnabled: account.notificationsEnabled !== false,
|
||||
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
|
||||
rules: Array.isArray(account.rules) ? account.rules : []
|
||||
};
|
||||
}
|
||||
|
||||
async function saveAccount(account) {
|
||||
@@ -393,7 +440,9 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
||||
const messages = [];
|
||||
for (const item of fetched.reverse()) {
|
||||
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
||||
messages.push(await toUiMessage(item, folder));
|
||||
const message = await toUiMessage(item, folder);
|
||||
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
||||
messages.push(message);
|
||||
}
|
||||
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
|
||||
} finally {
|
||||
@@ -451,8 +500,10 @@ async function fetchSnoozedMailbox(account, offset, limit) {
|
||||
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||
}, { uid: true });
|
||||
if (!item?.source) continue;
|
||||
messages.push({
|
||||
...await toUiMessage(item, 'Snoozed'),
|
||||
const message = await toUiMessage(item, 'Snoozed');
|
||||
message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || []));
|
||||
messages.push({
|
||||
...message,
|
||||
sourceFolder,
|
||||
snoozedUntil: Number(snooze.dueAt)
|
||||
});
|
||||
@@ -499,6 +550,7 @@ async function syncAccountMailboxes(account) {
|
||||
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 });
|
||||
@@ -529,6 +581,17 @@ async function syncAccountMailboxes(account) {
|
||||
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) {
|
||||
@@ -556,6 +619,39 @@ async function syncAccountMailboxes(account) {
|
||||
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) {
|
||||
console.error(`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: [] };
|
||||
@@ -568,7 +664,7 @@ async function syncAccountMailboxes(account) {
|
||||
}
|
||||
|
||||
function showNewMailNotification(account, count) {
|
||||
if (!count || !Notification.isSupported()) return;
|
||||
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
|
||||
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
|
||||
if (focused) return;
|
||||
const notification = new Notification({
|
||||
@@ -578,9 +674,14 @@ function showNewMailNotification(account, count) {
|
||||
notification.show();
|
||||
}
|
||||
|
||||
async function syncAccountWithBackoff(account) {
|
||||
async function syncAccountWithBackoff(account, periodicOnly = false) {
|
||||
if (periodicOnly) {
|
||||
const intervalMs = (Number(account.syncIntervalMinutes) || 2) * 60 * 1000;
|
||||
if (Date.now() - (lastBackgroundSyncAt.get(account.id) || 0) < intervalMs) return;
|
||||
}
|
||||
const failure = backgroundSyncFailures.get(account.id);
|
||||
if (failure && Date.now() < failure.retryAt) return;
|
||||
lastBackgroundSyncAt.set(account.id, Date.now());
|
||||
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
||||
try {
|
||||
const result = await syncAccountMailboxes(account);
|
||||
@@ -593,26 +694,29 @@ async function syncAccountWithBackoff(account) {
|
||||
}
|
||||
} catch (error) {
|
||||
const attempts = (failure?.attempts || 0) + 1;
|
||||
const retryDelay = Math.min(30 * 60 * 1000, backgroundSyncIntervalMs * (2 ** Math.min(attempts - 1, 4)));
|
||||
const retryDelay = Math.min(30 * 60 * 1000, backgroundRetryIntervalMs * (2 ** Math.min(attempts - 1, 4)));
|
||||
backgroundSyncFailures.set(account.id, { attempts, retryAt: Date.now() + retryDelay });
|
||||
console.error(`Background mail sync failed for ${account.email}:`, error);
|
||||
if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' });
|
||||
}
|
||||
}
|
||||
|
||||
async function runBackgroundSync() {
|
||||
async function runBackgroundSync(periodicOnly = false) {
|
||||
if (backgroundSyncInProgress) {
|
||||
backgroundSyncRequested = true;
|
||||
if (!periodicOnly) backgroundSyncRequested = true;
|
||||
return;
|
||||
}
|
||||
backgroundSyncInProgress = true;
|
||||
let onlyDueAccounts = periodicOnly;
|
||||
try {
|
||||
do {
|
||||
backgroundSyncRequested = false;
|
||||
const store = (await readAccountStore()) || { accounts: [] };
|
||||
for (let index = 0; index < store.accounts.length; index += backgroundSyncConcurrency) {
|
||||
await Promise.all(store.accounts.slice(index, index + backgroundSyncConcurrency).map(syncAccountWithBackoff));
|
||||
await Promise.all(store.accounts.slice(index, index + backgroundSyncConcurrency)
|
||||
.map(account => syncAccountWithBackoff(account, onlyDueAccounts)));
|
||||
}
|
||||
if (backgroundSyncRequested) onlyDueAccounts = false;
|
||||
} while (backgroundSyncRequested);
|
||||
} finally {
|
||||
backgroundSyncInProgress = false;
|
||||
@@ -669,7 +773,8 @@ ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
|
||||
? {
|
||||
...account,
|
||||
syncState: endpointChanged ? undefined : current.syncState,
|
||||
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || [])
|
||||
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []),
|
||||
ruleLabels: endpointChanged ? {} : (current.ruleLabels || {})
|
||||
}
|
||||
: item);
|
||||
return store.accounts.find(item => item.id === existing.id);
|
||||
@@ -830,12 +935,14 @@ ipcMain.handle('mail:send', async (_event, message) => {
|
||||
const transport = smtpTransport(account);
|
||||
const sentMessageId = `<${require('node:crypto').randomUUID()}@ep-mail.local>`;
|
||||
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||
const body = String(message?.text || '').slice(0, 500000);
|
||||
const signature = String(account.signature || '').slice(0, 5000);
|
||||
const messageOptions = {
|
||||
from: { name: fromName, address: account.email },
|
||||
to,
|
||||
cc: String(message.cc || '').trim() || undefined,
|
||||
subject: String(message.subject || '(no subject)').slice(0, 998),
|
||||
text: String(message.text || '').slice(0, 500000),
|
||||
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
|
||||
messageId: sentMessageId
|
||||
};
|
||||
try {
|
||||
@@ -1069,7 +1176,9 @@ function createWindow() {
|
||||
app.whenReady().then(() => {
|
||||
app.setAppUserModelId('studio.daybreak.mail');
|
||||
createWindow();
|
||||
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
|
||||
const syncTimer = setInterval(() => {
|
||||
void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error));
|
||||
}, backgroundSyncIntervalMs);
|
||||
syncTimer.unref();
|
||||
const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs);
|
||||
snoozeTimer.unref();
|
||||
|
||||
Reference in New Issue
Block a user