package studio.daybreak.mail import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.Uri import android.os.Build import android.app.AlertDialog import com.getcapacitor.JSObject import com.getcapacitor.Plugin import com.getcapacitor.PluginCall import com.getcapacitor.PluginMethod import com.getcapacitor.annotation.CapacitorPlugin import java.util.Locale import java.util.UUID import org.json.JSONArray import org.json.JSONObject @CapacitorPlugin(name = "EpMail") class EpMailPlugin : Plugin() { private var syncReceiver: BroadcastReceiver? = null override fun load() { AndroidAccountVault.initialize(context) val filter = IntentFilter(MailIdleService.ACTION_MAIL_SYNC) val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val update = intent.getStringExtra(MailIdleService.EXTRA_SYNC_UPDATE) ?: return notifyListeners("mailSyncUpdate", JSObject(update)) } } syncReceiver = receiver if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) } else { @Suppress("DEPRECATION") context.registerReceiver(receiver, filter) } MailIdleService.start(context) } override fun handleOnResume() { MailIdleService.start(context) } override fun handleOnDestroy() { syncReceiver?.let { try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {} } syncReceiver = null } @PluginMethod fun getAppVersion(call: PluginCall) { call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME)) } @PluginMethod fun getAccount(call: PluginCall) { val account = AndroidAccountVault.account() if (account == null) call.resolve() else call.resolve(AndroidAccountVault.publicAccount(account).toJSObject()) } @PluginMethod fun listAccounts(call: PluginCall) { val store = AndroidAccountVault.read() call.resolve(JSObject() .put("accounts", AndroidAccountVault.publicAccounts()) .put("activeId", store.optString("activeId"))) } @PluginMethod fun selectAccount(call: PluginCall) { try { val id = call.getString("id") ?: throw IllegalArgumentException("Choose a mail account.") val account = AndroidAccountVault.account(id) ?: throw IllegalStateException("That mail account is no longer available.") val store = AndroidAccountVault.read().put("activeId", id) AndroidAccountVault.write(store) MailIdleService.start(context) call.resolve(AndroidAccountVault.publicAccount(account).toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not select the mail account.") } } @PluginMethod fun removeAccount(call: PluginCall) { try { val id = call.getString("id") ?: throw IllegalArgumentException("Choose a mail account.") val result = AndroidAccountVault.removeAccount(id) if (AndroidAccountVault.accounts().length() == 0) MailIdleService.stop(context) else MailIdleService.start(context) call.resolve(result.toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not remove the mail account.") } } @PluginMethod fun connect(call: PluginCall) { try { val account = normalizeAccount(call.data) val status = AndroidMailService.connect(account) val saved = AndroidAccountVault.saveAccount(account) MailIdleService.start(context) call.resolve(AndroidAccountVault.publicAccount(saved) .put("ok", true) .put("mailbox", status.optString("mailbox")) .put("messages", status.optInt("messages")).toJSObject()) } catch (error: Exception) { call.reject("Could not connect to the mailbox: ${error.message}") } } @PluginMethod fun updateAccount(call: PluginCall) { try { val id = call.getString("id") ?: throw IllegalArgumentException("Choose a mail account.") val existing = AndroidAccountVault.account(id) ?: throw IllegalStateException("That mail account is no longer available.") val input = JSONObject(call.data.toString()).apply { if (optString("password").isBlank()) put("password", existing.optString("password")) } val account = normalizeAccount(input).put("id", id) val status = AndroidMailService.connect(account) val saved = AndroidAccountVault.saveAccount(account) MailIdleService.start(context) call.resolve(AndroidAccountVault.publicAccount(saved) .put("mailbox", status.optString("mailbox")) .put("messages", status.optInt("messages")).toJSObject()) } catch (error: Exception) { call.reject("Could not update the mailbox: ${error.message}") } } @PluginMethod fun listFolders(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before listing folders.") call.resolve(AndroidMailService.listFolders(account).toJSObject()) } catch (error: Exception) { call.resolve(JSObject().put("folders", org.json.JSONArray()).put("offline", true)) } } @PluginMethod fun createFolder(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before creating folders.") call.resolve(AndroidMailService.createFolder(account, call.getString("name") ?: "").toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not create the folder.") } } @PluginMethod fun syncFolder(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before syncing.") val requested = call.getString("folder") ?: "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") || AndroidMailService.isCustomFolder(selected)) selected else "Inbox" val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0) AndroidMailService.flushOutbox(account) call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not sync the mailbox.") } } @PluginMethod fun updateMessage(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before changing messages.") call.resolve(AndroidMailService.updateMessage(account, call.data).toJSObject()) } catch (error: Exception) { 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.") } } @PluginMethod fun setSnooze(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before setting a reminder.") val uid = call.getLong("uid") ?: throw IllegalArgumentException("That message could not be identified.") require(uid > 0) { "That message could not be identified." } val folder = call.getString("sourceFolder") ?: call.getString("folder") ?: "Inbox" require(folder in setOf("Inbox", "Sent", "Archive", "Trash")) { "That mailbox cannot be snoozed." } val dueAt = call.getLong("dueAt") if (dueAt != null && dueAt <= System.currentTimeMillis()) { throw IllegalArgumentException("Choose a reminder time in the future.") } AndroidAccountVault.setSnooze( account.optString("id"), uid, folder, dueAt, call.getString("subject").orEmpty() ) val update = JSONObject() .put("accountId", account.optString("id")) .put("foldersChanged", JSONArray().put("Snoozed").put(folder)) context.sendBroadcast(Intent(MailIdleService.ACTION_MAIL_SYNC) .setPackage(context.packageName) .putExtra(MailIdleService.EXTRA_SYNC_UPDATE, update.toString())) MailIdleService.start(context) call.resolve(JSObject().put("ok", true).put("snoozed", dueAt != null)) } catch (error: Exception) { call.reject(error.message ?: "Could not set the reminder.") } } @PluginMethod fun checkSnoozeReminders(call: PluginCall) { try { MailIdleService.checkSnoozeReminders(context) call.resolve() } catch (error: Exception) { call.reject(error.message ?: "Could not check mail reminders.") } } @PluginMethod fun saveAttachment(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before downloading attachments.") call.resolve(AndroidMailService.saveAttachment(context, account, call.data).toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not save the attachment.") } } @PluginMethod fun previewAttachment(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before previewing attachments.") call.resolve(AndroidMailService.previewAttachment(account, JSONObject(call.data.toString())).toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not preview the attachment.") } } @PluginMethod fun openExternal(call: PluginCall) { val raw = call.getString("url").orEmpty() val uri = runCatching { Uri.parse(raw) }.getOrNull() if (uri == null || uri.scheme?.lowercase(Locale.ROOT) !in setOf("http", "https") || uri.host.isNullOrBlank() || uri.userInfo != null) { call.reject("Only standard web links can be opened from mail.") return } AlertDialog.Builder(activity) .setTitle("Open external link?") .setMessage("Email links can lead to fake sign-in pages or harmful content.\n\nCheck the full address before continuing:\n${uri}") .setNegativeButton("Cancel") { _, _ -> call.resolve(JSObject().put("opened", false)) } .setPositiveButton("Open link") { _, _ -> try { val intent = Intent(Intent.ACTION_VIEW, uri) activity.startActivity(intent) call.resolve(JSObject().put("opened", true)) } catch (_: android.content.ActivityNotFoundException) { call.reject("No browser is available to open this link.") } catch (error: Exception) { call.reject(error.message ?: "Could not open the link.") } } .setOnCancelListener { call.resolve(JSObject().put("opened", false)) } .show() } @PluginMethod fun send(call: PluginCall) { val input = JSONObject(call.data.toString()).apply { if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>") } try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before sending.") call.resolve(AndroidMailService.send(account, input).toJSObject()) } catch (error: Exception) { val account = AndroidAccountVault.account() if (account != null && isConnectivityFailure(error)) { AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject() .put("id", UUID.randomUUID().toString()) .put("type", "send") .put("data", input)) call.resolve(JSObject().put("ok", true).put("queued", true)) } else call.reject(error.message ?: "Could not send the message.") } } @PluginMethod fun listDrafts(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before opening drafts.") call.resolve(JSObject().put("drafts", account.optJSONArray("drafts") ?: JSONArray()).put("offline", true)) } catch (error: Exception) { call.reject(error.message ?: "Could not open drafts.") } } @PluginMethod fun saveDraft(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before saving drafts.") val input = JSONObject(call.data.toString()) val draft = JSONObject() .put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() }) .put("to", input.optString("to").take(4000)) .put("cc", input.optString("cc").take(4000)) .put("subject", input.optString("subject").take(998)) .put("text", input.optString("text").take(500000)) .put("updatedAt", System.currentTimeMillis()) AndroidAccountVault.saveDraft(account.optString("id"), draft) call.resolve(draft.toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not save the draft.") } } @PluginMethod fun deleteDraft(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before deleting drafts.") val id = call.getString("id") ?: throw IllegalArgumentException("Choose a draft.") AndroidAccountVault.deleteDraft(account.optString("id"), id) call.resolve(JSObject().put("ok", true)) } catch (error: Exception) { call.reject(error.message ?: "Could not delete the draft.") } } private fun isConnectivityFailure(error: Throwable): Boolean { var current: Throwable? = error while (current != null) { if (current is java.net.UnknownHostException || current is java.net.ConnectException || current is java.net.SocketTimeoutException || current is javax.net.ssl.SSLException) return true val message = current.message.orEmpty().lowercase(Locale.ROOT) if (listOf("network is unreachable", "connection timed out", "connection refused", "unable to resolve host", "socket closed").any(message::contains)) return true current = current.cause } return false } @PluginMethod fun davList(call: PluginCall) { try { call.resolve(AndroidDavService.list().toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not list DAV accounts.") } } @PluginMethod fun davConnect(call: PluginCall) { try { call.resolve(AndroidDavService.connect(call.data).toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not connect the DAV account.") } } @PluginMethod fun davActivate(call: PluginCall) { try { call.resolve(AndroidDavService.activate(call.getString("type") ?: "caldav", call.getString("id") ?: "").toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not activate the DAV account.") } } @PluginMethod fun davRemove(call: PluginCall) { try { call.resolve(AndroidDavService.remove(call.getString("type") ?: "caldav", call.getString("id") ?: "").toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not remove the DAV account.") } } @PluginMethod fun davSync(call: PluginCall) { try { call.resolve(AndroidDavService.sync(call.getString("type") ?: "caldav").toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not sync the DAV account.") } } @PluginMethod fun davSaveEvent(call: PluginCall) { try { val result = AndroidDavService.saveEvent(call.data) if (result == null) call.resolve() else call.resolve(result.toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not save the calendar event.") } } @PluginMethod fun davDeleteEvent(call: PluginCall) { try { AndroidDavService.deleteEvent(call.data) call.resolve() } catch (error: Exception) { call.reject(error.message ?: "Could not delete the calendar event.") } } @PluginMethod fun davSaveContact(call: PluginCall) { try { val result = AndroidDavService.saveContact(call.data) if (result == null) call.resolve() else call.resolve(result.toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not save the contact.") } } @PluginMethod fun davDeleteContact(call: PluginCall) { try { AndroidDavService.deleteContact(call.data) call.resolve() } catch (error: Exception) { call.reject(error.message ?: "Could not delete the contact.") } } private fun normalizeAccount(input: JSONObject): JSONObject { val email = input.optString("email").trim() val password = input.optString("password") val displayName = input.optString("displayName").trim().take(80) val imapHost = input.optString("imapHost").trim() val smtpHost = input.optString("smtpHost").trim() require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) { "Enter a valid email, account display name, password, and both mail server names." } return JSONObject() .put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() }) .put("email", email) .put("password", password) .put("displayName", displayName) .put("imapHost", imapHost) .put("smtpHost", smtpHost) .put("signature", input.optString("signature").take(5000)) .put("notificationsEnabled", input.optBoolean("notificationsEnabled", true)) .put("syncIntervalMinutes", input.optInt("syncIntervalMinutes", 2).also { require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." } }) .put("rules", normalizeRules(input.optJSONArray("rules"))) .put("imapPort", input.optInt("imapPort", 143)) .put("smtpPort", input.optInt("smtpPort", 587)) } private fun normalizeRules(input: JSONArray?): JSONArray { val result = JSONArray() if (input == null) return result require(input.length() <= 50) { "You can set up to 50 mail rules per account." } for (index in 0 until input.length()) { val rule = input.getJSONObject(index) val sender = rule.optString("senderContains").trim().take(200) val subject = rule.optString("subjectContains").trim().take(200) val action = rule.optString("action") val value = rule.optString("value").trim().take(200) require((sender.isNotEmpty() || subject.isNotEmpty()) && action in setOf("archive", "move", "label", "flag")) { "Mail rule ${index + 1} needs a sender or subject condition and a valid action." } require(action !in setOf("move", "label") || value.isNotEmpty()) { "Mail rule ${index + 1} needs a destination folder or label." } require(action != "move" || !value.any { it == '\r' || it == '\n' || it == '\u0000' }) { "Mail rule ${index + 1} has an invalid destination folder." } require(action != "move" || value in setOf("Inbox", "Archive", "Trash") || AndroidMailService.isCustomFolder(value)) { "Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders." } result.put(JSONObject() .put("id", rule.optString("id").ifBlank { UUID.randomUUID().toString() }) .put("senderContains", sender) .put("subjectContains", subject) .put("action", action) .put("value", value)) } return result } private fun JSONObject.toJSObject(): JSObject = JSObject(toString()) companion object { private val EMAIL = Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$") } }