Ver V0.1.13 Add Automatic mailbox sync
This commit is contained in:
+239
-25
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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),
|
||||
|
||||
Reference in New Issue
Block a user