Add Snooze messages until a chosen time and show a follow-up reminder when they return. Bump version V0.1.17
This commit is contained in:
+173
-33
@@ -13,9 +13,11 @@ const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-account
|
||||
const backgroundSyncIntervalMs = 2 * 60 * 1000;
|
||||
const backgroundSyncConcurrency = 2;
|
||||
const backgroundIdleConcurrency = 2;
|
||||
const snoozeCheckIntervalMs = 30 * 1000;
|
||||
let accountStoreQueue = Promise.resolve();
|
||||
let backgroundSyncInProgress = false;
|
||||
let backgroundSyncRequested = false;
|
||||
let snoozeReminderCheckInProgress = false;
|
||||
const backgroundSyncGenerations = new Map();
|
||||
const backgroundSyncFailures = new Map();
|
||||
const flagSnapshots = new Map();
|
||||
@@ -41,6 +43,48 @@ function sendMailSyncUpdate(update) {
|
||||
}
|
||||
}
|
||||
|
||||
async function checkSnoozeReminders() {
|
||||
if (snoozeReminderCheckInProgress) return;
|
||||
snoozeReminderCheckInProgress = true;
|
||||
try {
|
||||
const current = await readAccountStore();
|
||||
if (!current?.accounts.some(account =>
|
||||
(account.snoozedMessages || []).some(item => Number(item.dueAt) <= Date.now())
|
||||
)) return;
|
||||
const due = await updateAccountStore(store => {
|
||||
const reminders = [];
|
||||
for (const account of store.accounts) {
|
||||
const snoozes = account.snoozedMessages || [];
|
||||
const remaining = [];
|
||||
for (const item of snoozes) {
|
||||
if (Number(item.dueAt) <= Date.now()) reminders.push({ accountId: account.id, email: account.email, ...item });
|
||||
else remaining.push(item);
|
||||
}
|
||||
account.snoozedMessages = remaining;
|
||||
}
|
||||
return reminders;
|
||||
});
|
||||
for (const reminder of due) {
|
||||
if (Notification.isSupported()) {
|
||||
new Notification({
|
||||
title: 'Mail reminder',
|
||||
body: `${reminder.subject || 'A message'}${reminder.email ? ` · ${reminder.email}` : ''}`
|
||||
}).show();
|
||||
}
|
||||
sendMailSyncUpdate({
|
||||
accountId: reminder.accountId,
|
||||
snoozeReminder: true,
|
||||
snoozedFolder: reminder.folder,
|
||||
foldersChanged: ['Snoozed', reminder.folder]
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Could not process snooze reminders:', error);
|
||||
} finally {
|
||||
snoozeReminderCheckInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
function requestBackgroundSync(accountId = null, force = false) {
|
||||
if (accountId) {
|
||||
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
|
||||
@@ -326,6 +370,7 @@ async function folderPath(client, folder, createIfMissing = false) {
|
||||
}
|
||||
|
||||
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
||||
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
|
||||
const client = imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
@@ -342,43 +387,85 @@ 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) continue;
|
||||
const parsed = await simpleParser(item.source);
|
||||
const sender = parsed.from?.value?.[0];
|
||||
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim();
|
||||
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();
|
||||
messages.push({
|
||||
id: Number(item.uid),
|
||||
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
|
||||
color: '#dce6df',
|
||||
sender: sender?.name || sender?.address || 'Unknown sender',
|
||||
email: sender?.address || '',
|
||||
subject: parsed.subject || '(no subject)',
|
||||
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),
|
||||
unread: !item.flags?.has('\\Seen'),
|
||||
star: item.flags?.has('\\Flagged') || false,
|
||||
tags: [folder],
|
||||
sent: folder === 'Sent',
|
||||
archived: folder === 'Archive',
|
||||
deleted: folder === 'Trash',
|
||||
body,
|
||||
uid: Number(item.uid),
|
||||
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
||||
attachment: parsed.attachments?.[0]?.filename || null,
|
||||
size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
|
||||
});
|
||||
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
||||
messages.push(await toUiMessage(item, folder));
|
||||
}
|
||||
return { messages, total: mailbox.exists, start: first, end: Math.min(end, mailbox.exists), folder };
|
||||
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
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 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 {
|
||||
id: Number(item.uid),
|
||||
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
|
||||
color: '#dce6df',
|
||||
sender: sender?.name || sender?.address || 'Unknown sender',
|
||||
email: sender?.address || '',
|
||||
subject: parsed.subject || '(no subject)',
|
||||
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),
|
||||
unread: !item.flags?.has('\\Seen'),
|
||||
star: item.flags?.has('\\Flagged') || false,
|
||||
tags: [folder],
|
||||
sent: folder === 'Sent',
|
||||
archived: folder === 'Archive',
|
||||
deleted: folder === 'Trash',
|
||||
body,
|
||||
uid: Number(item.uid),
|
||||
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
||||
attachment: parsed.attachments?.[0]?.filename || null,
|
||||
size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchSnoozedMailbox(account, offset, limit) {
|
||||
const now = Date.now();
|
||||
const pending = (account.snoozedMessages || [])
|
||||
.filter(item => Number(item.dueAt) > now)
|
||||
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
|
||||
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||
const client = imapClient(account);
|
||||
const messages = [];
|
||||
try {
|
||||
await client.connect();
|
||||
for (const snooze of selected) {
|
||||
const sourceFolder = String(snooze.folder || 'Inbox');
|
||||
const mailboxPath = await folderPath(client, sourceFolder);
|
||||
if (!mailboxPath) continue;
|
||||
const lock = await client.getMailboxLock(mailboxPath);
|
||||
try {
|
||||
const item = await client.fetchOne(Number(snooze.uid), {
|
||||
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||
}, { uid: true });
|
||||
if (!item?.source) continue;
|
||||
messages.push({
|
||||
...await toUiMessage(item, 'Snoozed'),
|
||||
sourceFolder,
|
||||
snoozedUntil: Number(snooze.dueAt)
|
||||
});
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
|
||||
}
|
||||
|
||||
async function saveAccountSyncState(accountId, generation, folders) {
|
||||
return updateAccountStore(store => {
|
||||
const account = store.accounts.find(item => item.id === accountId);
|
||||
@@ -579,7 +666,11 @@ ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
|
||||
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 }
|
||||
? {
|
||||
...account,
|
||||
syncState: endpointChanged ? undefined : current.syncState,
|
||||
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || [])
|
||||
}
|
||||
: item);
|
||||
return store.accounts.find(item => item.id === existing.id);
|
||||
});
|
||||
@@ -610,6 +701,39 @@ ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) =
|
||||
return fetchMailbox(account, folder, offset);
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:set-snooze', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before setting a reminder.');
|
||||
const uid = Number(input?.uid);
|
||||
const folder = String(input?.sourceFolder || input?.folder || 'Inbox');
|
||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||
if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.');
|
||||
const dueAt = input?.dueAt == null ? null : Number(input.dueAt);
|
||||
if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) {
|
||||
throw new Error('Choose a reminder time in the future.');
|
||||
}
|
||||
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 snoozes = saved.snoozedMessages || [];
|
||||
const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder));
|
||||
if (dueAt != null) {
|
||||
remaining.push({
|
||||
uid,
|
||||
folder,
|
||||
dueAt,
|
||||
subject: String(input.subject || '').slice(0, 200)
|
||||
});
|
||||
}
|
||||
saved.snoozedMessages = remaining;
|
||||
});
|
||||
sendMailSyncUpdate({
|
||||
accountId: account.id,
|
||||
foldersChanged: ['Snoozed', folder]
|
||||
});
|
||||
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.');
|
||||
@@ -617,7 +741,7 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
|
||||
const folder = String(input?.folder || 'Inbox');
|
||||
const action = String(input?.action || '');
|
||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||
if (!['star', 'unread', 'archive', 'delete'].includes(action)) throw new Error('That mail action is not supported.');
|
||||
if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
|
||||
const client = imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
@@ -634,13 +758,26 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
|
||||
} else {
|
||||
const target = action === 'archive'
|
||||
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
|
||||
: await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash');
|
||||
if (action === 'delete' && sourcePath === target) await client.messageDelete(uid, { uid: true });
|
||||
: action === 'delete'
|
||||
? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
|
||||
: 'INBOX';
|
||||
if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
|
||||
if (action === 'delete') await client.messageDelete(uid, { uid: true });
|
||||
}
|
||||
else await client.messageMove(uid, target, { uid: true });
|
||||
}
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
if (action === 'archive' || action === 'delete' || action === 'inbox') {
|
||||
await updateAccountStore(store => {
|
||||
const saved = store.accounts.find(item => item.id === account.id);
|
||||
if (saved) {
|
||||
saved.snoozedMessages = (saved.snoozedMessages || [])
|
||||
.filter(item => Number(item.uid) !== uid || item.folder !== folder);
|
||||
}
|
||||
});
|
||||
}
|
||||
return { ok: true };
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
@@ -934,6 +1071,9 @@ app.whenReady().then(() => {
|
||||
createWindow();
|
||||
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
|
||||
syncTimer.unref();
|
||||
const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs);
|
||||
snoozeTimer.unref();
|
||||
void checkSnoozeReminders();
|
||||
requestBackgroundSync();
|
||||
powerMonitor.on('suspend', () => {
|
||||
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||
|
||||
Reference in New Issue
Block a user