Add advanced search and offline mail support

Bump version to 0.1.20

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-10-07 01:41:07 +03:00
co-authored by Copilot
parent 9b3a890b1d
commit cae6825f2c
20 changed files with 1034 additions and 44 deletions
@@ -7,6 +7,9 @@ import android.util.Base64
import org.json.JSONArray
import org.json.JSONObject
import java.security.KeyStore
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
@@ -205,6 +208,215 @@ internal object AndroidAccountVault {
}
}
@Synchronized
fun cacheMessages(id: String, folder: String, messages: JSONArray) {
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 cache = account.optJSONObject("mailCache") ?: JSONObject()
val previous = cache.optJSONArray(folder) ?: JSONArray()
val merged = LinkedHashMap<String, JSONObject>()
for (itemIndex in 0 until previous.length()) {
val item = previous.optJSONObject(itemIndex) ?: continue
merged[item.optString("uid", item.optString("id"))] = item
}
for (itemIndex in 0 until messages.length()) {
val item = messages.optJSONObject(itemIndex) ?: continue
merged[item.optString("uid", item.optString("id"))] = item
}
cache.put(folder, JSONArray().apply {
merged.values.toList().takeLast(30).forEach { put(it) }
})
account.put("mailCache", cache)
write(store)
return
}
}
fun cachedFolder(id: String, folder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject? {
val account = account(id) ?: return null
val cached = account.optJSONObject("mailCache")?.optJSONArray(folder) ?: return null
val matched = (0 until cached.length()).mapNotNull { cached.optJSONObject(it) }
.filter { matchesFilters(it, filters) }
.sortedByDescending { it.optLong("timestamp") }
val start = offset.coerceAtLeast(0)
val page = matched.drop(start).take(20)
if (page.isEmpty() && matched.isEmpty()) return null
return JSONObject()
.put("messages", JSONArray().apply { page.forEach(::put) })
.put("total", matched.size)
.put("start", if (matched.isEmpty()) 0 else start + 1)
.put("end", start + page.size)
.put("folder", folder)
.put("offline", true)
}
private fun matchesFilters(message: JSONObject, filters: JSONObject): Boolean {
val query = filters.optString("query").trim().lowercase(Locale.ROOT)
val senderFilter = filters.optString("sender").trim().lowercase(Locale.ROOT)
val subjectFilter = filters.optString("subject").trim().lowercase(Locale.ROOT)
val sender = "${message.optString("sender")} ${message.optString("email")}".lowercase(Locale.ROOT)
val subject = message.optString("subject").lowercase(Locale.ROOT)
val attachments = message.optJSONArray("attachments")
val haystack = "$sender $subject ${message.optString("snippet")} ${message.optJSONArray("body")?.toString().orEmpty()}".lowercase(Locale.ROOT)
val timestamp = message.optLong("timestamp")
val after = dateBoundary(filters.optString("after"), false)
val before = dateBoundary(filters.optString("before"), true)
return (query.isBlank() || query.split(Regex("\\s+")).all(haystack::contains)) &&
(senderFilter.isBlank() || sender.contains(senderFilter)) &&
(subjectFilter.isBlank() || subject.contains(subjectFilter)) &&
(after == null || timestamp >= after) && (before == null || timestamp <= before) &&
(!filters.optBoolean("hasAttachments") || (attachments?.length() ?: 0) > 0)
}
private fun dateBoundary(value: String, endOfDay: Boolean): Long? {
if (value.isBlank()) return null
val parsed = runCatching { SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(value) }.getOrNull() ?: return null
val calendar = Calendar.getInstance().apply { time = parsed }
if (endOfDay) {
calendar.add(Calendar.DAY_OF_MONTH, 1)
return calendar.timeInMillis - 1
}
return calendar.timeInMillis
}
@Synchronized
fun saveDraft(id: String, draft: JSONObject) {
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 drafts = account.optJSONArray("drafts") ?: JSONArray()
val updated = JSONArray().put(JSONObject(draft.toString()))
for (draftIndex in 0 until drafts.length()) {
val current = drafts.optJSONObject(draftIndex) ?: continue
if (current.optString("id") != draft.optString("id")) updated.put(current)
}
account.put("drafts", updated)
write(store)
return
}
}
@Synchronized
fun deleteDraft(id: String, draftId: 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 drafts = account.optJSONArray("drafts") ?: JSONArray()
account.put("drafts", JSONArray().apply {
for (draftIndex in 0 until drafts.length()) {
val draft = drafts.optJSONObject(draftIndex) ?: continue
if (draft.optString("id") != draftId) put(draft)
}
})
write(store)
return
}
}
@Synchronized
fun enqueueMailOperation(id: String, operation: JSONObject) {
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 previous = account.optJSONArray("mailOutbox") ?: JSONArray()
val data = operation.optJSONObject("data")
val queue = JSONArray()
for (index in 0 until previous.length()) {
val existing = previous.optJSONObject(index) ?: continue
val existingData = existing.optJSONObject("data")
if (existingData == null) {
queue.put(existing)
continue
}
val duplicate = operation.optString("type") == "action" && existing.optString("type") == "action" &&
existingData.optLong("uid") == data?.optLong("uid") &&
existingData.optString("folder") == data?.optString("folder") &&
existingData.optString("action") == data?.optString("action")
if (!duplicate) queue.put(existing)
}
queue.put(JSONObject(operation.toString()))
account.put("mailOutbox", queue)
if (operation.optString("type") == "action" && data != null) applyQueuedActionToCache(account, data)
write(store)
return
}
}
private fun applyQueuedActionToCache(account: JSONObject, input: JSONObject) {
val cache = account.optJSONObject("mailCache") ?: return
val sourceName = input.optString("folder", "Inbox")
val source = cache.optJSONArray(sourceName) ?: return
val uid = input.optLong("uid")
val action = input.optString("action")
val updatedSource = JSONArray()
var moved: JSONObject? = null
for (index in 0 until source.length()) {
val message = source.optJSONObject(index) ?: continue
if (message.optLong("uid", message.optLong("id")) != uid) {
updatedSource.put(message)
continue
}
when (action) {
"star" -> {
message.put("star", input.optBoolean("enabled"))
updatedSource.put(message)
}
"unread" -> {
message.put("unread", input.optBoolean("enabled"))
updatedSource.put(message)
}
"archive", "delete", "inbox" -> moved = message
else -> updatedSource.put(message)
}
}
cache.put(sourceName, updatedSource)
val destinationName = when (action) {
"archive" -> "Archive"
"delete" -> "Trash"
"inbox" -> "Inbox"
else -> null
}
if (moved == null || destinationName == null) return
moved!!.put("sourceFolder", destinationName)
.put("archived", destinationName == "Archive")
.put("deleted", destinationName == "Trash")
val destination = cache.optJSONArray(destinationName) ?: JSONArray()
val merged = (0 until destination.length()).mapNotNull { destination.optJSONObject(it) }
.filter { it.optLong("uid", it.optLong("id")) != uid } + moved!!
cache.put(destinationName, JSONArray().apply { merged.takeLast(30).forEach { put(it) } })
}
@Synchronized
fun pendingMailOperations(id: String): JSONArray = account(id)?.optJSONArray("mailOutbox") ?: JSONArray()
@Synchronized
fun removeMailOperation(id: String, operationId: 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 queue = account.optJSONArray("mailOutbox") ?: JSONArray()
account.put("mailOutbox", JSONArray().apply {
for (queueIndex in 0 until queue.length()) {
val operation = queue.optJSONObject(queueIndex) ?: continue
if (operation.optString("id") != operationId) put(operation)
}
})
write(store)
return
}
}
fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray {
val result = JSONArray()
for (index in 0 until accounts.length()) {
@@ -12,6 +12,8 @@ import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.Properties
@@ -57,15 +59,46 @@ internal object AndroidMailService {
JSONObject().put("mailbox", "INBOX").put("messages", count)
}
fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject {
fun sync(account: JSONObject, requestedFolder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject {
if (requestedFolder == "Snoozed") return syncSnoozed(account, offset)
return withStore(account) { _, store ->
return try {
withStore(account) { _, store ->
val folder = resolveFolder(store, requestedFolder)
if (folder == null) return@withStore JSONObject()
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
folder.open(Folder.READ_ONLY)
try {
val total = folder.messageCount
val hasSearchFilters = listOf("query", "sender", "subject", "after", "before")
.any { filters.optString(it).isNotBlank() } || filters.optBoolean("hasAttachments")
if (hasSearchFilters) {
val all = JSONArray()
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
if (total > 0) {
val start = (total - 4999).coerceAtLeast(1)
for (message in folder.getMessages(start, total)) {
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
if (snoozed.length() > 0 && (0 until snoozed.length()).any { index ->
val item = snoozed.optJSONObject(index) ?: return@any false
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
item.optLong("dueAt") > System.currentTimeMillis()
}) continue
all.put(messageJson(folder, message, requestedFolder, account))
}
}
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, all)
val matches = (0 until all.length()).mapNotNull { all.optJSONObject(it) }
.filter { matchesFilters(it, filters) }
.sortedByDescending { it.optLong("timestamp") }
val start = offset.coerceAtLeast(0)
val page = matches.drop(start).take(20)
return@withStore JSONObject()
.put("messages", JSONArray().apply { page.forEach(::put) })
.put("total", matches.size)
.put("start", if (matches.isEmpty()) 0 else start + 1)
.put("end", start + page.size)
.put("folder", requestedFolder)
}
val end = (total - offset.coerceAtLeast(0)).coerceAtLeast(0)
if (end == 0) {
return@withStore JSONObject().put("messages", JSONArray()).put("total", total)
@@ -75,6 +108,7 @@ internal object AndroidMailService {
val result = JSONArray()
val batch = folder.getMessages(first, end).reversed()
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
val cached = JSONArray()
for (message in batch) {
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
val isSnoozed = (0 until snoozed.length()).any { index ->
@@ -83,16 +117,67 @@ internal object AndroidMailService {
item.optLong("dueAt") > System.currentTimeMillis()
}
if (isSnoozed) continue
result.put(messageJson(folder, message, requestedFolder, account))
val value = messageJson(folder, message, requestedFolder, account)
result.put(value)
cached.put(value)
}
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached)
JSONObject().put("messages", result).put("total", total)
.put("start", first).put("end", end).put("folder", requestedFolder)
} finally {
folder.close(false)
}
}
} catch (error: Exception) {
if (!isConnectivityFailure(error)) throw error
AndroidAccountVault.cachedFolder(account.optString("id"), requestedFolder, offset, filters)
?: throw error
}
}
private fun isConnectivityFailure(error: Throwable): Boolean {
var current: Throwable? = error
while (current != null) {
if (current is java.net.UnknownHostException ||
current is java.net.ConnectException ||
current is java.net.SocketTimeoutException ||
current is javax.net.ssl.SSLException) return true
val message = current.message.orEmpty().lowercase(Locale.ROOT)
if (listOf("network is unreachable", "connection timed out", "connection refused", "unable to resolve host", "socket closed").any(message::contains)) return true
current = current.cause
}
return false
}
private fun matchesFilters(message: JSONObject, filters: JSONObject): Boolean {
val query = filters.optString("query").trim().lowercase(Locale.ROOT)
val senderFilter = filters.optString("sender").trim().lowercase(Locale.ROOT)
val subjectFilter = filters.optString("subject").trim().lowercase(Locale.ROOT)
val sender = "${message.optString("sender")} ${message.optString("email")}".lowercase(Locale.ROOT)
val subject = message.optString("subject").lowercase(Locale.ROOT)
val haystack = "$sender $subject ${message.optString("snippet")} ${message.optJSONArray("body")?.toString().orEmpty()}".lowercase(Locale.ROOT)
val timestamp = message.optLong("timestamp")
val after = dateBoundary(filters.optString("after"), false)
val before = dateBoundary(filters.optString("before"), true)
val attachments = message.optJSONArray("attachments")
return (query.isBlank() || query.split(Regex("\\s+")).all(haystack::contains)) &&
(senderFilter.isBlank() || sender.contains(senderFilter)) &&
(subjectFilter.isBlank() || subject.contains(subjectFilter)) &&
(after == null || timestamp >= after) && (before == null || timestamp <= before) &&
(!filters.optBoolean("hasAttachments") || (attachments?.length() ?: 0) > 0)
}
private fun dateBoundary(value: String, endOfDay: Boolean): Long? {
if (value.isBlank()) return null
val parsed = runCatching { SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(value) }.getOrNull() ?: return null
val calendar = Calendar.getInstance().apply { time = parsed }
if (endOfDay) {
calendar.add(Calendar.DAY_OF_MONTH, 1)
return calendar.timeInMillis - 1
}
return calendar.timeInMillis
}
private fun syncSnoozed(account: JSONObject, offset: Int): JSONObject =
withStore(account) { _, store ->
val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray()
@@ -193,6 +278,7 @@ internal object AndroidMailService {
)
message.sentDate = Date()
message.saveChanges()
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
val transport = session.getTransport("smtp")
try {
@@ -221,6 +307,26 @@ internal object AndroidMailService {
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
}
fun flushOutbox(account: JSONObject) {
val accountId = account.optString("id")
val queued = AndroidAccountVault.pendingMailOperations(accountId)
for (index in 0 until queued.length()) {
val operation = queued.optJSONObject(index) ?: continue
try {
val data = operation.optJSONObject("data") ?: continue
when (operation.optString("type")) {
"send" -> send(account, data)
"action" -> updateMessage(account, data)
else -> throw IllegalStateException("Unsupported queued mail operation.")
}
AndroidAccountVault.removeMailOperation(accountId, operation.optString("id"))
} catch (error: Exception) {
android.util.Log.w("EpMailOutbox", "Mail operation remains queued for a later retry.", error)
break
}
}
}
fun saveAttachment(context: Context, account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store ->
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
@@ -239,7 +345,9 @@ internal object AndroidMailService {
}
}
fun checkForNewMail(account: JSONObject): Int = withStore(account) { _, store ->
fun checkForNewMail(account: JSONObject): Int {
flushOutbox(account)
return withStore(account) { _, store ->
val folder = store.getFolder("INBOX")
folder.open(Folder.READ_ONLY)
try {
@@ -260,6 +368,7 @@ internal object AndroidMailService {
} finally {
folder.close(false)
}
}
}
fun applyRules(account: JSONObject, uids: List<Long>) {
@@ -420,7 +529,7 @@ internal object AndroidMailService {
val body = ArrayList<String>()
val attachments = JSONArray()
collectParts(message, body, attachments)
val bodyText = body.joinToString("\n\n").trim()
val bodyText = body.joinToString("\n\n").trim().take(8000)
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date()
val tags = JSONArray().put(requestedFolder)
@@ -446,12 +555,14 @@ internal object AndroidMailService {
.put("snippet", snippet)
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
.put("timestamp", date.time)
.put("unread", !flags.contains(Flags.Flag.SEEN))
.put("star", flags.contains(Flags.Flag.FLAGGED))
.put("tags", tags)
.put("sent", requestedFolder == "Sent")
.put("archived", requestedFolder == "Archive")
.put("deleted", requestedFolder == "Trash")
.put("sourceFolder", labelFolder)
.put("body", JSONArray().apply {
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
@@ -140,9 +140,13 @@ class EpMailPlugin : Plugin() {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before syncing.")
val requested = call.getString("folder") ?: "Inbox"
val folder = if (requested in setOf("Inbox", "Sent", "Archive", "Trash", "Starred", "Snoozed")) requested else "Inbox"
val filters = call.getObject("filters") ?: JSObject()
val filterFolder = filters.getString("folder")
val selected = filterFolder?.takeIf { it in setOf("Inbox", "Sent", "Archive", "Trash", "Starred") } ?: requested
val folder = if (selected in setOf("Inbox", "Sent", "Archive", "Trash", "Starred", "Snoozed")) selected else "Inbox"
val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0)
call.resolve(AndroidMailService.sync(account, folder, offset).toJSObject())
AndroidMailService.flushOutbox(account)
call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not sync the mailbox.")
}
@@ -155,7 +159,14 @@ class EpMailPlugin : Plugin() {
?: throw IllegalStateException("Add a mail account before changing messages.")
call.resolve(AndroidMailService.updateMessage(account, call.data).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not update the message.")
val account = AndroidAccountVault.account()
if (account != null && isConnectivityFailure(error)) {
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
.put("id", UUID.randomUUID().toString())
.put("type", "action")
.put("data", JSONObject(call.data.toString())))
call.resolve(JSObject().put("ok", true).put("queued", true))
} else call.reject(error.message ?: "Could not update the message.")
}
}
@@ -215,15 +226,83 @@ class EpMailPlugin : Plugin() {
@PluginMethod
fun send(call: PluginCall) {
val input = JSONObject(call.data.toString()).apply {
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
}
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before sending.")
call.resolve(AndroidMailService.send(account, call.data).toJSObject())
call.resolve(AndroidMailService.send(account, input).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not send the message.")
val account = AndroidAccountVault.account()
if (account != null && isConnectivityFailure(error)) {
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
.put("id", UUID.randomUUID().toString())
.put("type", "send")
.put("data", input))
call.resolve(JSObject().put("ok", true).put("queued", true))
} else call.reject(error.message ?: "Could not send the message.")
}
}
@PluginMethod
fun listDrafts(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before opening drafts.")
call.resolve(JSObject().put("drafts", account.optJSONArray("drafts") ?: JSONArray()).put("offline", true))
} catch (error: Exception) {
call.reject(error.message ?: "Could not open drafts.")
}
}
@PluginMethod
fun saveDraft(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before saving drafts.")
val input = JSONObject(call.data.toString())
val draft = JSONObject()
.put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() })
.put("to", input.optString("to").take(4000))
.put("cc", input.optString("cc").take(4000))
.put("subject", input.optString("subject").take(998))
.put("text", input.optString("text").take(500000))
.put("updatedAt", System.currentTimeMillis())
AndroidAccountVault.saveDraft(account.optString("id"), draft)
call.resolve(draft.toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the draft.")
}
}
@PluginMethod
fun deleteDraft(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before deleting drafts.")
val id = call.getString("id") ?: throw IllegalArgumentException("Choose a draft.")
AndroidAccountVault.deleteDraft(account.optString("id"), id)
call.resolve(JSObject().put("ok", true))
} catch (error: Exception) {
call.reject(error.message ?: "Could not delete the draft.")
}
}
private fun isConnectivityFailure(error: Throwable): Boolean {
var current: Throwable? = error
while (current != null) {
if (current is java.net.UnknownHostException ||
current is java.net.ConnectException ||
current is java.net.SocketTimeoutException ||
current is javax.net.ssl.SSLException) return true
val message = current.message.orEmpty().lowercase(Locale.ROOT)
if (listOf("network is unreachable", "connection timed out", "connection refused", "unable to resolve host", "socket closed").any(message::contains)) return true
current = current.cause
}
return false
}
@PluginMethod
fun davList(call: PluginCall) {
try {