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 61d5b81d7e
20 changed files with 1034 additions and 44 deletions
+2 -2
View File
@@ -4,13 +4,13 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E
## Desktop app ## 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. 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 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, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. 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. 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 ## 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. 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: 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. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. 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 ```sh
npm install npm install
+2 -2
View File
@@ -12,8 +12,8 @@
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return. - [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
- [ ] Add Undo Send and scheduled sending. - [ ] Add Undo Send and scheduled sending.
- [ ] Improve mail search with sender, subject, date, folder, and attachment filters. - [x] Improve mail search with sender, subject, date, folder, and attachment filters.
- [ ] Add offline reading and drafts, with queued actions when connectivity returns. - [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
- [ ] Group related messages into conversations, with controls to expand or collapse threads. - [ ] 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 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 configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
@@ -7,6 +7,9 @@ import android.util.Base64
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.security.KeyStore import java.security.KeyStore
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import javax.crypto.Cipher import javax.crypto.Cipher
import javax.crypto.KeyGenerator import javax.crypto.KeyGenerator
import javax.crypto.SecretKey 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 { fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray {
val result = JSONArray() val result = JSONArray()
for (index in 0 until accounts.length()) { for (index in 0 until accounts.length()) {
@@ -12,6 +12,8 @@ import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
import java.text.DateFormat import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date import java.util.Date
import java.util.Locale import java.util.Locale
import java.util.Properties import java.util.Properties
@@ -57,15 +59,46 @@ internal object AndroidMailService {
JSONObject().put("mailbox", "INBOX").put("messages", count) 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) if (requestedFolder == "Snoozed") return syncSnoozed(account, offset)
return withStore(account) { _, store -> return try {
withStore(account) { _, store ->
val folder = resolveFolder(store, requestedFolder) val folder = resolveFolder(store, requestedFolder)
if (folder == null) return@withStore JSONObject() if (folder == null) return@withStore JSONObject()
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder) .put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
folder.open(Folder.READ_ONLY) folder.open(Folder.READ_ONLY)
try { try {
val total = folder.messageCount 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) val end = (total - offset.coerceAtLeast(0)).coerceAtLeast(0)
if (end == 0) { if (end == 0) {
return@withStore JSONObject().put("messages", JSONArray()).put("total", total) return@withStore JSONObject().put("messages", JSONArray()).put("total", total)
@@ -75,6 +108,7 @@ internal object AndroidMailService {
val result = JSONArray() val result = JSONArray()
val batch = folder.getMessages(first, end).reversed() val batch = folder.getMessages(first, end).reversed()
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray() val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
val cached = JSONArray()
for (message in batch) { for (message in batch) {
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
val isSnoozed = (0 until snoozed.length()).any { index -> val isSnoozed = (0 until snoozed.length()).any { index ->
@@ -83,16 +117,67 @@ internal object AndroidMailService {
item.optLong("dueAt") > System.currentTimeMillis() item.optLong("dueAt") > System.currentTimeMillis()
} }
if (isSnoozed) continue 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) JSONObject().put("messages", result).put("total", total)
.put("start", first).put("end", end).put("folder", requestedFolder) .put("start", first).put("end", end).put("folder", requestedFolder)
} finally { } finally {
folder.close(false) 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 = private fun syncSnoozed(account: JSONObject, offset: Int): JSONObject =
withStore(account) { _, store -> withStore(account) { _, store ->
val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray() val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray()
@@ -193,6 +278,7 @@ internal object AndroidMailService {
) )
message.sentDate = Date() message.sentDate = Date()
message.saveChanges() message.saveChanges()
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
val transport = session.getTransport("smtp") val transport = session.getTransport("smtp")
try { try {
@@ -221,6 +307,26 @@ internal object AndroidMailService {
return JSONObject().put("ok", true).put("savedToSent", savedToSent) 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 = fun saveAttachment(context: Context, account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store -> withStore(account) { _, store ->
val folder = resolveFolder(store, input.optString("folder", "Inbox")) 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") val folder = store.getFolder("INBOX")
folder.open(Folder.READ_ONLY) folder.open(Folder.READ_ONLY)
try { try {
@@ -260,6 +368,7 @@ internal object AndroidMailService {
} finally { } finally {
folder.close(false) folder.close(false)
} }
}
} }
fun applyRules(account: JSONObject, uids: List<Long>) { fun applyRules(account: JSONObject, uids: List<Long>) {
@@ -420,7 +529,7 @@ internal object AndroidMailService {
val body = ArrayList<String>() val body = ArrayList<String>()
val attachments = JSONArray() val attachments = JSONArray()
collectParts(message, body, attachments) 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 snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date() val date = message.receivedDate ?: message.sentDate ?: Date()
val tags = JSONArray().put(requestedFolder) val tags = JSONArray().put(requestedFolder)
@@ -446,12 +555,14 @@ internal object AndroidMailService {
.put("snippet", snippet) .put("snippet", snippet)
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date)) .put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, 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("unread", !flags.contains(Flags.Flag.SEEN))
.put("star", flags.contains(Flags.Flag.FLAGGED)) .put("star", flags.contains(Flags.Flag.FLAGGED))
.put("tags", tags) .put("tags", tags)
.put("sent", requestedFolder == "Sent") .put("sent", requestedFolder == "Sent")
.put("archived", requestedFolder == "Archive") .put("archived", requestedFolder == "Archive")
.put("deleted", requestedFolder == "Trash") .put("deleted", requestedFolder == "Trash")
.put("sourceFolder", labelFolder)
.put("body", JSONArray().apply { .put("body", JSONArray().apply {
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40) 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) 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() val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before syncing.") ?: throw IllegalStateException("Add a mail account before syncing.")
val requested = call.getString("folder") ?: "Inbox" 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) 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) { } catch (error: Exception) {
call.reject(error.message ?: "Could not sync the mailbox.") 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.") ?: throw IllegalStateException("Add a mail account before changing messages.")
call.resolve(AndroidMailService.updateMessage(account, call.data).toJSObject()) call.resolve(AndroidMailService.updateMessage(account, call.data).toJSObject())
} catch (error: Exception) { } 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 @PluginMethod
fun send(call: PluginCall) { fun send(call: PluginCall) {
val input = JSONObject(call.data.toString()).apply {
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
}
try { try {
val account = AndroidAccountVault.account() val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before sending.") ?: 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) { } 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 @PluginMethod
fun davList(call: PluginCall) { fun davList(call: PluginCall) {
try { try {
+207 -15
View File
@@ -416,7 +416,45 @@ async function folderPath(client, folder, createIfMissing = false) {
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null); return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
} }
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) { function filterMailboxMessages(messages, filters = {}) {
const text = String(filters.query || '').trim().toLowerCase();
const sender = String(filters.sender || '').trim().toLowerCase();
const subject = String(filters.subject || '').trim().toLowerCase();
const after = filters.after ? new Date(`${filters.after}T00:00:00`).getTime() : null;
const before = filters.before ? new Date(`${filters.before}T23:59:59.999`).getTime() : null;
return messages.filter(message => {
const haystack = `${message.sender || ''} ${message.email || ''} ${message.subject || ''} ${message.snippet || ''} ${(message.body || []).join(' ')}`.toLowerCase();
const date = Number(message.timestamp || 0);
return (!text || text.split(/\s+/).every(term => haystack.includes(term))) &&
(!sender || `${message.sender || ''} ${message.email || ''}`.toLowerCase().includes(sender)) &&
(!subject || String(message.subject || '').toLowerCase().includes(subject)) &&
(!after || date >= after) && (!before || date <= before) &&
(!filters.hasAttachments || (message.attachments || []).length > 0);
});
}
async function cacheMailboxMessages(accountId, folder, messages) {
if (!messages.length) return;
await updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
if (!account) return;
account.mailCache = account.mailCache || {};
const previous = account.mailCache[folder] || [];
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
for (const message of messages) merged.set(String(message.uid || message.id), message);
account.mailCache[folder] = [...merged.values()].slice(-50);
});
}
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
const start = Math.max(0, Number(offset) || 0);
const messages = all.slice(start, start + limit);
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
}
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit); if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
const client = imapClient(account); const client = imapClient(account);
try { try {
@@ -424,6 +462,27 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
const mailboxPath = await folderPath(client, folder); const mailboxPath = await folderPath(client, folder);
if (!mailboxPath) return { messages: [], total: 0 }; if (!mailboxPath) return { messages: [], total: 0 };
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true }); const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
const snoozed = new Set((account.snoozedMessages || [])
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
.map(item => Number(item.uid)));
if (Object.values(filters).some(value => value && value !== false)) {
const searchStart = Math.max(1, mailbox.exists - 4999);
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
uid: true, envelope: true, flags: true, internalDate: true, source: true
}) : [];
const all = [];
for (const item of fetched) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
all.push(message);
}
await cacheMailboxMessages(account.id, folder, all);
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
const start = Math.max(0, Number(offset) || 0);
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
}
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0)); const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder }; if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1); const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
@@ -434,9 +493,6 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
internalDate: true, internalDate: true,
source: true source: true
}); });
const snoozed = new Set((account.snoozedMessages || [])
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
.map(item => Number(item.uid)));
const messages = []; const messages = [];
for (const item of fetched.reverse()) { for (const item of fetched.reverse()) {
if (!item.source || snoozed.has(Number(item.uid))) continue; if (!item.source || snoozed.has(Number(item.uid))) continue;
@@ -444,6 +500,7 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || [])); message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
messages.push(message); messages.push(message);
} }
await cacheMailboxMessages(account.id, folder, messages);
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder }; return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
} finally { } finally {
if (client.usable) await client.logout().catch(() => {}); if (client.usable) await client.logout().catch(() => {});
@@ -453,7 +510,7 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
async function toUiMessage(item, folder) { async function toUiMessage(item, folder) {
const parsed = await simpleParser(item.source); const parsed = await simpleParser(item.source);
const sender = parsed.from?.value?.[0]; const sender = parsed.from?.value?.[0];
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim(); const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.']; const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
const date = parsed.date || item.internalDate || new Date(); const date = parsed.date || item.internalDate || new Date();
return { return {
@@ -466,12 +523,14 @@ async function toUiMessage(item, folder) {
snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180), snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date), time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date), date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
timestamp: date.getTime(),
unread: !item.flags?.has('\\Seen'), unread: !item.flags?.has('\\Seen'),
star: item.flags?.has('\\Flagged') || false, star: item.flags?.has('\\Flagged') || false,
tags: [folder], tags: [folder],
sent: folder === 'Sent', sent: folder === 'Sent',
archived: folder === 'Archive', archived: folder === 'Archive',
deleted: folder === 'Trash', deleted: folder === 'Trash',
sourceFolder: folder,
body, body,
uid: Number(item.uid), uid: Number(item.uid),
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })), attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
@@ -541,6 +600,7 @@ function backgroundFolderLabel(mailbox) {
} }
async function syncAccountMailboxes(account) { async function syncAccountMailboxes(account) {
await flushMailOutbox(account);
const generation = backgroundSyncGenerations.get(account.id) || 0; const generation = backgroundSyncGenerations.get(account.id) || 0;
const client = imapClient(account); const client = imapClient(account);
try { try {
@@ -798,12 +858,58 @@ ipcMain.handle('mail:connect', async (_event, input) => {
} }
}); });
ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) => { ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => {
const account = await readAccount(); const account = await readAccount();
if (!account) throw new Error('Add a mail account before syncing.'); if (!account) throw new Error('Add a mail account before syncing.');
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']); const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
const folder = allowedFolders.has(requestedFolder) ? requestedFolder : 'Inbox'; const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder;
return fetchMailbox(account, folder, offset); const folder = allowedFolders.has(selectedFolder) ? selectedFolder : 'Inbox';
const { folder: _filterFolder, ...criteria } = filters;
try {
await flushMailOutbox(account);
return await fetchMailbox(account, folder, offset, 20, criteria);
} catch (error) {
if (!isConnectivityFailure(error)) throw error;
const cached = cachedMailbox(account, folder, offset, 20, criteria);
if (!cached.total) throw error;
return cached;
}
});
ipcMain.handle('mail:list-drafts', async () => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before opening drafts.');
return { drafts: account.drafts || [], offline: true };
});
ipcMain.handle('mail:save-draft', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before saving drafts.');
const draft = {
id: String(input?.id || randomUUID()),
to: String(input?.to || '').slice(0, 4000),
cc: String(input?.cc || '').slice(0, 4000),
subject: String(input?.subject || '').slice(0, 998),
text: String(input?.text || '').slice(0, 500000),
updatedAt: Date.now()
};
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) throw new Error('That mail account is no longer available.');
const drafts = saved.drafts || [];
saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500);
});
return draft;
});
ipcMain.handle('mail:delete-draft', async (_event, id) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before deleting drafts.');
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id);
});
return { ok: true };
}); });
ipcMain.handle('mail:set-snooze', async (_event, input) => { ipcMain.handle('mail:set-snooze', async (_event, input) => {
@@ -839,9 +945,7 @@ ipcMain.handle('mail:set-snooze', async (_event, input) => {
return { ok: true, snoozed: dueAt != null }; return { ok: true, snoozed: dueAt != null };
}); });
ipcMain.handle('mail:update-message', async (_event, input) => { async function applyMessageAction(account, input) {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before changing messages.');
const uid = Number(input?.uid); const uid = Number(input?.uid);
const folder = String(input?.folder || 'Inbox'); const folder = String(input?.folder || 'Inbox');
const action = String(input?.action || ''); const action = String(input?.action || '');
@@ -887,6 +991,78 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
} finally { } finally {
if (client.usable) await client.logout().catch(() => {}); if (client.usable) await client.logout().catch(() => {});
} }
}
function isConnectivityFailure(error) {
const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']);
for (let current = error; current; current = current.cause) {
if (networkCodes.has(current.code)) return true;
if (/network is unreachable|connection timed out|connection refused|could not resolve|socket hang up/i.test(current.message || '')) return true;
}
return false;
}
function applyQueuedActionToCache(account, input) {
const folder = String(input.folder || 'Inbox');
const cache = account.mailCache?.[folder];
if (!cache) return;
const index = cache.findIndex(message => Number(message.uid || message.id) === Number(input.uid));
if (index < 0) return;
const [message] = cache.splice(index, 1);
if (input.action === 'star' || input.action === 'unread') {
message[input.action] = Boolean(input.enabled);
cache.splice(index, 0, message);
return;
}
const target = input.action === 'archive' ? 'Archive' : input.action === 'delete' ? 'Trash' : input.action === 'inbox' ? 'Inbox' : null;
if (!target) {
cache.splice(index, 0, message);
return;
}
message.sourceFolder = target;
message.archived = target === 'Archive';
message.deleted = target === 'Trash';
account.mailCache[target] = account.mailCache[target] || [];
account.mailCache[target] = [...account.mailCache[target].filter(item => Number(item.uid || item.id) !== Number(input.uid)), message].slice(-50);
}
async function flushMailOutbox(account) {
const operations = [...(account.mailOutbox || [])];
for (const operation of operations) {
try {
if (operation.type === 'send') await sendMailNow(account, operation.data);
else if (operation.type === 'action') await applyMessageAction(account, operation.data);
else throw new Error('Unsupported queued mail operation.');
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) saved.mailOutbox = (saved.mailOutbox || []).filter(item => item.id !== operation.id);
});
} catch (error) {
if (isConnectivityFailure(error)) break;
console.error(`Could not complete queued mail operation ${operation.id}:`, error);
break;
}
}
}
ipcMain.handle('mail:update-message', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before changing messages.');
try {
return await applyMessageAction(account, input);
} catch (error) {
if (!isConnectivityFailure(error)) throw error;
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) throw new Error('That mail account is no longer available.');
saved.mailOutbox = saved.mailOutbox || [];
saved.mailOutbox = saved.mailOutbox.filter(item => !(item.type === 'action' &&
Number(item.data?.uid) === Number(input.uid) && item.data?.folder === input.folder && item.data?.action === input.action));
saved.mailOutbox.push({ id: randomUUID(), type: 'action', data: input, createdAt: Date.now() });
applyQueuedActionToCache(saved, input);
});
return { ok: true, queued: true };
}
}); });
ipcMain.handle('mail:save-attachment', async (event, input) => { ipcMain.handle('mail:save-attachment', async (event, input) => {
@@ -927,13 +1103,11 @@ ipcMain.handle('mail:sync-inbox', async () => {
return fetchMailbox(account, 'Inbox'); return fetchMailbox(account, 'Inbox');
}); });
ipcMain.handle('mail:send', async (_event, message) => { async function sendMailNow(account, message) {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before sending.');
const to = String(message?.to || '').trim(); const to = String(message?.to || '').trim();
if (!to) throw new Error('Add at least one recipient.'); if (!to) throw new Error('Add at least one recipient.');
const transport = smtpTransport(account); const transport = smtpTransport(account);
const sentMessageId = `<${require('node:crypto').randomUUID()}@ep-mail.local>`; const sentMessageId = String(message.messageId || `<${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 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 body = String(message?.text || '').slice(0, 500000);
const signature = String(account.signature || '').slice(0, 5000); const signature = String(account.signature || '').slice(0, 5000);
@@ -973,6 +1147,24 @@ ipcMain.handle('mail:send', async (_event, message) => {
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends. // SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
} }
return { ok: true, savedToSent }; return { ok: true, savedToSent };
}
ipcMain.handle('mail:send', async (_event, message) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before sending.');
const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` };
try {
return await sendMailNow(account, queuedMessage);
} catch (error) {
if (!isConnectivityFailure(error)) throw error;
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) throw new Error('That mail account is no longer available.');
saved.mailOutbox = saved.mailOutbox || [];
saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() });
});
return { ok: true, queued: true };
}
}); });
ipcMain.handle('mail:disconnect', async (_event, accountId) => { ipcMain.handle('mail:disconnect', async (_event, accountId) => {
+4 -1
View File
@@ -8,7 +8,10 @@ contextBridge.exposeInMainWorld('daybreakMail', {
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id), removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
connect: details => ipcRenderer.invoke('mail:connect', details), connect: details => ipcRenderer.invoke('mail:connect', details),
updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details), updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details),
syncFolder: (folder, offset) => ipcRenderer.invoke('mail:sync-folder', folder, offset), syncFolder: (folder, offset, filters) => ipcRenderer.invoke('mail:sync-folder', folder, offset, filters),
listDrafts: () => ipcRenderer.invoke('mail:list-drafts'),
saveDraft: draft => ipcRenderer.invoke('mail:save-draft', draft),
deleteDraft: id => ipcRenderer.invoke('mail:delete-draft', id),
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'), syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)), onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
updateMessage: details => ipcRenderer.invoke('mail:update-message', details), updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
+1 -1
View File
@@ -43,7 +43,7 @@
</aside> </aside>
<main class="main-area"> <main class="main-area">
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button></div></header> <header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
<section id="mail-view" class="content-view mail-layout"> <section id="mail-view" class="content-view mail-layout">
<div class="list-pane"> <div class="list-pane">
+191 -2
View File
@@ -4,6 +4,7 @@ let mailTotal = 0;
let mailboxSyncPromise = null; let mailboxSyncPromise = null;
let mailboxSyncQueued = false; let mailboxSyncQueued = false;
let mailboxRefreshPending = false; let mailboxRefreshPending = false;
let folderBeforeSearch = null;
function updateAccountCard(account) { function updateAccountCard(account) {
const card = $('#account-settings'); const card = $('#account-settings');
@@ -126,6 +127,124 @@ function openMailAccount(existingAccount = null) {
}; };
$('#mail-account-email').focus(); $('#mail-account-email').focus();
} }
function mailSearchFilters() {
return {
query: $('#search').value.trim(),
sender: $('#filter-sender').value.trim(),
subject: $('#filter-subject').value.trim(),
after: $('#filter-after').value,
before: $('#filter-before').value,
hasAttachments: $('#filter-attachments').checked,
folder: $('#filter-folder').value
};
}
function renderDrafts(drafts) {
messages.splice(0, messages.length, ...drafts.map(draft => ({
id: draft.id,
sender: 'Draft',
email: draft.to || 'No recipient',
subject: draft.subject || '(no subject)',
snippet: String(draft.text || '').replace(/\s+/g, ' ').slice(0, 180) || 'No message text',
date: new Date(draft.updatedAt || Date.now()).toLocaleString(),
tags: ['Drafts'],
initials: 'D',
color: '#dce6df',
draft
})));
$('#message-list').innerHTML = messages.length ? messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft');
if (start) start.onclick = () => showCompose();
$$('.message').forEach(row => row.onclick = () => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (draft) showCompose(null, false, draft);
});
$('#reader-pane').innerHTML = emptyReader();
$('#pagination').textContent = `${messages.length} drafts`;
$('#load-more').classList.add('hidden');
}
function setupDraftComposer() {
const original = window.showCompose;
window.showCompose = (reply, forward = false, draft = null) => {
original(reply, forward);
const root = $('#modal-root');
const modal = root.querySelector('.compose-modal');
if (!modal) return;
modal.dataset.draftId = draft?.id || '';
if (draft) {
$('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || '';
$('#compose-subject').value = draft.subject || '';
$('#compose-body').value = draft.text || '';
modal.querySelector('.modal-head span').textContent = 'Edit draft';
}
const save = document.createElement('button');
save.type = 'button';
save.className = 'discard';
save.id = 'save-draft';
save.textContent = 'Save draft';
modal.querySelector('.compose-footer').insertBefore(save, $('#send'));
let saveTimer;
let closed = false;
const persist = async () => {
if (closed || !$('#compose-to')) return;
const values = {
id: modal.dataset.draftId || window.crypto.randomUUID(),
to: $('#compose-to').value,
cc: $('#compose-cc').value,
subject: $('#compose-subject').value,
text: $('#compose-body').value
};
if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return;
modal.dataset.draftId = values.id;
const result = await window.daybreakMail.saveDraft(values);
modal.dataset.draftId = result.id;
};
save.onclick = async () => {
try {
await persist();
toast('Draft saved on this device');
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not save draft'); }
};
modal.addEventListener('input', () => {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => persist().catch(error => toast(error.message || 'Could not save draft')), 700);
});
modal.querySelector('.modal-overlay')?.addEventListener('click', event => {
if (!event.target.classList.contains('modal-overlay')) return;
clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft'));
closed = true;
}, true);
root.querySelector('.modal-close')?.addEventListener('click', () => {
clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft'));
closed = true;
}, true);
$('#discard').onclick = async () => {
clearTimeout(saveTimer);
closed = true;
try {
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
root.innerHTML = '';
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete draft'); }
};
$('#send').addEventListener('click', () => {
clearTimeout(saveTimer);
closed = true;
}, true);
};
}
async function syncMailbox(showToast, options = {}) { async function syncMailbox(showToast, options = {}) {
if (mailboxSyncPromise) { if (mailboxSyncPromise) {
mailboxSyncQueued = true; mailboxSyncQueued = true;
@@ -139,9 +258,15 @@ async function syncMailbox(showToast, options = {}) {
if (refresh) refresh.disabled = true; if (refresh) refresh.disabled = true;
const sync = (async () => { const sync = (async () => {
try { try {
if (activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts();
renderDrafts(result.drafts || []);
if (showToast) toast(`${result.drafts.length} saved drafts`);
return;
}
const previouslyActiveMessage = activeMessage; const previouslyActiveMessage = activeMessage;
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset); const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
const result = await window.daybreakMail.syncFolder(activeFolder, offset); const result = await window.daybreakMail.syncFolder(activeFolder, offset, mailSearchFilters());
if (options.append) messages.push(...result.messages); if (options.append) messages.push(...result.messages);
else messages.splice(0, messages.length, ...result.messages); else messages.splice(0, messages.length, ...result.messages);
messages.forEach(message => { messages.forEach(message => {
@@ -163,6 +288,7 @@ async function syncMailbox(showToast, options = {}) {
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages'; if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = $('#load-more'); const loadMore = $('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total); if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
query = '';
renderList(); renderList();
if (activeMessage) { if (activeMessage) {
openMessage(activeMessage); openMessage(activeMessage);
@@ -171,12 +297,15 @@ async function syncMailbox(showToast, options = {}) {
} }
else $('#reader-pane').innerHTML = emptyReader(); else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount); updateAccountCard(connectedMailAccount);
const status = $('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toast(`Synced ${messages.length} messages`); if (showToast) toast(`Synced ${messages.length} messages`);
} catch (error) { } catch (error) {
toast(error.message || 'Could not sync the inbox'); toast(error.message || 'Could not sync the inbox');
} finally { } finally {
if (refresh) refresh.disabled = false; if (refresh) refresh.disabled = false;
} }
})(); })();
mailboxSyncPromise = sync; mailboxSyncPromise = sync;
try { try {
@@ -191,6 +320,48 @@ async function syncMailbox(showToast, options = {}) {
} }
if (window.daybreakMail) { if (window.daybreakMail) {
setupDraftComposer();
let searchTimer;
const searchControls = ['#search', '#filter-folder', '#filter-sender', '#filter-subject', '#filter-after', '#filter-before', '#filter-attachments'];
$('#search-filters-toggle').onclick = () => {
const panel = $('#search-filters');
const expanded = panel.classList.toggle('hidden') === false;
$('#search-filters-toggle').setAttribute('aria-expanded', String(expanded));
};
$('#clear-search-filters').onclick = () => {
$('#filter-folder').value = '';
$('#filter-sender').value = '';
$('#filter-subject').value = '';
$('#filter-after').value = '';
$('#filter-before').value = '';
$('#filter-attachments').checked = false;
$('#search').value = '';
activeFolder = folderBeforeSearch || activeFolder;
folderBeforeSearch = null;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
$('#sidebar-title').textContent = activeFolder;
$('#crumb-current').textContent = activeFolder;
query = '';
renderList();
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
};
for (const selector of searchControls) {
$(selector).addEventListener(selector === '#search' ? 'input' : 'change', () => {
if (selector === '#filter-folder' && $('#filter-folder').value) {
if (!folderBeforeSearch) folderBeforeSearch = activeFolder;
activeFolder = $('#filter-folder').value;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
$('#sidebar-title').textContent = activeFolder;
$('#crumb-current').textContent = activeFolder;
}
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
}, selector === '#search' ? 350 : 0);
});
}
window.daybreakMail.getAppVersion().then(version => { window.daybreakMail.getAppVersion().then(version => {
document.title = `ep-mail v${version}`; document.title = `ep-mail v${version}`;
}).catch(error => { }).catch(error => {
@@ -218,6 +389,9 @@ if (window.daybreakMail) {
window.addEventListener('focus', () => { window.addEventListener('focus', () => {
if (connectedMailAccount) syncMailbox(false); if (connectedMailAccount) syncMailbox(false);
}); });
window.addEventListener('online', () => {
if (connectedMailAccount) syncMailbox(false, { offset: 0 });
});
setInterval(() => { setInterval(() => {
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') { if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
syncMailbox(false); syncMailbox(false);
@@ -230,7 +404,11 @@ if (window.daybreakMail) {
$('#settings-button').onclick = () => openPreferences(); $('#settings-button').onclick = () => openPreferences();
$('#refresh').onclick = () => syncMailbox(true); $('#refresh').onclick = () => syncMailbox(true);
$$('.folder').forEach(button => button.addEventListener('click', () => { $$('.folder').forEach(button => button.addEventListener('click', () => {
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred'].includes(button.dataset.folder)) { if ($('#filter-folder').value) {
$('#filter-folder').value = '';
folderBeforeSearch = null;
}
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Drafts'].includes(button.dataset.folder)) {
mailPageOffset = 0; mailPageOffset = 0;
syncMailbox(false, { offset: 0 }); syncMailbox(false, { offset: 0 });
} }
@@ -263,9 +441,20 @@ if (window.daybreakMail) {
text: $('#compose-body').value, text: $('#compose-body').value,
displayName: connectedMailAccount.displayName || profileSettings.name displayName: connectedMailAccount.displayName || profileSettings.name
}); });
if (result.queued) {
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = '';
toast('Offline: message queued and will send when connected');
if (activeFolder === 'Drafts') void syncMailbox(false);
return;
}
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = ''; $('#modal-root').innerHTML = '';
toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved'); toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 }); if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { } catch (error) {
sendButton.disabled = false; sendButton.disabled = false;
sendButton.textContent = 'Send ↗'; sendButton.textContent = 'Send ↗';
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.1.19", "version": "0.1.20",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.1.19", "version": "0.1.20",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.1.19", "version": "0.1.20",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"author": "Eternity Project", "author": "Eternity Project",
+4 -1
View File
@@ -519,7 +519,10 @@
removeAccount: (id) => EpMail.removeAccount({ id }), removeAccount: (id) => EpMail.removeAccount({ id }),
connect: (details) => EpMail.connect(details), connect: (details) => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset) => EpMail.syncFolder({ folder, offset }), syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
listDrafts: () => EpMail.listDrafts(),
saveDraft: (draft) => EpMail.saveDraft(draft),
deleteDraft: (id) => EpMail.deleteDraft({ id }),
syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }), syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }),
onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback), onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback),
updateMessage: (details) => EpMail.updateMessage(details), updateMessage: (details) => EpMail.updateMessage(details),
+1 -1
View File
@@ -40,7 +40,7 @@ function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="
function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} 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=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).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 renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).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 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()} 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}).then(result=>{if(result?.queued)toast('Offline: action queued and will sync when connected');return result})}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')}} 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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.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 ↓';}); 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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.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()} 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()}
+4 -1
View File
@@ -11,7 +11,10 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
removeAccount: id => EpMail.removeAccount({ id }), removeAccount: id => EpMail.removeAccount({ id }),
connect: details => EpMail.connect(details), connect: details => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset) => EpMail.syncFolder({ folder, offset }), syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
listDrafts: () => EpMail.listDrafts(),
saveDraft: draft => EpMail.saveDraft(draft),
deleteDraft: id => EpMail.deleteDraft({ id }),
syncInbox: () => EpMail.syncFolder({ folder: 'Inbox', offset: 0 }), syncInbox: () => EpMail.syncFolder({ folder: 'Inbox', offset: 0 }),
onSyncUpdate: callback => EpMail.addListener('mailSyncUpdate', callback), onSyncUpdate: callback => EpMail.addListener('mailSyncUpdate', callback),
updateMessage: details => EpMail.updateMessage(details), updateMessage: details => EpMail.updateMessage(details),
+3
View File
@@ -118,3 +118,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.snooze-options .outline-button{width:100%;text-align:left} .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} .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}} @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}}
.search-filters{position:absolute;right:78px;top:calc(100% + 8px);z-index:12;display:grid;grid-template-columns:1fr 1fr;gap:10px;width:min(360px,calc(100vw - 32px));padding:14px;border:1px solid var(--border,#d8ddd5);border-radius:12px;background:var(--panel,#fff);box-shadow:0 8px 28px #17201724}.search-filters.hidden{display:none}.search-filters label{display:grid;gap:4px;font-size:12px}.search-filters input,.search-filters select{min-width:0;border:1px solid var(--border,#d8ddd5);border-radius:7px;padding:7px;background:transparent;color:inherit;font:inherit}.search-filters .filter-checkbox{display:flex;align-items:center;gap:7px}.search-filters .filter-checkbox input{min-width:auto}.search-filters .text-button{grid-column:1/-1;justify-self:start}.top-actions{position:relative}
body.ep-wasteland .search-filters{background:#211c18;border-color:#4a3f33;color:#d4cbbc}body.ep-wasteland .search-filters input,body.ep-wasteland .search-filters select{border-color:#4a3f33;color:#d4cbbc}
body.ep-daylight .search-filters{background:#fbfbf6;border-color:#b9c5bc;color:#263a3d}
+1 -1
View File
@@ -43,7 +43,7 @@
</aside> </aside>
<main class="main-area"> <main class="main-area">
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button></div></header> <header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
<section id="mail-view" class="content-view mail-layout"> <section id="mail-view" class="content-view mail-layout">
<div class="list-pane"> <div class="list-pane">
+191 -2
View File
@@ -4,6 +4,7 @@ let mailTotal = 0;
let mailboxSyncPromise = null; let mailboxSyncPromise = null;
let mailboxSyncQueued = false; let mailboxSyncQueued = false;
let mailboxRefreshPending = false; let mailboxRefreshPending = false;
let folderBeforeSearch = null;
function updateAccountCard(account) { function updateAccountCard(account) {
const card = $('#account-settings'); const card = $('#account-settings');
@@ -126,6 +127,124 @@ function openMailAccount(existingAccount = null) {
}; };
$('#mail-account-email').focus(); $('#mail-account-email').focus();
} }
function mailSearchFilters() {
return {
query: $('#search').value.trim(),
sender: $('#filter-sender').value.trim(),
subject: $('#filter-subject').value.trim(),
after: $('#filter-after').value,
before: $('#filter-before').value,
hasAttachments: $('#filter-attachments').checked,
folder: $('#filter-folder').value
};
}
function renderDrafts(drafts) {
messages.splice(0, messages.length, ...drafts.map(draft => ({
id: draft.id,
sender: 'Draft',
email: draft.to || 'No recipient',
subject: draft.subject || '(no subject)',
snippet: String(draft.text || '').replace(/\s+/g, ' ').slice(0, 180) || 'No message text',
date: new Date(draft.updatedAt || Date.now()).toLocaleString(),
tags: ['Drafts'],
initials: 'D',
color: '#dce6df',
draft
})));
$('#message-list').innerHTML = messages.length ? messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft');
if (start) start.onclick = () => showCompose();
$$('.message').forEach(row => row.onclick = () => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (draft) showCompose(null, false, draft);
});
$('#reader-pane').innerHTML = emptyReader();
$('#pagination').textContent = `${messages.length} drafts`;
$('#load-more').classList.add('hidden');
}
function setupDraftComposer() {
const original = window.showCompose;
window.showCompose = (reply, forward = false, draft = null) => {
original(reply, forward);
const root = $('#modal-root');
const modal = root.querySelector('.compose-modal');
if (!modal) return;
modal.dataset.draftId = draft?.id || '';
if (draft) {
$('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || '';
$('#compose-subject').value = draft.subject || '';
$('#compose-body').value = draft.text || '';
modal.querySelector('.modal-head span').textContent = 'Edit draft';
}
const save = document.createElement('button');
save.type = 'button';
save.className = 'discard';
save.id = 'save-draft';
save.textContent = 'Save draft';
modal.querySelector('.compose-footer').insertBefore(save, $('#send'));
let saveTimer;
let closed = false;
const persist = async () => {
if (closed || !$('#compose-to')) return;
const values = {
id: modal.dataset.draftId || window.crypto.randomUUID(),
to: $('#compose-to').value,
cc: $('#compose-cc').value,
subject: $('#compose-subject').value,
text: $('#compose-body').value
};
if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return;
modal.dataset.draftId = values.id;
const result = await window.daybreakMail.saveDraft(values);
modal.dataset.draftId = result.id;
};
save.onclick = async () => {
try {
await persist();
toast('Draft saved on this device');
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not save draft'); }
};
modal.addEventListener('input', () => {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => persist().catch(error => toast(error.message || 'Could not save draft')), 700);
});
modal.querySelector('.modal-overlay')?.addEventListener('click', event => {
if (!event.target.classList.contains('modal-overlay')) return;
clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft'));
closed = true;
}, true);
root.querySelector('.modal-close')?.addEventListener('click', () => {
clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft'));
closed = true;
}, true);
$('#discard').onclick = async () => {
clearTimeout(saveTimer);
closed = true;
try {
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
root.innerHTML = '';
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete draft'); }
};
$('#send').addEventListener('click', () => {
clearTimeout(saveTimer);
closed = true;
}, true);
};
}
async function syncMailbox(showToast, options = {}) { async function syncMailbox(showToast, options = {}) {
if (mailboxSyncPromise) { if (mailboxSyncPromise) {
mailboxSyncQueued = true; mailboxSyncQueued = true;
@@ -139,9 +258,15 @@ async function syncMailbox(showToast, options = {}) {
if (refresh) refresh.disabled = true; if (refresh) refresh.disabled = true;
const sync = (async () => { const sync = (async () => {
try { try {
if (activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts();
renderDrafts(result.drafts || []);
if (showToast) toast(`${result.drafts.length} saved drafts`);
return;
}
const previouslyActiveMessage = activeMessage; const previouslyActiveMessage = activeMessage;
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset); const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
const result = await window.daybreakMail.syncFolder(activeFolder, offset); const result = await window.daybreakMail.syncFolder(activeFolder, offset, mailSearchFilters());
if (options.append) messages.push(...result.messages); if (options.append) messages.push(...result.messages);
else messages.splice(0, messages.length, ...result.messages); else messages.splice(0, messages.length, ...result.messages);
messages.forEach(message => { messages.forEach(message => {
@@ -163,6 +288,7 @@ async function syncMailbox(showToast, options = {}) {
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages'; if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = $('#load-more'); const loadMore = $('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total); if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
query = '';
renderList(); renderList();
if (activeMessage) { if (activeMessage) {
openMessage(activeMessage); openMessage(activeMessage);
@@ -171,12 +297,15 @@ async function syncMailbox(showToast, options = {}) {
} }
else $('#reader-pane').innerHTML = emptyReader(); else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount); updateAccountCard(connectedMailAccount);
const status = $('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toast(`Synced ${messages.length} messages`); if (showToast) toast(`Synced ${messages.length} messages`);
} catch (error) { } catch (error) {
toast(error.message || 'Could not sync the inbox'); toast(error.message || 'Could not sync the inbox');
} finally { } finally {
if (refresh) refresh.disabled = false; if (refresh) refresh.disabled = false;
} }
})(); })();
mailboxSyncPromise = sync; mailboxSyncPromise = sync;
try { try {
@@ -191,6 +320,48 @@ async function syncMailbox(showToast, options = {}) {
} }
if (window.daybreakMail) { if (window.daybreakMail) {
setupDraftComposer();
let searchTimer;
const searchControls = ['#search', '#filter-folder', '#filter-sender', '#filter-subject', '#filter-after', '#filter-before', '#filter-attachments'];
$('#search-filters-toggle').onclick = () => {
const panel = $('#search-filters');
const expanded = panel.classList.toggle('hidden') === false;
$('#search-filters-toggle').setAttribute('aria-expanded', String(expanded));
};
$('#clear-search-filters').onclick = () => {
$('#filter-folder').value = '';
$('#filter-sender').value = '';
$('#filter-subject').value = '';
$('#filter-after').value = '';
$('#filter-before').value = '';
$('#filter-attachments').checked = false;
$('#search').value = '';
activeFolder = folderBeforeSearch || activeFolder;
folderBeforeSearch = null;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
$('#sidebar-title').textContent = activeFolder;
$('#crumb-current').textContent = activeFolder;
query = '';
renderList();
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
};
for (const selector of searchControls) {
$(selector).addEventListener(selector === '#search' ? 'input' : 'change', () => {
if (selector === '#filter-folder' && $('#filter-folder').value) {
if (!folderBeforeSearch) folderBeforeSearch = activeFolder;
activeFolder = $('#filter-folder').value;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
$('#sidebar-title').textContent = activeFolder;
$('#crumb-current').textContent = activeFolder;
}
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
}, selector === '#search' ? 350 : 0);
});
}
window.daybreakMail.getAppVersion().then(version => { window.daybreakMail.getAppVersion().then(version => {
document.title = `ep-mail v${version}`; document.title = `ep-mail v${version}`;
}).catch(error => { }).catch(error => {
@@ -218,6 +389,9 @@ if (window.daybreakMail) {
window.addEventListener('focus', () => { window.addEventListener('focus', () => {
if (connectedMailAccount) syncMailbox(false); if (connectedMailAccount) syncMailbox(false);
}); });
window.addEventListener('online', () => {
if (connectedMailAccount) syncMailbox(false, { offset: 0 });
});
setInterval(() => { setInterval(() => {
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') { if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
syncMailbox(false); syncMailbox(false);
@@ -230,7 +404,11 @@ if (window.daybreakMail) {
$('#settings-button').onclick = () => openPreferences(); $('#settings-button').onclick = () => openPreferences();
$('#refresh').onclick = () => syncMailbox(true); $('#refresh').onclick = () => syncMailbox(true);
$$('.folder').forEach(button => button.addEventListener('click', () => { $$('.folder').forEach(button => button.addEventListener('click', () => {
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred'].includes(button.dataset.folder)) { if ($('#filter-folder').value) {
$('#filter-folder').value = '';
folderBeforeSearch = null;
}
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Drafts'].includes(button.dataset.folder)) {
mailPageOffset = 0; mailPageOffset = 0;
syncMailbox(false, { offset: 0 }); syncMailbox(false, { offset: 0 });
} }
@@ -263,9 +441,20 @@ if (window.daybreakMail) {
text: $('#compose-body').value, text: $('#compose-body').value,
displayName: connectedMailAccount.displayName || profileSettings.name displayName: connectedMailAccount.displayName || profileSettings.name
}); });
if (result.queued) {
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = '';
toast('Offline: message queued and will send when connected');
if (activeFolder === 'Drafts') void syncMailbox(false);
return;
}
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = ''; $('#modal-root').innerHTML = '';
toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved'); toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 }); if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { } catch (error) {
sendButton.disabled = false; sendButton.disabled = false;
sendButton.textContent = 'Send ↗'; sendButton.textContent = 'Send ↗';
+4 -1
View File
@@ -519,7 +519,10 @@
removeAccount: (id) => EpMail.removeAccount({ id }), removeAccount: (id) => EpMail.removeAccount({ id }),
connect: (details) => EpMail.connect(details), connect: (details) => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset) => EpMail.syncFolder({ folder, offset }), syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
listDrafts: () => EpMail.listDrafts(),
saveDraft: (draft) => EpMail.saveDraft(draft),
deleteDraft: (id) => EpMail.deleteDraft({ id }),
syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }), syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }),
onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback), onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback),
updateMessage: (details) => EpMail.updateMessage(details), updateMessage: (details) => EpMail.updateMessage(details),
+1 -1
View File
@@ -40,7 +40,7 @@ function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="
function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} 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=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).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 renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).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 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()} 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}).then(result=>{if(result?.queued)toast('Offline: action queued and will sync when connected');return result})}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')}} 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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.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 ↓';}); 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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.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()} 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()}
+3
View File
@@ -118,3 +118,6 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.snooze-options .outline-button{width:100%;text-align:left} .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} .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}} @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}}
.search-filters{position:absolute;right:78px;top:calc(100% + 8px);z-index:12;display:grid;grid-template-columns:1fr 1fr;gap:10px;width:min(360px,calc(100vw - 32px));padding:14px;border:1px solid var(--border,#d8ddd5);border-radius:12px;background:var(--panel,#fff);box-shadow:0 8px 28px #17201724}.search-filters.hidden{display:none}.search-filters label{display:grid;gap:4px;font-size:12px}.search-filters input,.search-filters select{min-width:0;border:1px solid var(--border,#d8ddd5);border-radius:7px;padding:7px;background:transparent;color:inherit;font:inherit}.search-filters .filter-checkbox{display:flex;align-items:center;gap:7px}.search-filters .filter-checkbox input{min-width:auto}.search-filters .text-button{grid-column:1/-1;justify-self:start}.top-actions{position:relative}
body.ep-wasteland .search-filters{background:#211c18;border-color:#4a3f33;color:#d4cbbc}body.ep-wasteland .search-filters input,body.ep-wasteland .search-filters select{border-color:#4a3f33;color:#d4cbbc}
body.ep-daylight .search-filters{background:#fbfbf6;border-color:#b9c5bc;color:#263a3d}