Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51f5113aff | ||
|
|
2becdcccd7 | ||
|
|
e50073ab4c |
@@ -4,6 +4,7 @@
|
||||
|
||||
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
|
||||
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
|
||||
- [x] Show the app version after **ep-mail** in the window title.
|
||||
|
||||
## Mail security
|
||||
|
||||
@@ -11,14 +12,23 @@
|
||||
|
||||
## 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
|
||||
|
||||
- [ ] Fix the mailbox space indicator; it is not working.
|
||||
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
||||
- [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.
|
||||
- [ ] Display name must be set per account.
|
||||
- [ ] Remove the display name initials from the bottom-left corner.
|
||||
- [x] Display name must be set per account.
|
||||
- [x] Remove the display name initials from the bottom-left corner.
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ async function openAccountManager(){
|
||||
try{
|
||||
const data=await window.daybreakMail.listAccounts();
|
||||
const accounts=data.accounts||[];
|
||||
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.email)}</strong><small>${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
|
||||
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.displayName||account.email)}</strong><small>${esc(account.email)} · ${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
|
||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Mail accounts</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
|
||||
const close=()=>root.innerHTML='';
|
||||
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
|
||||
|
||||
+247
-29
@@ -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 {
|
||||
@@ -65,10 +110,12 @@ function normalizeAccount(input) {
|
||||
const password = String(input?.password || '');
|
||||
const imapHost = String(input?.imapHost || '').trim();
|
||||
const smtpHost = String(input?.smtpHost || '').trim();
|
||||
const displayName = String(input?.displayName || '').trim().slice(0, 80);
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) {
|
||||
throw new Error('Enter a valid email, password, and both mail server names.');
|
||||
}
|
||||
return { email, password, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
|
||||
if (!displayName) throw new Error('Enter a display name for this mail account.');
|
||||
return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
|
||||
}
|
||||
|
||||
function imapClient(account) {
|
||||
@@ -138,17 +185,17 @@ async function readAccount(accountId = null) {
|
||||
}
|
||||
|
||||
function publicAccount(account) {
|
||||
return { id: account.id, email: account.email, imapHost: account.imapHost, smtpHost: account.smtpHost };
|
||||
return { id: account.id, email: account.email, displayName: account.displayName || '', imapHost: account.imapHost, smtpHost: account.smtpHost };
|
||||
}
|
||||
|
||||
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 +292,162 @@ 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('app:get-version', () => app.getVersion());
|
||||
|
||||
ipcMain.handle('mail:get-account', async () => {
|
||||
const account = await readAccount();
|
||||
return account ? publicAccount(account) : null;
|
||||
@@ -256,35 +459,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 +508,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}`);
|
||||
@@ -391,7 +605,7 @@ ipcMain.handle('mail:send', async (_event, message) => {
|
||||
if (!to) throw new Error('Add at least one recipient.');
|
||||
const transport = smtpTransport(account);
|
||||
const sentMessageId = `<${require('node:crypto').randomUUID()}@ep-mail.local>`;
|
||||
const fromName = String(message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||
const messageOptions = {
|
||||
from: { name: fromName, address: account.email },
|
||||
to,
|
||||
@@ -603,7 +817,7 @@ function createWindow() {
|
||||
height: 920,
|
||||
minWidth: 920,
|
||||
minHeight: 680,
|
||||
title: 'ep-mail',
|
||||
title: `ep-mail v${app.getVersion()}`,
|
||||
backgroundColor: '#f4f5f1',
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
@@ -631,6 +845,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();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const { contextBridge, ipcRenderer } = require('electron');
|
||||
|
||||
contextBridge.exposeInMainWorld('daybreakMail', {
|
||||
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
|
||||
getAccount: () => ipcRenderer.invoke('mail:get-account'),
|
||||
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
|
||||
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
|
||||
@@ -9,6 +10,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),
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
|
||||
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
|
||||
<div class="rail-spacer"></div>
|
||||
<button class="avatar tiny profile-button" title="Account settings" aria-label="Account settings"><span>•</span></button>
|
||||
</aside>
|
||||
|
||||
<aside class="sidebar">
|
||||
|
||||
+99
-39
@@ -1,26 +1,34 @@
|
||||
let connectedMailAccount = null;
|
||||
let mailPageOffset = 0;
|
||||
let mailTotal = 0;
|
||||
let mailboxSyncPromise = null;
|
||||
let mailboxSyncQueued = false;
|
||||
let mailboxRefreshPending = false;
|
||||
|
||||
function updateAccountCard(account) {
|
||||
const card = $('#account-settings');
|
||||
if (!card) return;
|
||||
const email = account.email || '';
|
||||
const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase());
|
||||
const displayName = profileSettings.name.trim() || localName;
|
||||
const displayName = account.displayName?.trim() || profileSettings.name.trim() || localName;
|
||||
const initials = displayName.split(/\s+/).filter(Boolean).map(part => part[0]).join('').slice(0, 2);
|
||||
card.querySelector('.account-avatar').textContent = initials || 'M';
|
||||
card.querySelector('.account-info strong').textContent = displayName;
|
||||
card.querySelector('.account-info span').textContent = email;
|
||||
card.title = `${displayName} <${email}>`;
|
||||
card.querySelector('.online-dot').style.background = '#70ad7b';
|
||||
const profileButton = $('.top-avatar');
|
||||
if (profileButton) {
|
||||
profileButton.textContent = initials || 'M';
|
||||
profileButton.title = `${displayName} <${email}>`;
|
||||
profileButton.setAttribute('aria-label', `${displayName} account settings`);
|
||||
}
|
||||
}
|
||||
|
||||
function openMailAccount(existingAccount = null) {
|
||||
const root = $('#modal-root');
|
||||
const editing = Boolean(existingAccount);
|
||||
const displayName = profileSettings.name || '';
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name"></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><p class="account-note">IMAP uses STARTTLS on port 143 · SMTP uses STARTTLS on port 587.${editing ? ' Leave the password empty to keep the saved password.' : ' Your display name is also used as the sender name.'}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
||||
const displayName = existingAccount?.displayName || profileSettings.name || '';
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><p class="account-note">This display name is saved for this mailbox and used on outgoing messages. IMAP uses STARTTLS on port 143 · SMTP uses STARTTLS on port 587.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
$$('.modal-close').forEach(button => button.onclick = close);
|
||||
$('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
|
||||
@@ -30,6 +38,7 @@ function openMailAccount(existingAccount = null) {
|
||||
const status = $('#mail-account-status');
|
||||
const password = $('#mail-account-password').value;
|
||||
const name = $('#mail-account-display-name').value.trim();
|
||||
if (!name) { status.textContent = 'Enter a display name for this mail account.'; $('#mail-account-display-name').focus(); return; }
|
||||
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; }
|
||||
button.disabled = true;
|
||||
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
||||
@@ -38,13 +47,13 @@ function openMailAccount(existingAccount = null) {
|
||||
const details = {
|
||||
email: $('#mail-account-email').value,
|
||||
password,
|
||||
displayName: name,
|
||||
imapHost: $('#mail-account-imap').value,
|
||||
smtpHost: $('#mail-account-smtp').value
|
||||
};
|
||||
const account = editing
|
||||
? await window.daybreakMail.updateAccount(existingAccount.id, details)
|
||||
: await window.daybreakMail.connect(details);
|
||||
if (name) setProfileName(name);
|
||||
if (editing) {
|
||||
const accountList = await window.daybreakMail.listAccounts();
|
||||
if (accountList.activeId === account.id) {
|
||||
@@ -73,51 +82,102 @@ function openMailAccount(existingAccount = null) {
|
||||
$('#mail-account-email').focus();
|
||||
}
|
||||
async function syncMailbox(showToast, options = {}) {
|
||||
if (mailboxSyncPromise) {
|
||||
mailboxSyncQueued = true;
|
||||
return mailboxSyncPromise;
|
||||
}
|
||||
if (!connectedMailAccount || !window.daybreakMail) {
|
||||
openMailAccount();
|
||||
return;
|
||||
}
|
||||
const refresh = $('#refresh');
|
||||
if (refresh) refresh.disabled = true;
|
||||
try {
|
||||
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
|
||||
const result = await window.daybreakMail.syncFolder(activeFolder, offset);
|
||||
if (options.append) messages.push(...result.messages);
|
||||
else messages.splice(0, messages.length, ...result.messages);
|
||||
messages.forEach(message => {
|
||||
try {
|
||||
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
||||
message.tags = [...new Set([...(message.tags || []), ...localTags])];
|
||||
} catch {}
|
||||
});
|
||||
if (!options.append) mailPageOffset = offset;
|
||||
mailTotal = result.total;
|
||||
activeMessage = messages[0]?.id;
|
||||
selectedIds.clear();
|
||||
const unread = messages.filter(message => message.unread).length;
|
||||
const inboxCount = $('.folder[data-folder="Inbox"] .count');
|
||||
if (inboxCount) inboxCount.textContent = String(unread);
|
||||
const pagination = $('#pagination');
|
||||
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||
const loadMore = $('#load-more');
|
||||
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
|
||||
renderList();
|
||||
if (activeMessage) {
|
||||
openMessage(activeMessage);
|
||||
const current = messages.find(message => message.id === activeMessage);
|
||||
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
||||
const sync = (async () => {
|
||||
try {
|
||||
const previouslyActiveMessage = activeMessage;
|
||||
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
|
||||
const result = await window.daybreakMail.syncFolder(activeFolder, offset);
|
||||
if (options.append) messages.push(...result.messages);
|
||||
else messages.splice(0, messages.length, ...result.messages);
|
||||
messages.forEach(message => {
|
||||
try {
|
||||
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
||||
message.tags = [...new Set([...(message.tags || []), ...localTags])];
|
||||
} catch {}
|
||||
});
|
||||
if (!options.append) mailPageOffset = offset;
|
||||
mailTotal = result.total;
|
||||
activeMessage = messages.some(message => message.id === previouslyActiveMessage)
|
||||
? previouslyActiveMessage
|
||||
: messages[0]?.id;
|
||||
selectedIds.clear();
|
||||
const unread = messages.filter(message => message.unread).length;
|
||||
const inboxCount = $('.folder[data-folder="Inbox"] .count');
|
||||
if (inboxCount) inboxCount.textContent = String(unread);
|
||||
const pagination = $('#pagination');
|
||||
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||
const loadMore = $('#load-more');
|
||||
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
|
||||
renderList();
|
||||
if (activeMessage) {
|
||||
openMessage(activeMessage);
|
||||
const current = messages.find(message => message.id === activeMessage);
|
||||
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
||||
}
|
||||
else $('#reader-pane').innerHTML = emptyReader();
|
||||
updateAccountCard(connectedMailAccount);
|
||||
if (showToast) toast(`Synced ${messages.length} messages`);
|
||||
} catch (error) {
|
||||
toast(error.message || 'Could not sync the inbox');
|
||||
} finally {
|
||||
if (refresh) refresh.disabled = false;
|
||||
}
|
||||
else $('#reader-pane').innerHTML = emptyReader();
|
||||
updateAccountCard(connectedMailAccount);
|
||||
if (showToast) toast(`Synced ${messages.length} messages`);
|
||||
} catch (error) {
|
||||
toast(error.message || 'Could not sync the inbox');
|
||||
})();
|
||||
mailboxSyncPromise = sync;
|
||||
try {
|
||||
await sync;
|
||||
} finally {
|
||||
if (refresh) refresh.disabled = false;
|
||||
mailboxSyncPromise = null;
|
||||
if (mailboxSyncQueued) {
|
||||
mailboxSyncQueued = false;
|
||||
void syncMailbox(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (window.daybreakMail) {
|
||||
window.daybreakMail.getAppVersion().then(version => {
|
||||
document.title = `ep-mail v${version}`;
|
||||
}).catch(error => {
|
||||
console.error('Could not read app version:', error);
|
||||
});
|
||||
window.daybreakMail.onSyncUpdate(update => {
|
||||
if (update.accountId !== connectedMailAccount?.id) return;
|
||||
if (update.error) {
|
||||
toast(update.error);
|
||||
return;
|
||||
}
|
||||
if (update.newCount || (update.foldersChanged || []).length) {
|
||||
if (document.visibilityState === 'visible') {
|
||||
syncMailbox(false, update.newCount ? { offset: 0 } : {});
|
||||
}
|
||||
else mailboxRefreshPending = true;
|
||||
}
|
||||
});
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible' && mailboxRefreshPending) {
|
||||
mailboxRefreshPending = false;
|
||||
syncMailbox(false, { offset: 0 });
|
||||
}
|
||||
});
|
||||
window.addEventListener('focus', () => {
|
||||
if (connectedMailAccount) syncMailbox(false);
|
||||
});
|
||||
setInterval(() => {
|
||||
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
|
||||
syncMailbox(false);
|
||||
}
|
||||
}, 60 * 1000);
|
||||
$('#account-settings').addEventListener('click', openMailAccount);
|
||||
$('#account-settings').addEventListener('keydown', event => {
|
||||
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); }
|
||||
@@ -156,7 +216,7 @@ if (window.daybreakMail) {
|
||||
cc: $('#compose-cc').value,
|
||||
subject: $('#compose-subject').value.trim(),
|
||||
text: $('#compose-body').value,
|
||||
displayName: profileSettings.name
|
||||
displayName: connectedMailAccount.displayName || profileSettings.name
|
||||
});
|
||||
$('#modal-root').innerHTML = '';
|
||||
toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.1.12",
|
||||
"version": "0.1.15",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ep-mail",
|
||||
"version": "0.1.12",
|
||||
"version": "0.1.15",
|
||||
"dependencies": {
|
||||
"ical.js": "^2.2.1",
|
||||
"imapflow": "2.2.1",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.1.12",
|
||||
"version": "0.1.15",
|
||||
"private": true,
|
||||
"description": "Eternity Project mail client",
|
||||
"author": "Eternity Project",
|
||||
|
||||
+2
-3
@@ -11,10 +11,10 @@ productWrite(productKeys.contacts, savedContacts);
|
||||
let savedEvents = productRead(productKeys.events, []);
|
||||
let customLabels = productRead(productKeys.labels, []);
|
||||
let snoozedIds = productRead(productKeys.snoozed, []);
|
||||
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; $$('.profile-button').forEach(b => b.textContent = profileSettings.name.split(/\s+/).filter(Boolean).map(x=>x[0]).join('').slice(0,2).toUpperCase() || '•'); if (connectedMailAccount) updateAccountCard(connectedMailAccount); }
|
||||
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); }
|
||||
function openAccountSettings() {
|
||||
const root=$('#modal-root');
|
||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting and profile.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||
const close=()=>root.innerHTML='';
|
||||
$$('.modal-close').forEach(button=>button.onclick=close);
|
||||
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||
@@ -47,4 +47,3 @@ const baseMessageRenderer=renderList;
|
||||
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?snoozedIds.includes(m.id):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()};
|
||||
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true);
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user