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:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user