diff --git a/TODO.md b/TODO.md index 460bb34..659eb49 100644 --- a/TODO.md +++ b/TODO.md @@ -11,12 +11,19 @@ ## Appearance and settings +- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears. - [x] Make **EP Wasteland** the default theme for new users. - [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts. - [x] Keep the display name in Account Settings and make it available while adding a mailbox. ## Account settings +- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background. + - [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable. + - [ ] Add persistent IMAP IDLE watchers; bounded periodic polling currently provides updates and reconnect/backoff. + - [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed. + - [x] Send updates to the renderer over IPC and show native notifications for new inbox mail. +- [x] Add new mail notifications. - [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup. - [ ] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views. - [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name. diff --git a/desktop/main.cjs b/desktop/main.cjs index a3bf510..4b5d632 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -1,4 +1,4 @@ -const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog } = require('electron'); +const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor } = require('electron'); const path = require('node:path'); const fs = require('node:fs/promises'); const { ImapFlow } = require('imapflow'); @@ -10,6 +10,51 @@ 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 backgroundSyncConcurrency = 2; +let accountStoreQueue = Promise.resolve(); +let backgroundSyncInProgress = false; +let backgroundSyncRequested = false; +const backgroundSyncGenerations = new Map(); +const backgroundSyncFailures = new Map(); +const flagSnapshots = new Map(); + +function updateAccountStore(update) { + const operation = accountStoreQueue.then(async () => { + const store = (await readAccountStore()) || { accounts: [], activeId: null }; + const result = await update(store); + if (store.accounts.length) await saveAccountStore(store); + else await fs.rm(credentialsPath(), { force: true }); + return result; + }); + accountStoreQueue = operation.catch(() => {}); + return operation; +} + +function sendMailSyncUpdate(update) { + for (const window of BrowserWindow.getAllWindows()) { + if (!window.isDestroyed() && !window.webContents.isDestroyed()) { + window.webContents.send('mail:sync-update', update); + } + } +} + +function requestBackgroundSync(accountId = null, force = false) { + if (accountId) { + backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1); + backgroundSyncFailures.delete(accountId); + flagSnapshots.delete(accountId); + } + if (force) { + for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0; + } + if (backgroundSyncInProgress) { + if (accountId || force) backgroundSyncRequested = true; + return; + } + backgroundSyncRequested = true; + void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error)); +} async function readDavStore() { try { @@ -142,13 +187,13 @@ function publicAccount(account) { } async function saveAccount(account) { - const store = (await readAccountStore()) || { accounts: [], activeId: null }; - const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase()); - const saved = { ...account, id: existing?.id || randomUUID() }; - store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved]; - store.activeId = saved.id; - await saveAccountStore(store); - return saved; + return updateAccountStore(store => { + const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase()); + const saved = { ...existing, ...account, id: existing?.id || randomUUID() }; + store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved]; + store.activeId = saved.id; + return saved; + }); } async function connectMail(account) { @@ -245,6 +290,160 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) { } } +async function saveAccountSyncState(accountId, generation, folders) { + return updateAccountStore(store => { + const account = store.accounts.find(item => item.id === accountId); + if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false; + account.syncState = account.syncState || { folders: {} }; + account.syncState.folders = folders; + return true; + }); +} + +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; +} + +async function syncAccountMailboxes(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 = []; + + 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 }) + : []; + 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 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(() => {}); + } +} + +function showNewMailNotification(account, count) { + if (!count || !Notification.isSupported()) return; + const focused = BrowserWindow.getAllWindows().some(window => window.isFocused()); + if (focused) return; + const notification = new Notification({ + title: count === 1 ? 'New mail' : `${count} new messages`, + body: account.email + }); + notification.show(); +} + +async function syncAccountWithBackoff(account) { + const failure = backgroundSyncFailures.get(account.id); + if (failure && Date.now() < failure.retryAt) return; + const generation = backgroundSyncGenerations.get(account.id) || 0; + try { + const result = await syncAccountMailboxes(account); + if (backgroundSyncGenerations.get(account.id) !== generation) return; + backgroundSyncFailures.delete(account.id); + if (result.newCount || result.changedFolders.length) { + const update = { accountId: account.id, newCount: result.newCount, foldersChanged: result.changedFolders }; + sendMailSyncUpdate(update); + showNewMailNotification(account, result.newCount); + } + } catch (error) { + const attempts = (failure?.attempts || 0) + 1; + const retryDelay = Math.min(30 * 60 * 1000, backgroundSyncIntervalMs * (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() { + if (backgroundSyncInProgress) { + backgroundSyncRequested = true; + return; + } + backgroundSyncInProgress = true; + 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)); + } + } while (backgroundSyncRequested); + } finally { + backgroundSyncInProgress = false; + if (backgroundSyncRequested) void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error)); + } +} + ipcMain.handle('mail:get-account', async () => { const account = await readAccount(); return account ? publicAccount(account) : null; @@ -256,35 +455,45 @@ ipcMain.handle('mail:list-accounts', async () => { }); ipcMain.handle('mail:select-account', async (_event, accountId) => { - const store = await readAccountStore(); - const account = store?.accounts.find(item => item.id === accountId); - if (!account) throw new Error('That mail account is no longer available.'); - store.activeId = account.id; - await saveAccountStore(store); + const account = await updateAccountStore(store => { + const selected = store.accounts.find(item => item.id === accountId); + if (!selected) throw new Error('That mail account is no longer available.'); + store.activeId = selected.id; + return selected; + }); + requestBackgroundSync(); return publicAccount(account); }); ipcMain.handle('mail:remove-account', async (_event, accountId) => { - const store = await readAccountStore(); - if (!store) return { accounts: [], activeId: null }; - store.accounts = store.accounts.filter(account => account.id !== accountId); - if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null; - if (store.accounts.length) await saveAccountStore(store); - else await fs.rm(credentialsPath(), { force: true }); - return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; + const result = await updateAccountStore(store => { + store.accounts = store.accounts.filter(account => account.id !== accountId); + if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null; + return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; + }); + requestBackgroundSync(accountId); + requestBackgroundSync(); + return result; }); ipcMain.handle('mail:update-account', async (_event, accountId, input) => { - const store = await readAccountStore(); - const existing = store?.accounts.find(account => account.id === accountId); + const existing = await readAccount(accountId); if (!existing) throw new Error('That mail account is no longer available.'); const account = normalizeAccount({ ...existing, ...input, password: String(input?.password || '') || existing.password }); account.id = existing.id; try { const status = await connectMail(account); - store.accounts = store.accounts.map(item => item.id === existing.id ? account : item); - await saveAccountStore(store); - return { ...publicAccount(account), ...status }; + const savedAccount = await updateAccountStore(store => { + const current = store.accounts.find(item => item.id === existing.id); + if (!current) throw new Error('That mail account is no longer available.'); + const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost; + store.accounts = store.accounts.map(item => item.id === existing.id + ? { ...account, syncState: endpointChanged ? undefined : current.syncState } + : item); + return store.accounts.find(item => item.id === existing.id); + }); + requestBackgroundSync(existing.id); + return { ...publicAccount(savedAccount), ...status }; } catch (error) { throw new Error(`Could not update the mailbox: ${error.message}`); } @@ -295,6 +504,7 @@ ipcMain.handle('mail:connect', async (_event, input) => { try { const status = await connectMail(account); const saved = await saveAccount(account); + requestBackgroundSync(saved.id); return { ok: true, ...publicAccount(saved), ...status }; } catch (error) { throw new Error(`Could not connect to the mailbox: ${error.message}`); @@ -631,6 +841,10 @@ function createWindow() { app.whenReady().then(() => { app.setAppUserModelId('studio.daybreak.mail'); createWindow(); + const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs); + syncTimer.unref(); + requestBackgroundSync(); + powerMonitor.on('resume', () => requestBackgroundSync(null, true)); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); diff --git a/desktop/preload.cjs b/desktop/preload.cjs index 389e564..5603bb7 100644 --- a/desktop/preload.cjs +++ b/desktop/preload.cjs @@ -9,6 +9,7 @@ contextBridge.exposeInMainWorld('daybreakMail', { updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details), syncFolder: (folder, offset) => ipcRenderer.invoke('mail:sync-folder', folder, offset), syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'), + onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)), updateMessage: details => ipcRenderer.invoke('mail:update-message', details), saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details), send: message => ipcRenderer.invoke('mail:send', message), diff --git a/mail-ui.js b/mail-ui.js index 15acb0e..f5bc420 100644 --- a/mail-ui.js +++ b/mail-ui.js @@ -118,6 +118,16 @@ async function syncMailbox(showToast, options = {}) { } if (window.daybreakMail) { + window.daybreakMail.onSyncUpdate(update => { + if (update.accountId !== connectedMailAccount?.id) return; + if (update.error) { + toast(update.error); + return; + } + if ((update.foldersChanged || []).includes(activeFolder)) { + syncMailbox(false, { offset: 0 }); + } + }); $('#account-settings').addEventListener('click', openMailAccount); $('#account-settings').addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); } diff --git a/package-lock.json b/package-lock.json index 2bf38a6..b940524 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.1.12", + "version": "0.1.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.1.12", + "version": "0.1.13", "dependencies": { "ical.js": "^2.2.1", "imapflow": "2.2.1", diff --git a/package.json b/package.json index baca394..1b6dd0e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.1.12", + "version": "0.1.13", "private": true, "description": "Eternity Project mail client", "author": "Eternity Project",