Add per-account mail rules and settings
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user