Add advanced search and offline mail support
Bump version to 0.1.20 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
+207
-15
@@ -416,7 +416,45 @@ async function folderPath(client, folder, createIfMissing = false) {
|
||||
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
|
||||
}
|
||||
|
||||
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
||||
function filterMailboxMessages(messages, filters = {}) {
|
||||
const text = String(filters.query || '').trim().toLowerCase();
|
||||
const sender = String(filters.sender || '').trim().toLowerCase();
|
||||
const subject = String(filters.subject || '').trim().toLowerCase();
|
||||
const after = filters.after ? new Date(`${filters.after}T00:00:00`).getTime() : null;
|
||||
const before = filters.before ? new Date(`${filters.before}T23:59:59.999`).getTime() : null;
|
||||
return messages.filter(message => {
|
||||
const haystack = `${message.sender || ''} ${message.email || ''} ${message.subject || ''} ${message.snippet || ''} ${(message.body || []).join(' ')}`.toLowerCase();
|
||||
const date = Number(message.timestamp || 0);
|
||||
return (!text || text.split(/\s+/).every(term => haystack.includes(term))) &&
|
||||
(!sender || `${message.sender || ''} ${message.email || ''}`.toLowerCase().includes(sender)) &&
|
||||
(!subject || String(message.subject || '').toLowerCase().includes(subject)) &&
|
||||
(!after || date >= after) && (!before || date <= before) &&
|
||||
(!filters.hasAttachments || (message.attachments || []).length > 0);
|
||||
});
|
||||
}
|
||||
|
||||
async function cacheMailboxMessages(accountId, folder, messages) {
|
||||
if (!messages.length) return;
|
||||
await updateAccountStore(store => {
|
||||
const account = store.accounts.find(item => item.id === accountId);
|
||||
if (!account) return;
|
||||
account.mailCache = account.mailCache || {};
|
||||
const previous = account.mailCache[folder] || [];
|
||||
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
|
||||
for (const message of messages) merged.set(String(message.uid || message.id), message);
|
||||
account.mailCache[folder] = [...merged.values()].slice(-50);
|
||||
});
|
||||
}
|
||||
|
||||
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
|
||||
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
|
||||
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
|
||||
const start = Math.max(0, Number(offset) || 0);
|
||||
const messages = all.slice(start, start + limit);
|
||||
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
|
||||
}
|
||||
|
||||
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
|
||||
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
|
||||
const client = imapClient(account);
|
||||
try {
|
||||
@@ -424,6 +462,27 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
||||
const mailboxPath = await folderPath(client, folder);
|
||||
if (!mailboxPath) return { messages: [], total: 0 };
|
||||
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
|
||||
const snoozed = new Set((account.snoozedMessages || [])
|
||||
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
|
||||
.map(item => Number(item.uid)));
|
||||
if (Object.values(filters).some(value => value && value !== false)) {
|
||||
const searchStart = Math.max(1, mailbox.exists - 4999);
|
||||
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
|
||||
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||
}) : [];
|
||||
const all = [];
|
||||
for (const item of fetched) {
|
||||
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
||||
const message = await toUiMessage(item, folder);
|
||||
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
||||
all.push(message);
|
||||
}
|
||||
await cacheMailboxMessages(account.id, folder, all);
|
||||
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
|
||||
const start = Math.max(0, Number(offset) || 0);
|
||||
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
|
||||
}
|
||||
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
|
||||
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
|
||||
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
|
||||
@@ -434,9 +493,6 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
||||
internalDate: true,
|
||||
source: true
|
||||
});
|
||||
const snoozed = new Set((account.snoozedMessages || [])
|
||||
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
|
||||
.map(item => Number(item.uid)));
|
||||
const messages = [];
|
||||
for (const item of fetched.reverse()) {
|
||||
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
||||
@@ -444,6 +500,7 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
||||
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
||||
messages.push(message);
|
||||
}
|
||||
await cacheMailboxMessages(account.id, folder, messages);
|
||||
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
@@ -453,7 +510,7 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
||||
async function toUiMessage(item, folder) {
|
||||
const parsed = await simpleParser(item.source);
|
||||
const sender = parsed.from?.value?.[0];
|
||||
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim();
|
||||
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
|
||||
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
|
||||
const date = parsed.date || item.internalDate || new Date();
|
||||
return {
|
||||
@@ -466,12 +523,14 @@ async function toUiMessage(item, folder) {
|
||||
snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
||||
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
||||
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
||||
timestamp: date.getTime(),
|
||||
unread: !item.flags?.has('\\Seen'),
|
||||
star: item.flags?.has('\\Flagged') || false,
|
||||
tags: [folder],
|
||||
sent: folder === 'Sent',
|
||||
archived: folder === 'Archive',
|
||||
deleted: folder === 'Trash',
|
||||
sourceFolder: folder,
|
||||
body,
|
||||
uid: Number(item.uid),
|
||||
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
||||
@@ -541,6 +600,7 @@ function backgroundFolderLabel(mailbox) {
|
||||
}
|
||||
|
||||
async function syncAccountMailboxes(account) {
|
||||
await flushMailOutbox(account);
|
||||
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
||||
const client = imapClient(account);
|
||||
try {
|
||||
@@ -798,12 +858,58 @@ ipcMain.handle('mail:connect', async (_event, input) => {
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) => {
|
||||
ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before syncing.');
|
||||
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
|
||||
const folder = allowedFolders.has(requestedFolder) ? requestedFolder : 'Inbox';
|
||||
return fetchMailbox(account, folder, offset);
|
||||
const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder;
|
||||
const folder = allowedFolders.has(selectedFolder) ? selectedFolder : 'Inbox';
|
||||
const { folder: _filterFolder, ...criteria } = filters;
|
||||
try {
|
||||
await flushMailOutbox(account);
|
||||
return await fetchMailbox(account, folder, offset, 20, criteria);
|
||||
} catch (error) {
|
||||
if (!isConnectivityFailure(error)) throw error;
|
||||
const cached = cachedMailbox(account, folder, offset, 20, criteria);
|
||||
if (!cached.total) throw error;
|
||||
return cached;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:list-drafts', async () => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before opening drafts.');
|
||||
return { drafts: account.drafts || [], offline: true };
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:save-draft', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before saving drafts.');
|
||||
const draft = {
|
||||
id: String(input?.id || randomUUID()),
|
||||
to: String(input?.to || '').slice(0, 4000),
|
||||
cc: String(input?.cc || '').slice(0, 4000),
|
||||
subject: String(input?.subject || '').slice(0, 998),
|
||||
text: String(input?.text || '').slice(0, 500000),
|
||||
updatedAt: Date.now()
|
||||
};
|
||||
await updateAccountStore(store => {
|
||||
const saved = store.accounts.find(item => item.id === account.id);
|
||||
if (!saved) throw new Error('That mail account is no longer available.');
|
||||
const drafts = saved.drafts || [];
|
||||
saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500);
|
||||
});
|
||||
return draft;
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:delete-draft', async (_event, id) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before deleting drafts.');
|
||||
await updateAccountStore(store => {
|
||||
const saved = store.accounts.find(item => item.id === account.id);
|
||||
if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id);
|
||||
});
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:set-snooze', async (_event, input) => {
|
||||
@@ -839,9 +945,7 @@ ipcMain.handle('mail:set-snooze', async (_event, input) => {
|
||||
return { ok: true, snoozed: dueAt != null };
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:update-message', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before changing messages.');
|
||||
async function applyMessageAction(account, input) {
|
||||
const uid = Number(input?.uid);
|
||||
const folder = String(input?.folder || 'Inbox');
|
||||
const action = String(input?.action || '');
|
||||
@@ -887,6 +991,78 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
function isConnectivityFailure(error) {
|
||||
const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']);
|
||||
for (let current = error; current; current = current.cause) {
|
||||
if (networkCodes.has(current.code)) return true;
|
||||
if (/network is unreachable|connection timed out|connection refused|could not resolve|socket hang up/i.test(current.message || '')) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function applyQueuedActionToCache(account, input) {
|
||||
const folder = String(input.folder || 'Inbox');
|
||||
const cache = account.mailCache?.[folder];
|
||||
if (!cache) return;
|
||||
const index = cache.findIndex(message => Number(message.uid || message.id) === Number(input.uid));
|
||||
if (index < 0) return;
|
||||
const [message] = cache.splice(index, 1);
|
||||
if (input.action === 'star' || input.action === 'unread') {
|
||||
message[input.action] = Boolean(input.enabled);
|
||||
cache.splice(index, 0, message);
|
||||
return;
|
||||
}
|
||||
const target = input.action === 'archive' ? 'Archive' : input.action === 'delete' ? 'Trash' : input.action === 'inbox' ? 'Inbox' : null;
|
||||
if (!target) {
|
||||
cache.splice(index, 0, message);
|
||||
return;
|
||||
}
|
||||
message.sourceFolder = target;
|
||||
message.archived = target === 'Archive';
|
||||
message.deleted = target === 'Trash';
|
||||
account.mailCache[target] = account.mailCache[target] || [];
|
||||
account.mailCache[target] = [...account.mailCache[target].filter(item => Number(item.uid || item.id) !== Number(input.uid)), message].slice(-50);
|
||||
}
|
||||
|
||||
async function flushMailOutbox(account) {
|
||||
const operations = [...(account.mailOutbox || [])];
|
||||
for (const operation of operations) {
|
||||
try {
|
||||
if (operation.type === 'send') await sendMailNow(account, operation.data);
|
||||
else if (operation.type === 'action') await applyMessageAction(account, operation.data);
|
||||
else throw new Error('Unsupported queued mail operation.');
|
||||
await updateAccountStore(store => {
|
||||
const saved = store.accounts.find(item => item.id === account.id);
|
||||
if (saved) saved.mailOutbox = (saved.mailOutbox || []).filter(item => item.id !== operation.id);
|
||||
});
|
||||
} catch (error) {
|
||||
if (isConnectivityFailure(error)) break;
|
||||
console.error(`Could not complete queued mail operation ${operation.id}:`, error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ipcMain.handle('mail:update-message', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before changing messages.');
|
||||
try {
|
||||
return await applyMessageAction(account, input);
|
||||
} catch (error) {
|
||||
if (!isConnectivityFailure(error)) throw error;
|
||||
await updateAccountStore(store => {
|
||||
const saved = store.accounts.find(item => item.id === account.id);
|
||||
if (!saved) throw new Error('That mail account is no longer available.');
|
||||
saved.mailOutbox = saved.mailOutbox || [];
|
||||
saved.mailOutbox = saved.mailOutbox.filter(item => !(item.type === 'action' &&
|
||||
Number(item.data?.uid) === Number(input.uid) && item.data?.folder === input.folder && item.data?.action === input.action));
|
||||
saved.mailOutbox.push({ id: randomUUID(), type: 'action', data: input, createdAt: Date.now() });
|
||||
applyQueuedActionToCache(saved, input);
|
||||
});
|
||||
return { ok: true, queued: true };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:save-attachment', async (event, input) => {
|
||||
@@ -927,13 +1103,11 @@ ipcMain.handle('mail:sync-inbox', async () => {
|
||||
return fetchMailbox(account, 'Inbox');
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:send', async (_event, message) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before sending.');
|
||||
async function sendMailNow(account, message) {
|
||||
const to = String(message?.to || '').trim();
|
||||
if (!to) throw new Error('Add at least one recipient.');
|
||||
const transport = smtpTransport(account);
|
||||
const sentMessageId = `<${require('node:crypto').randomUUID()}@ep-mail.local>`;
|
||||
const sentMessageId = String(message.messageId || `<${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);
|
||||
@@ -973,6 +1147,24 @@ ipcMain.handle('mail:send', async (_event, message) => {
|
||||
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
|
||||
}
|
||||
return { ok: true, savedToSent };
|
||||
}
|
||||
|
||||
ipcMain.handle('mail:send', async (_event, message) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before sending.');
|
||||
const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` };
|
||||
try {
|
||||
return await sendMailNow(account, queuedMessage);
|
||||
} catch (error) {
|
||||
if (!isConnectivityFailure(error)) throw error;
|
||||
await updateAccountStore(store => {
|
||||
const saved = store.accounts.find(item => item.id === account.id);
|
||||
if (!saved) throw new Error('That mail account is no longer available.');
|
||||
saved.mailOutbox = saved.mailOutbox || [];
|
||||
saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() });
|
||||
});
|
||||
return { ok: true, queued: true };
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:disconnect', async (_event, accountId) => {
|
||||
|
||||
Reference in New Issue
Block a user