From 9b3a890b1d1af4238692b08885f91d567e7de886 Mon Sep 17 00:00:00 2001 From: Tero Date: Wed, 7 Oct 2026 01:24:01 +0300 Subject: [PATCH] Add per-account mail rules and settings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 4 +- TODO.md | 8 +- .../daybreak/mail/AndroidAccountVault.kt | 22 +++ .../daybreak/mail/AndroidMailService.kt | 98 +++++++++++- .../java/studio/daybreak/mail/EpMailPlugin.kt | 39 +++++ .../studio/daybreak/mail/MailIdleService.kt | 110 +++++++------- desktop/main.cjs | 143 +++++++++++++++--- mail-ui.js | 49 +++++- package-lock.json | 4 +- package.json | 2 +- productivity.js | 6 +- styles.css | 4 + www/mail-ui.js | 49 +++++- www/productivity.js | 6 +- www/styles.css | 4 + 15 files changed, 456 insertions(+), 92 deletions(-) diff --git a/README.md b/README.md index 723cfa5..8e2a498 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,13 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E ## Desktop app -The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. The app uses required STARTTLS for IMAP port 143 and SMTP port 587 and stores the password encrypted through the operating system credential store. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. +The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Settings are stored with the encrypted account credentials. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker. ## Android app -The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run: +The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run: ```sh npm install diff --git a/TODO.md b/TODO.md index ad0a91d..3250b35 100644 --- a/TODO.md +++ b/TODO.md @@ -14,8 +14,12 @@ - [ ] Add Undo Send and scheduled sending. - [ ] Improve mail search with sender, subject, date, folder, and attachment filters. - [ ] Add offline reading and drafts, with queued actions when connectivity returns. -- [ ] Add user-configurable rules to sort, archive, label, or flag messages automatically. -- [ ] Add per-account signatures, notification preferences, and sync settings. +- [ ] Group related messages into conversations, with controls to expand or collapse threads. +- [ ] Add attachment previews and a dedicated view to find and manage attachments across mailboxes. +- [ ] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search. +- [ ] Add warnings for suspicious sender addresses and links before opening potentially unsafe content. +- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject. +- [x] Add per-account signatures, notification preferences, and sync settings. - [ ] Block remote images by default and let users load them per message. ## Mail security diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt index da108c2..17b8535 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt @@ -187,6 +187,24 @@ internal object AndroidAccountVault { return JSONArray() } + @Synchronized + fun addRuleLabel(id: String, folder: String, uid: Long, label: String) { + val store = read() + val accounts = store.optJSONArray("accounts") ?: return + for (index in 0 until accounts.length()) { + val account = accounts.getJSONObject(index) + if (account.optString("id") != id) continue + val labels = account.optJSONObject("ruleLabels") ?: JSONObject() + val key = "$folder:$uid" + val values = labels.optJSONArray(key) ?: JSONArray() + if ((0 until values.length()).none { values.optString(it) == label }) values.put(label) + labels.put(key, values) + account.put("ruleLabels", labels) + write(store) + return + } + } + fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray { val result = JSONArray() for (index in 0 until accounts.length()) { @@ -202,6 +220,10 @@ internal object AndroidAccountVault { .put("displayName", account.optString("displayName")) .put("imapHost", account.optString("imapHost")) .put("smtpHost", account.optString("smtpHost")) + .put("signature", account.optString("signature")) + .put("notificationsEnabled", account.optBoolean("notificationsEnabled", true)) + .put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2)) + .put("rules", account.optJSONArray("rules") ?: JSONArray()) fun storeDav(type: String): JSONArray = read().optJSONArray(type) ?: JSONArray() diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt index faeb710..a6d052c 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -83,7 +83,7 @@ internal object AndroidMailService { item.optLong("dueAt") > System.currentTimeMillis() } if (isSnoozed) continue - result.put(messageJson(folder, message, requestedFolder)) + result.put(messageJson(folder, message, requestedFolder, account)) } JSONObject().put("messages", result).put("total", total) .put("start", first).put("end", end).put("folder", requestedFolder) @@ -108,7 +108,7 @@ internal object AndroidMailService { folder.open(Folder.READ_ONLY) try { val message = (folder as? UIDFolder)?.getMessageByUID(snooze.optLong("uid")) ?: continue - messages.put(messageJson(folder, message, "Snoozed") + messages.put(messageJson(folder, message, "Snoozed", account, sourceFolder) .put("sourceFolder", sourceFolder) .put("snoozedUntil", snooze.optLong("dueAt"))) } finally { @@ -185,7 +185,12 @@ internal object AndroidMailService { val cc = input.optString("cc").trim() if (cc.isNotEmpty()) message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, true)) message.subject = input.optString("subject", "(no subject)") - message.setText(input.optString("text"), "UTF-8") + val body = input.optString("text") + val signature = account.optString("signature").take(5000) + message.setText( + if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature", + "UTF-8" + ) message.sentDate = Date() message.saveChanges() @@ -250,12 +255,63 @@ internal object AndroidMailService { if (latestUid <= lastUid) return@withStore 0 val added = uidFolder.getMessagesByUID(lastUid + 1, UIDFolder.LASTUID) AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid) + applyRules(account, added.mapNotNull { try { uidFolder.getUID(it) } catch (_: Exception) { null } }) added.size } finally { folder.close(false) } } + fun applyRules(account: JSONObject, uids: List) { + val rules = account.optJSONArray("rules") ?: return + if (rules.length() == 0 || uids.isEmpty()) return + withStore(account) { _, store -> + val inbox = resolveFolder(store, "Inbox") ?: return@withStore + for (uid in uids.distinct()) { + try { + inbox.open(Folder.READ_WRITE) + try { + val message = (inbox as? UIDFolder)?.getMessageByUID(uid) ?: continue + val sender = message.from.orEmpty().joinToString(" ") { address -> + if (address is InternetAddress) "${address.personal.orEmpty()} ${address.address}" else address.toString() + } + val subject = message.subject.orEmpty() + val matched = (0 until rules.length()).asSequence() + .map { rules.getJSONObject(it) } + .firstOrNull { rule -> + val senderCondition = rule.optString("senderContains") + val subjectCondition = rule.optString("subjectContains") + (senderCondition.isBlank() || sender.contains(senderCondition, ignoreCase = true)) && + (subjectCondition.isBlank() || subject.contains(subjectCondition, ignoreCase = true)) + } ?: continue + when (matched.optString("action")) { + "flag" -> message.setFlag(Flags.Flag.FLAGGED, true) + "label" -> AndroidAccountVault.addRuleLabel( + account.optString("id"), "Inbox", uid, matched.optString("value") + ) + "archive", "move" -> { + val destination = if (matched.optString("action") == "archive") { + resolveFolder(store, "Archive") ?: store.getFolder("Archive").also { + if (!it.exists()) it.create(Folder.HOLDS_MESSAGES) + } + } else resolveFolder(store, matched.optString("value")) + ?: throw IllegalStateException("Rule destination mailbox \"${matched.optString("value")}\" was not found.") + if (destination.fullName != inbox.fullName) { + inbox.copyMessages(arrayOf(message), destination) + message.setFlag(Flags.Flag.DELETED, true) + } + } + } + } finally { + inbox.close(true) + } + } catch (error: Exception) { + android.util.Log.e("EpMailRules", "Could not apply a mail rule to message $uid", error) + } + } + } + } + fun watchInbox( account: JSONObject, onNewMail: (Int) -> Unit, @@ -266,6 +322,8 @@ internal object AndroidMailService { setProperty("mail.imap.timeout", "0") setProperty("mail.imap.writetimeout", "60000") } + val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2) + .coerceIn(2, 60) * 60_000L val session = Session.getInstance(props, credentials(account)) val store = session.getStore("imap") try { @@ -295,6 +353,12 @@ internal object AndroidMailService { if (uidValidity > 0 && newestUid > 0) { AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, newestUid) } + val addedUids = event.messages.mapNotNull { message -> + try { uidFolder?.getUID(message) } catch (_: Exception) { null } + } + Thread({ + applyRules(account, addedUids) + }, "ep-mail-rules-${account.optString("id")}").start() onNewMail(event.messages.size) } } @@ -307,9 +371,12 @@ internal object AndroidMailService { if (supportsIdle && inbox is IMAPFolder) { inbox.idle() } else { - Thread.sleep(120_000) + Thread.sleep(pollingIntervalMs) val currentCount = inbox.messageCount - if (currentCount > previousCount) onNewMail(currentCount - previousCount) + if (currentCount > previousCount) { + val added = checkForNewMail(account) + if (added > 0) onNewMail(added) + } previousCount = currentCount } } catch (error: Exception) { @@ -331,10 +398,20 @@ internal object AndroidMailService { fun accountFingerprint(account: JSONObject): String = listOf( account.optString("email"), account.optString("imapHost"), - account.optString("password") + account.optString("password"), + account.optBoolean("notificationsEnabled", true), + account.optInt("syncIntervalMinutes", 2), + account.optString("signature"), + account.optJSONArray("rules")?.toString().orEmpty() ).joinToString("|").hashCode().toString() - private fun messageJson(folder: Folder, message: Message, requestedFolder: String): JSONObject { + private fun messageJson( + folder: Folder, + message: Message, + requestedFolder: String, + account: JSONObject? = null, + labelFolder: String = requestedFolder + ): JSONObject { val uid = (folder as? UIDFolder)?.getUID(message) ?: message.messageNumber.toLong() val sender = (message.from?.firstOrNull() as? InternetAddress) val senderName = decode(sender?.personal).ifBlank { sender?.address ?: "Unknown sender" } @@ -347,6 +424,13 @@ internal object AndroidMailService { val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) val date = message.receivedDate ?: message.sentDate ?: Date() val tags = JSONArray().put(requestedFolder) + val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid") + if (ruleLabels != null) { + for (index in 0 until ruleLabels.length()) { + val label = ruleLabels.optString(index) + if (label.isNotBlank()) tags.put(label) + } + } val files = attachmentList(attachments) val flags = message.flags val id = uid.toDouble() diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt index 8bee720..ed95b66 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -325,10 +325,49 @@ class EpMailPlugin : Plugin() { .put("displayName", displayName) .put("imapHost", imapHost) .put("smtpHost", smtpHost) + .put("signature", input.optString("signature").take(5000)) + .put("notificationsEnabled", input.optBoolean("notificationsEnabled", true)) + .put("syncIntervalMinutes", input.optInt("syncIntervalMinutes", 2).also { + require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." } + }) + .put("rules", normalizeRules(input.optJSONArray("rules"))) .put("imapPort", input.optInt("imapPort", 143)) .put("smtpPort", input.optInt("smtpPort", 587)) } + private fun normalizeRules(input: JSONArray?): JSONArray { + val result = JSONArray() + if (input == null) return result + require(input.length() <= 50) { "You can set up to 50 mail rules per account." } + for (index in 0 until input.length()) { + val rule = input.getJSONObject(index) + val sender = rule.optString("senderContains").trim().take(200) + val subject = rule.optString("subjectContains").trim().take(200) + val action = rule.optString("action") + val value = rule.optString("value").trim().take(200) + require((sender.isNotEmpty() || subject.isNotEmpty()) && + action in setOf("archive", "move", "label", "flag")) { + "Mail rule ${index + 1} needs a sender or subject condition and a valid action." + } + require(action !in setOf("move", "label") || value.isNotEmpty()) { + "Mail rule ${index + 1} needs a destination folder or label." + } + require(action != "move" || !value.any { it == '\r' || it == '\n' || it == '\u0000' }) { + "Mail rule ${index + 1} has an invalid destination folder." + } + require(action != "move" || value in setOf("Inbox", "Archive", "Trash")) { + "Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash." + } + result.put(JSONObject() + .put("id", rule.optString("id").ifBlank { UUID.randomUUID().toString() }) + .put("senderContains", sender) + .put("subjectContains", subject) + .put("action", action) + .put("value", value)) + } + return result + } + private fun JSONObject.toJSObject(): JSObject = JSObject(toString()) companion object { diff --git a/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt b/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt index abcd2cc..70b57db 100644 --- a/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt @@ -200,14 +200,37 @@ class MailIdleService : Service() { if (count <= 0) return val appContext = context.applicationContext val email = account.optString("email") - val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && - notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) { - notificationManager.createNotificationChannel(NotificationChannel( - MAIL_CHANNEL_ID, - "New mail", - NotificationManager.IMPORTANCE_DEFAULT - ).apply { description = "Notifies you when new mail arrives." }) + if (account.optBoolean("notificationsEnabled", true)) { + val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && + notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) { + notificationManager.createNotificationChannel(NotificationChannel( + MAIL_CHANNEL_ID, + "New mail", + NotificationManager.IMPORTANCE_DEFAULT + ).apply { description = "Notifies you when new mail arrives." }) + } + val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName) + ?: Intent(appContext, MainActivity::class.java) + launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) + val pendingIntent = PendingIntent.getActivity( + appContext, 0, launchIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + val title = if (count == 1) "New mail" else "$count new messages" + val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) + .setSmallIcon(android.R.drawable.ic_dialog_email) + .setContentTitle(title) + .setContentText(email) + .setAutoCancel(true) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .setContentIntent(pendingIntent) + .build() + try { + NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification) + } catch (error: SecurityException) { + android.util.Log.w(TAG, "Notification permission is unavailable", error) + } } val update = JSONObject() .put("accountId", account.optString("id")) @@ -216,56 +239,37 @@ class MailIdleService : Service() { appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC) .setPackage(appContext.packageName) .putExtra(EXTRA_SYNC_UPDATE, update.toString())) - val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName) - ?: Intent(appContext, MainActivity::class.java) - launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) - val pendingIntent = PendingIntent.getActivity( - appContext, 0, launchIntent, - PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE - ) - val title = if (count == 1) "New mail" else "$count new messages" - val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) - .setSmallIcon(android.R.drawable.ic_dialog_email) - .setContentTitle(title) - .setContentText(email) - .setAutoCancel(true) - .setPriority(NotificationCompat.PRIORITY_DEFAULT) - .setContentIntent(pendingIntent) - .build() - try { - NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification) - } catch (error: SecurityException) { - android.util.Log.w(TAG, "Notification permission is unavailable", error) - } } fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) { val appContext = context.applicationContext val email = account.optString("email") - val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && - manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) { - manager.createNotificationChannel(NotificationChannel( - MAIL_CHANNEL_ID, - "Mail reminders", - NotificationManager.IMPORTANCE_DEFAULT - )) - } - val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) - .setSmallIcon(android.R.drawable.ic_dialog_email) - .setContentTitle("Mail reminder") - .setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" }) - .setAutoCancel(true) - .setPriority(NotificationCompat.PRIORITY_DEFAULT) - .setContentIntent(appPendingIntentFor(appContext)) - .build() - try { - NotificationManagerCompat.from(appContext).notify( - (email + reminder.optLong("uid")).hashCode(), - notification - ) - } catch (error: SecurityException) { - android.util.Log.w(TAG, "Reminder notification permission is unavailable", error) + if (account.optBoolean("notificationsEnabled", true)) { + val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && + manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) { + manager.createNotificationChannel(NotificationChannel( + MAIL_CHANNEL_ID, + "Mail reminders", + NotificationManager.IMPORTANCE_DEFAULT + )) + } + val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) + .setSmallIcon(android.R.drawable.ic_dialog_email) + .setContentTitle("Mail reminder") + .setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" }) + .setAutoCancel(true) + .setPriority(NotificationCompat.PRIORITY_DEFAULT) + .setContentIntent(appPendingIntentFor(appContext)) + .build() + try { + NotificationManagerCompat.from(appContext).notify( + (email + reminder.optLong("uid")).hashCode(), + notification + ) + } catch (error: SecurityException) { + android.util.Log.w(TAG, "Reminder notification permission is unavailable", error) + } } val update = JSONObject() .put("accountId", account.optString("id")) diff --git a/desktop/main.cjs b/desktop/main.cjs index 9cb2ad6..b81965e 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -10,7 +10,8 @@ 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 backgroundSyncIntervalMs = 30 * 1000; +const backgroundRetryIntervalMs = 2 * 60 * 1000; const backgroundSyncConcurrency = 2; const backgroundIdleConcurrency = 2; const snoozeCheckIntervalMs = 30 * 1000; @@ -22,6 +23,7 @@ const backgroundSyncGenerations = new Map(); const backgroundSyncFailures = new Map(); const flagSnapshots = new Map(); const idleWatchers = new Map(); +const lastBackgroundSyncAt = new Map(); function updateAccountStore(update) { const operation = accountStoreQueue.then(async () => { @@ -57,7 +59,12 @@ async function checkSnoozeReminders() { 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 }); + if (Number(item.dueAt) <= Date.now()) reminders.push({ + accountId: account.id, + email: account.email, + notificationsEnabled: account.notificationsEnabled !== false, + ...item + }); else remaining.push(item); } account.snoozedMessages = remaining; @@ -65,7 +72,7 @@ async function checkSnoozeReminders() { return reminders; }); for (const reminder of due) { - if (Notification.isSupported()) { + if (reminder.notificationsEnabled !== false && Notification.isSupported()) { new Notification({ title: 'Mail reminder', body: `${reminder.subject || 'A message'}${reminder.email ? ` · ${reminder.email}` : ''}` @@ -245,7 +252,37 @@ function normalizeAccount(input) { throw new Error('Enter a valid email, password, and both mail server names.'); } if (!displayName) throw new Error('Enter a display name for this mail account.'); - return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 }; + const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2); + if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) { + throw new Error('Choose a supported mailbox sync interval.'); + } + const inputRules = Array.isArray(input?.rules) ? input.rules : []; + if (inputRules.length > 50) throw new Error('You can set up to 50 mail rules per account.'); + const rules = inputRules.map((rule, index) => { + const senderContains = String(rule?.senderContains || '').trim().slice(0, 200); + const subjectContains = String(rule?.subjectContains || '').trim().slice(0, 200); + const action = String(rule?.action || ''); + const value = String(rule?.value || '').trim().slice(0, 200); + if ((!senderContains && !subjectContains) || !['archive', 'move', 'label', 'flag'].includes(action)) { + throw new Error(`Mail rule ${index + 1} needs a sender or subject condition and a valid action.`); + } + if ((action === 'move' || action === 'label') && !value) { + throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`); + } + if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value)) { + throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash.`); + } + return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value }; + }); + return { + email, password, displayName, imapHost, smtpHost, + signature: String(input?.signature || '').slice(0, 5000), + notificationsEnabled: input?.notificationsEnabled !== false, + syncIntervalMinutes, + rules, + imapPort: 143, + smtpPort: 587 + }; } function imapClient(account, options = {}) { @@ -316,7 +353,17 @@ async function readAccount(accountId = null) { } function publicAccount(account) { - return { id: account.id, email: account.email, displayName: account.displayName || '', imapHost: account.imapHost, smtpHost: account.smtpHost }; + return { + id: account.id, + email: account.email, + displayName: account.displayName || '', + imapHost: account.imapHost, + smtpHost: account.smtpHost, + signature: account.signature || '', + notificationsEnabled: account.notificationsEnabled !== false, + syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2, + rules: Array.isArray(account.rules) ? account.rules : [] + }; } async function saveAccount(account) { @@ -393,7 +440,9 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) { const messages = []; for (const item of fetched.reverse()) { if (!item.source || snoozed.has(Number(item.uid))) continue; - messages.push(await toUiMessage(item, folder)); + const message = await toUiMessage(item, folder); + message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || [])); + messages.push(message); } return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder }; } finally { @@ -451,8 +500,10 @@ async function fetchSnoozedMailbox(account, offset, limit) { uid: true, envelope: true, flags: true, internalDate: true, source: true }, { uid: true }); if (!item?.source) continue; - messages.push({ - ...await toUiMessage(item, 'Snoozed'), + const message = await toUiMessage(item, 'Snoozed'); + message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || [])); + messages.push({ + ...message, sourceFolder, snoozedUntil: Number(snooze.dueAt) }); @@ -499,6 +550,7 @@ async function syncAccountMailboxes(account) { const accountSnapshots = new Map(flagSnapshots.get(account.id) || []); let inboxNewCount = 0; const changedFolders = []; + const ruleActions = []; for (const listedMailbox of mailboxes) { const mailbox = await client.mailboxOpen(listedMailbox.path, { readOnly: true }); @@ -529,6 +581,17 @@ async function syncAccountMailboxes(account) { const added = uidCeiling > previousUid ? await client.fetchAll(`${previousUid + 1}:${uidCeiling}`, { uid: true, envelope: true, flags: true }, { uid: true }) : []; + if (label === 'Inbox' && account.rules?.length) { + for (const item of added) { + const rule = account.rules.find(candidate => { + const sender = (item.envelope?.from || []).map(address => `${address.name || ''} ${address.address || ''}`).join(' ').toLowerCase(); + const subject = String(item.envelope?.subject || '').toLowerCase(); + return (!candidate.senderContains || sender.includes(candidate.senderContains.toLowerCase())) && + (!candidate.subjectContains || subject.includes(candidate.subjectContains.toLowerCase())); + }); + if (rule) ruleActions.push({ uid: Number(item.uid), folder, rule }); + } + } let flagsChanged = false; if (mailbox.highestModseq && oldState.highestModseq) { @@ -556,6 +619,39 @@ async function syncAccountMailboxes(account) { if (added.length || flagsChanged) changedFolders.push(label); } + const ruleLabels = []; + for (const { uid, folder, rule } of ruleActions) { + const lock = await client.getMailboxLock(folder); + try { + if (rule.action === 'flag') { + await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true }); + } else if (rule.action === 'archive' || rule.action === 'move') { + const target = rule.action === 'archive' + ? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive') + : await folderPath(client, rule.value); + if (!target) throw new Error(`Rule destination mailbox "${rule.value}" was not found.`); + if (target !== folder) await client.messageMove(uid, target, { uid: true }); + changedFolders.push(rule.action === 'archive' ? 'Archive' : backgroundFolderLabel({ path: target })); + } else if (rule.action === 'label') { + ruleLabels.push({ key: `${folder}:${uid}`, label: rule.value }); + } + } catch (error) { + console.error(`Could not apply mail rule "${rule.id}" to message ${uid}:`, error); + } finally { + lock.release(); + } + } + if (ruleLabels.length) { + await updateAccountStore(store => { + const saved = store.accounts.find(item => item.id === account.id); + if (!saved) return; + saved.ruleLabels = saved.ruleLabels || {}; + for (const { key, label } of ruleLabels) { + saved.ruleLabels[key] = [...new Set([...(saved.ruleLabels[key] || []), label])]; + } + }); + } + const saved = await saveAccountSyncState(account.id, generation, states); if (!saved || backgroundSyncGenerations.get(account.id) !== generation) { return { newCount: 0, changedFolders: [] }; @@ -568,7 +664,7 @@ async function syncAccountMailboxes(account) { } function showNewMailNotification(account, count) { - if (!count || !Notification.isSupported()) return; + if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return; const focused = BrowserWindow.getAllWindows().some(window => window.isFocused()); if (focused) return; const notification = new Notification({ @@ -578,9 +674,14 @@ function showNewMailNotification(account, count) { notification.show(); } -async function syncAccountWithBackoff(account) { +async function syncAccountWithBackoff(account, periodicOnly = false) { + if (periodicOnly) { + const intervalMs = (Number(account.syncIntervalMinutes) || 2) * 60 * 1000; + if (Date.now() - (lastBackgroundSyncAt.get(account.id) || 0) < intervalMs) return; + } const failure = backgroundSyncFailures.get(account.id); if (failure && Date.now() < failure.retryAt) return; + lastBackgroundSyncAt.set(account.id, Date.now()); const generation = backgroundSyncGenerations.get(account.id) || 0; try { const result = await syncAccountMailboxes(account); @@ -593,26 +694,29 @@ async function syncAccountWithBackoff(account) { } } catch (error) { const attempts = (failure?.attempts || 0) + 1; - const retryDelay = Math.min(30 * 60 * 1000, backgroundSyncIntervalMs * (2 ** Math.min(attempts - 1, 4))); + const retryDelay = Math.min(30 * 60 * 1000, backgroundRetryIntervalMs * (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() { +async function runBackgroundSync(periodicOnly = false) { if (backgroundSyncInProgress) { - backgroundSyncRequested = true; + if (!periodicOnly) backgroundSyncRequested = true; return; } backgroundSyncInProgress = true; + let onlyDueAccounts = periodicOnly; 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)); + await Promise.all(store.accounts.slice(index, index + backgroundSyncConcurrency) + .map(account => syncAccountWithBackoff(account, onlyDueAccounts))); } + if (backgroundSyncRequested) onlyDueAccounts = false; } while (backgroundSyncRequested); } finally { backgroundSyncInProgress = false; @@ -669,7 +773,8 @@ ipcMain.handle('mail:update-account', async (_event, accountId, input) => { ? { ...account, syncState: endpointChanged ? undefined : current.syncState, - snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []) + snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []), + ruleLabels: endpointChanged ? {} : (current.ruleLabels || {}) } : item); return store.accounts.find(item => item.id === existing.id); @@ -830,12 +935,14 @@ ipcMain.handle('mail:send', async (_event, message) => { const transport = smtpTransport(account); const sentMessageId = `<${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); const messageOptions = { from: { name: fromName, address: account.email }, to, cc: String(message.cc || '').trim() || undefined, subject: String(message.subject || '(no subject)').slice(0, 998), - text: String(message.text || '').slice(0, 500000), + text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body, messageId: sentMessageId }; try { @@ -1069,7 +1176,9 @@ function createWindow() { app.whenReady().then(() => { app.setAppUserModelId('studio.daybreak.mail'); createWindow(); - const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs); + const syncTimer = setInterval(() => { + void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error)); + }, backgroundSyncIntervalMs); syncTimer.unref(); const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs); snoozeTimer.unref(); diff --git a/mail-ui.js b/mail-ui.js index ed6d109..956aefc 100644 --- a/mail-ui.js +++ b/mail-ui.js @@ -16,6 +16,7 @@ function updateAccountCard(account) { card.querySelector('.account-info strong').textContent = displayName; card.querySelector('.account-info span').textContent = email; card.title = `${displayName} <${email}>`; + if (typeof renderLabels === 'function') renderLabels(); card.querySelector('.online-dot').style.background = '#70ad7b'; const profileButton = $('.top-avatar'); if (profileButton) { @@ -28,11 +29,46 @@ function openMailAccount(existingAccount = null) { const root = $('#modal-root'); const editing = Boolean(existingAccount); const displayName = existingAccount?.displayName || profileSettings.name || ''; - root.innerHTML = ``; + const ruleMarkup = (existingAccount?.rules || []).map(rule => ` +
+ + + + ${rule.action==='move' + ? `` + : ``} + +
`).join(''); + root.innerHTML = ``; const close = () => { root.innerHTML = ''; }; $$('.modal-close').forEach(button => button.onclick = close); $('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); }); $('#disconnect-mail').onclick = close; + const addRuleRow = rule => { + const row = document.createElement('div'); + row.className = 'mail-rule-row'; + row.innerHTML = ``; + row.querySelector('.mail-rule-action').value = rule?.action || 'archive'; + $('#mail-rule-list').append(row); + }; + $('#add-mail-rule').onclick = () => addRuleRow(); + $('#mail-rule-list').onclick = event => { + if (event.target.closest('.remove-mail-rule')) event.target.closest('.mail-rule-row').remove(); + }; + $('#mail-rule-list').onchange = event => { + if (!event.target.matches('.mail-rule-action')) return; + const row = event.target.closest('.mail-rule-row'); + const value = row.querySelector('.mail-rule-value'); + if (event.target.value === 'move') { + const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? value.value : 'Inbox'; + value.outerHTML = ``; + } else if (value.tagName === 'SELECT') { + value.outerHTML = ``; + } + row.querySelector('.mail-rule-value').disabled = event.target.value === 'flag'; + }; $('#connect-mail').onclick = async () => { const button = $('#connect-mail'); const status = $('#mail-account-status'); @@ -49,7 +85,16 @@ function openMailAccount(existingAccount = null) { password, displayName: name, imapHost: $('#mail-account-imap').value, - smtpHost: $('#mail-account-smtp').value + smtpHost: $('#mail-account-smtp').value, + signature: $('#mail-account-signature').value, + notificationsEnabled: $('#mail-account-notifications').checked, + syncIntervalMinutes: Number($('#mail-account-sync-interval').value), + rules: [...$('#mail-rule-list').querySelectorAll('.mail-rule-row')].map(row => ({ + senderContains: row.querySelector('.mail-rule-sender').value, + subjectContains: row.querySelector('.mail-rule-subject').value, + action: row.querySelector('.mail-rule-action').value, + value: row.querySelector('.mail-rule-value').value + })) }; const account = editing ? await window.daybreakMail.updateAccount(existingAccount.id, details) diff --git a/package-lock.json b/package-lock.json index 1a85a1f..d03c880 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.1.17", + "version": "0.1.19", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.1.17", + "version": "0.1.19", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index 6b7fb0c..d10089e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.1.17", + "version": "0.1.19", "private": true, "description": "Eternity Project mail client", "author": "Eternity Project", diff --git a/productivity.js b/productivity.js index 5abe0ac..a8eb9f0 100644 --- a/productivity.js +++ b/productivity.js @@ -10,6 +10,7 @@ let savedContacts = productRead(productKeys.contacts, []).filter(contact => !gen 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'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); } function openAccountSettings() { const root=$('#modal-root'); @@ -36,12 +37,13 @@ function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), da function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`
${d.getDate()}${items.slice(0,3).map(e=>`
${esc(e.time?`${e.time} `:'')}${esc(e.title)}
`).join('')}${items.length>3?`+${items.length-3} more`:''}
`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`

