Add per-account mail rules and settings

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-10-07 01:24:01 +03:00
co-authored by Copilot
parent a1b8bca066
commit 9b3a890b1d
15 changed files with 456 additions and 92 deletions
@@ -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()
@@ -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<Long>) {
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()
@@ -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 {
@@ -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"))