package studio.daybreak.mail import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build 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 syncFolder(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before syncing.") val requested = call.getString("folder") ?: "Inbox" val folder = if (requested in setOf("Inbox", "Sent", "Archive", "Trash", "Starred", "Snoozed")) requested else "Inbox" val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0) call.resolve(AndroidMailService.sync(account, folder, offset).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) { 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 send(call: PluginCall) { try { val account = AndroidAccountVault.account() ?: throw IllegalStateException("Add a mail account before sending.") call.resolve(AndroidMailService.send(account, call.data).toJSObject()) } catch (error: Exception) { call.reject(error.message ?: "Could not send the message.") } } @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("imapPort", input.optInt("imapPort", 143)) .put("smtpPort", input.optInt("smtpPort", 587)) } private fun JSONObject.toJSObject(): JSObject = JSObject(toString()) companion object { private val EMAIL = Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$") } }