YOUR TIME, WITH ROOM TO BREATHE

${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}

${savedEvents.length} saved events

${days.map(d=>`${d}`).join('')}
${cells}

Coming up

${upcoming.length?upcoming.map(e=>``).join(''):'

No upcoming events yet.

'}
`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}} function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=``;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()} function renderContacts(){const cards=savedContacts.map((c,i)=>`
${esc(c.initials)}
${esc(c.name)}${esc(c.email)}${esc(c.note)}
`).join('');$('#contacts-view').innerHTML=`

THE PEOPLE WHO MAKE LIFE FULLER

Your people

${savedContacts.length} contacts, all in one place.

${cards||'

No contacts yet. Add someone to get started.

'}
`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}} -function renderLabels(){const box=$('#custom-labels');if(!box)return;box.innerHTML=customLabels.map(label=>``).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})} +function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} +function renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>``).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})} function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')} function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true})}return Promise.resolve()} async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}} document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';}); function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()} const baseMessageRenderer=renderList; -renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='
✎

No saved drafts

Compose a message to get started.

';$('#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='
⌕

No messages here

Try another folder or label.

';return}baseMessageRenderer()}; +renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='
✎

No saved drafts

Compose a message to get started.

';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels,...accountRuleLabels()].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?Boolean(m.snoozedUntil):(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='
⌕

No messages here

Try another folder or label.

';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); diff --git a/styles.css b/styles.css index ef71f99..0e14c14 100644 --- a/styles.css +++ b/styles.css @@ -114,3 +114,7 @@ body.ep-daylight .compose-line input::placeholder,body.ep-daylight .compose-body body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b} body.ep-daylight .toast{background:#11212b;color:#f1f1e9} body.ep-daylight .row-check:checked{accent-color:#526a2c} +.compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-fields{min-height:0;flex:1 1 auto;overflow-y:auto} +.snooze-options .outline-button{width:100%;text-align:left} +.mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap} +@media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}} diff --git a/www/mail-ui.js b/www/mail-ui.js index ed6d109..956aefc 100644 --- a/www/mail-ui.js +++ b/www/mail-ui.js @@ -16,6 +16,7 @@ function updateAccountCard(account) { card.querySelector('.account-info strong').textContent = displayName; card.querySelector('.account-info span').textContent = email; card.title = `${displayName} <${email}>`; + if (typeof renderLabels === 'function') renderLabels(); card.querySelector('.online-dot').style.background = '#70ad7b'; const profileButton = $('.top-avatar'); if (profileButton) { @@ -28,11 +29,46 @@ function openMailAccount(existingAccount = null) { const root = $('#modal-root'); const editing = Boolean(existingAccount); const displayName = existingAccount?.displayName || profileSettings.name || ''; - root.innerHTML = ``; + const ruleMarkup = (existingAccount?.rules || []).map(rule => ` +
+ + + + ${rule.action==='move' + ? `` + : ``} + +
`).join(''); + root.innerHTML = ``; const close = () => { root.innerHTML = ''; }; $$('.modal-close').forEach(button => button.onclick = close); $('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); }); $('#disconnect-mail').onclick = close; + const addRuleRow = rule => { + const row = document.createElement('div'); + row.className = 'mail-rule-row'; + row.innerHTML = ``; + row.querySelector('.mail-rule-action').value = rule?.action || 'archive'; + $('#mail-rule-list').append(row); + }; + $('#add-mail-rule').onclick = () => addRuleRow(); + $('#mail-rule-list').onclick = event => { + if (event.target.closest('.remove-mail-rule')) event.target.closest('.mail-rule-row').remove(); + }; + $('#mail-rule-list').onchange = event => { + if (!event.target.matches('.mail-rule-action')) return; + const row = event.target.closest('.mail-rule-row'); + const value = row.querySelector('.mail-rule-value'); + if (event.target.value === 'move') { + const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? value.value : 'Inbox'; + value.outerHTML = ``; + } else if (value.tagName === 'SELECT') { + value.outerHTML = ``; + } + row.querySelector('.mail-rule-value').disabled = event.target.value === 'flag'; + }; $('#connect-mail').onclick = async () => { const button = $('#connect-mail'); const status = $('#mail-account-status'); @@ -49,7 +85,16 @@ function openMailAccount(existingAccount = null) { password, displayName: name, imapHost: $('#mail-account-imap').value, - smtpHost: $('#mail-account-smtp').value + smtpHost: $('#mail-account-smtp').value, + signature: $('#mail-account-signature').value, + notificationsEnabled: $('#mail-account-notifications').checked, + syncIntervalMinutes: Number($('#mail-account-sync-interval').value), + rules: [...$('#mail-rule-list').querySelectorAll('.mail-rule-row')].map(row => ({ + senderContains: row.querySelector('.mail-rule-sender').value, + subjectContains: row.querySelector('.mail-rule-subject').value, + action: row.querySelector('.mail-rule-action').value, + value: row.querySelector('.mail-rule-value').value + })) }; const account = editing ? await window.daybreakMail.updateAccount(existingAccount.id, details) diff --git a/www/productivity.js b/www/productivity.js index 5abe0ac..a8eb9f0 100644 --- a/www/productivity.js +++ b/www/productivity.js @@ -10,6 +10,7 @@ let savedContacts = productRead(productKeys.contacts, []).filter(contact => !gen 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'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); } function openAccountSettings() { const root=$('#modal-root'); @@ -36,12 +37,13 @@ function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), da function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`
${d.getDate()}${items.slice(0,3).map(e=>`
${esc(e.time?`${e.time} `:'')}${esc(e.title)}
`).join('')}${items.length>3?`+${items.length-3} more`:''}
`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`

YOUR TIME, WITH ROOM TO BREATHE

${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}

${savedEvents.length} saved events

${days.map(d=>`${d}`).join('')}
${cells}

Coming up

${upcoming.length?upcoming.map(e=>``).join(''):'

No upcoming events yet.

'}
`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}} function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=``;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()} function renderContacts(){const cards=savedContacts.map((c,i)=>`
${esc(c.initials)}
${esc(c.name)}${esc(c.email)}${esc(c.note)}
`).join('');$('#contacts-view').innerHTML=`

THE PEOPLE WHO MAKE LIFE FULLER

Your people

${savedContacts.length} contacts, all in one place.

${cards||'

No contacts yet. Add someone to get started.

'}
`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}} -function renderLabels(){const box=$('#custom-labels');if(!box)return;box.innerHTML=customLabels.map(label=>``).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})} +function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} +function renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>``).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})} function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')} function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true})}return Promise.resolve()} async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}} document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';}); function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()} const baseMessageRenderer=renderList; -renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='
✎

No saved drafts

Compose a message to get started.

';$('#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='
⌕

No messages here

Try another folder or label.

';return}baseMessageRenderer()}; +renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='
✎

No saved drafts

Compose a message to get started.

';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels,...accountRuleLabels()].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?Boolean(m.snoozedUntil):(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='
⌕

No messages here

Try another folder or label.

';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); diff --git a/www/styles.css b/www/styles.css index ef71f99..0e14c14 100644 --- a/www/styles.css +++ b/www/styles.css @@ -114,3 +114,7 @@ body.ep-daylight .compose-line input::placeholder,body.ep-daylight .compose-body body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b} body.ep-daylight .toast{background:#11212b;color:#f1f1e9} body.ep-daylight .row-check:checked{accent-color:#526a2c} +.compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-fields{min-height:0;flex:1 1 auto;overflow-y:auto} +.snooze-options .outline-button{width:100%;text-align:left} +.mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap} +@media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}}