Ver V0.1.16 Add Android version to project

This commit is contained in:
2026-10-07 00:26:54 +03:00
parent 7135cbb629
commit 520056d27c
83 changed files with 5783 additions and 5 deletions
@@ -0,0 +1,26 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MailIdleService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
</manifest>
@@ -0,0 +1,251 @@
package studio.daybreak.mail
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import org.json.JSONArray
import org.json.JSONObject
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
internal object AndroidAccountVault {
private const val KEY_ALIAS = "ep-mail-account-key"
private const val PREFS_NAME = "ep-mail-secure-store"
private const val ENCRYPTED_VALUE = "encrypted-data"
private const val GCM_TAG_BITS = 128
@Volatile private var appContext: Context? = null
fun initialize(context: Context) {
appContext = context.applicationContext
secretKey()
}
@Synchronized
fun read(): JSONObject {
val context = requireContext()
val encoded = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.getString(ENCRYPTED_VALUE, null) ?: return emptyStore()
val payload = Base64.decode(encoded, Base64.NO_WRAP)
require(payload.size > 12) { "Encrypted account data is invalid." }
val iv = payload.copyOfRange(0, 12)
val encrypted = payload.copyOfRange(12, payload.size)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
return JSONObject(String(cipher.doFinal(encrypted), Charsets.UTF_8))
}
@Synchronized
fun write(store: JSONObject) {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, secretKey())
val encrypted = cipher.doFinal(store.toString().toByteArray(Charsets.UTF_8))
val payload = cipher.iv + encrypted
val saved = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.edit()
.putString(ENCRYPTED_VALUE, Base64.encodeToString(payload, Base64.NO_WRAP))
.commit()
check(saved) { "Could not save encrypted account data." }
}
fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray()
fun account(id: String? = null): JSONObject? {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return null
val selectedId = id ?: store.optString("activeId")
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") == selectedId) return account
}
return null
}
@Synchronized
fun saveAccount(account: JSONObject): JSONObject {
val store = read()
val accounts = store.optJSONArray("accounts") ?: JSONArray()
val updated = JSONArray()
var saved: JSONObject? = null
for (index in 0 until accounts.length()) {
val previous = accounts.getJSONObject(index)
val same = previous.optString("email").equals(account.optString("email"), true) &&
previous.optString("imapHost").equals(account.optString("imapHost"), true)
if (same || previous.optString("id") == account.optString("id")) {
val merged = JSONObject(previous.toString())
val keys = account.keys()
while (keys.hasNext()) {
val key = keys.next()
merged.put(key, account.get(key))
}
saved = merged
updated.put(merged)
} else {
updated.put(previous)
}
}
if (saved == null) {
saved = JSONObject(account.toString())
updated.put(saved)
}
store.put("accounts", updated)
store.put("activeId", saved.optString("id"))
write(store)
return saved
}
@Synchronized
fun removeAccount(id: String?): JSONObject {
val store = read()
val accounts = store.optJSONArray("accounts") ?: JSONArray()
val kept = JSONArray()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) kept.put(account)
}
val activeId = if (store.optString("activeId") == id) {
kept.optJSONObject(0)?.optString("id") ?: ""
} else store.optString("activeId")
store.put("accounts", kept)
store.put("activeId", activeId)
write(store)
return JSONObject().put("accounts", publicAccounts(kept)).put("activeId", activeId)
}
@Synchronized
fun updateInboxCursor(id: String, uidValidity: Long, lastUid: Long) {
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) {
account.put("androidInboxSyncState", JSONObject()
.put("uidValidity", uidValidity)
.put("lastUid", lastUid))
write(store)
return
}
}
}
fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray {
val result = JSONArray()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
result.put(publicAccount(account))
}
return result
}
fun publicAccount(account: JSONObject): JSONObject = JSONObject()
.put("id", account.optString("id"))
.put("email", account.optString("email"))
.put("displayName", account.optString("displayName"))
.put("imapHost", account.optString("imapHost"))
.put("smtpHost", account.optString("smtpHost"))
fun storeDav(type: String): JSONArray = read().optJSONArray(type) ?: JSONArray()
fun putDavAccount(type: String, account: JSONObject): JSONObject {
val store = read()
val accounts = store.optJSONArray(type) ?: JSONArray()
val updated = JSONArray()
var saved: JSONObject? = null
for (index in 0 until accounts.length()) {
val previous = accounts.getJSONObject(index)
if (previous.optString("serverUrl") == account.optString("serverUrl") &&
previous.optString("username").equals(account.optString("username"), true)) {
val merged = JSONObject(account.toString()).put("id", previous.optString("id"))
updated.put(merged)
saved = merged
} else {
updated.put(previous)
}
}
if (saved == null) {
saved = JSONObject(account.toString())
updated.put(saved)
}
store.put(type, updated)
store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", saved.optString("id"))
write(store)
return saved
}
fun activeDav(type: String, id: String? = null): JSONObject? {
val store = read()
val accounts = store.optJSONArray(type) ?: return null
val selectedId = id ?: store.optString(if (type == "caldav") "activeCaldavId" else "activeCarddavId")
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") == selectedId) return account
}
return null
}
fun publicDavAccounts(type: String): JSONArray {
val result = JSONArray()
val accounts = storeDav(type)
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
result.put(JSONObject()
.put("id", account.optString("id"))
.put("serverUrl", account.optString("serverUrl"))
.put("username", account.optString("username"))
.put("collections", account.optJSONArray("collections") ?: JSONArray()))
}
return result
}
fun removeDavAccount(type: String, id: String): JSONObject {
val store = read()
val accounts = store.optJSONArray(type) ?: JSONArray()
val remaining = JSONArray()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) remaining.put(account)
}
val activeKey = if (type == "caldav") "activeCaldavId" else "activeCarddavId"
val activeId = if (store.optString(activeKey) == id) {
remaining.optJSONObject(0)?.optString("id") ?: ""
} else store.optString(activeKey)
store.put(type, remaining)
store.put(activeKey, activeId)
write(store)
return JSONObject().put("accounts", publicDavAccounts(type)).put("activeId", activeId)
}
private fun emptyStore() = JSONObject()
.put("accounts", JSONArray())
.put("activeId", "")
.put("caldav", JSONArray())
.put("carddav", JSONArray())
.put("activeCaldavId", "")
.put("activeCarddavId", "")
private fun requireContext(): Context =
appContext ?: throw IllegalStateException("Encrypted account storage is not initialized.")
@Synchronized
private fun secretKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.setRandomizedEncryptionRequired(true)
.build()
)
return generator.generateKey()
}
}
@@ -0,0 +1,443 @@
package studio.daybreak.mail
import android.util.Base64
import org.json.JSONArray
import org.json.JSONObject
import org.w3c.dom.Element
import java.io.ByteArrayInputStream
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.Locale
import java.util.UUID
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit
import javax.xml.parsers.DocumentBuilderFactory
internal object AndroidDavService {
private val httpClient = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
fun list(): JSONObject {
val store = AndroidAccountVault.read()
return JSONObject()
.put("caldav", AndroidAccountVault.publicDavAccounts("caldav"))
.put("carddav", AndroidAccountVault.publicDavAccounts("carddav"))
.put("activeCaldavId", store.optString("activeCaldavId"))
.put("activeCarddavId", store.optString("activeCarddavId"))
}
fun connect(input: JSONObject): JSONObject {
val type = type(input.optString("type"))
val serverUrl = input.optString("serverUrl").trim()
val username = input.optString("username").trim()
val password = input.optString("password")
val url = try { URL(serverUrl) } catch (_: Exception) {
throw IllegalArgumentException("Enter a valid CalDAV or CardDAV server URL.")
}
require(url.protocol == "https" || (url.protocol == "http" && url.host in setOf("localhost", "127.0.0.1", "::1"))) {
"DAV server URLs must use HTTPS."
}
require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." }
val collections = discoverCollections(url.toString(), username, password, type)
require(collections.length() > 0) {
"No ${if (type == "caldav") "calendars" else "address books"} were found on this server."
}
val account = JSONObject()
.put("id", UUID.randomUUID().toString())
.put("type", type)
.put("serverUrl", url.toString())
.put("username", username)
.put("password", password)
.put("collections", collections)
val saved = AndroidAccountVault.putDavAccount(type, account)
val publicConfig = publicDav(saved)
return JSONObject()
.put("config", publicConfig)
.put("collections", collections)
.put("accounts", list())
}
fun activate(typeInput: String, id: String): JSONObject {
val type = type(typeInput)
val config = AndroidAccountVault.activeDav(type, id)
?: throw IllegalStateException("That DAV account could not be found.")
val store = AndroidAccountVault.read()
store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", config.optString("id"))
AndroidAccountVault.write(store)
return JSONObject().put("id", config.optString("id"))
}
fun remove(typeInput: String, id: String): JSONObject =
AndroidAccountVault.removeDavAccount(type(typeInput), id)
fun sync(typeInput: String): JSONObject {
val type = type(typeInput)
val account = AndroidAccountVault.activeDav(type)
?: throw IllegalStateException("Connect a ${if (type == "caldav") "CalDAV" else "CardDAV"} server first.")
val collectionKey = if (type == "caldav") "calendar" else "addressbook"
val result = JSONArray()
val collections = account.optJSONArray("collections") ?: JSONArray()
for (index in 0 until collections.length()) {
val collection = collections.getJSONObject(index)
val objects = listObjects(account, collection, type)
for (obj in objects) {
val href = obj.optString("href")
val data = obj.optString("data")
if (data.isBlank()) continue
if (type == "caldav") parseCalendar(data, account, collection, obj).forEach(result::put)
else parseContacts(data, account, collection, obj).forEach(result::put)
}
}
return JSONObject().put("items", result).put("account", publicDav(account))
.put("collectionType", collectionKey)
}
fun saveEvent(input: JSONObject): JSONObject? {
val remote = input.optJSONObject("_dav") ?: JSONObject()
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId").ifBlank { null }) ?: return null
val collections = account.optJSONArray("collections") ?: JSONArray()
val collection = findCollection(collections, remote.optString("collectionUrl"))
?: throw IllegalStateException("No writable calendar was found.")
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
val filename = "$uid.ics"
val collectionUrl = collection.optString("url")
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
val data = calendarData(input, uid)
val response = request(account, target, "PUT", data, mapOf("Content-Type" to "text/calendar; charset=utf-8"))
require(response.code in 200..299) { "The calendar server rejected the event (${response.code})." }
return JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collectionUrl)
.put("objectUrl", target)
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
.put("uid", uid)
}
fun deleteEvent(remote: JSONObject) {
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId"))
?: throw IllegalStateException("That calendar account could not be found.")
val url = remote.optString("objectUrl")
if (url.isBlank()) return
val response = request(account, url, "DELETE", null)
require(response.code in 200..299 || response.code == 404) { "The calendar server rejected the deletion (${response.code})." }
}
fun saveContact(input: JSONObject): JSONObject? {
val remote = input.optJSONObject("_dav") ?: JSONObject()
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId").ifBlank { null }) ?: return null
val collections = account.optJSONArray("collections") ?: JSONArray()
val collection = findCollection(collections, remote.optString("collectionUrl"))
?: throw IllegalStateException("No writable address book was found.")
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
val filename = "$uid.vcf"
val collectionUrl = collection.optString("url")
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
val response = request(account, target, "PUT", vcardData(input, uid), mapOf("Content-Type" to "text/vcard; charset=utf-8"))
require(response.code in 200..299) { "The address book server rejected the contact (${response.code})." }
return JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collectionUrl)
.put("objectUrl", target)
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
.put("uid", uid)
}
fun deleteContact(remote: JSONObject) {
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId"))
?: throw IllegalStateException("That address book account could not be found.")
val url = remote.optString("objectUrl")
if (url.isBlank()) return
val response = request(account, url, "DELETE", null)
require(response.code in 200..299 || response.code == 404) { "The address book server rejected the deletion (${response.code})." }
}
private data class HttpResult(val code: Int, val body: ByteArray, val headers: Map<String, String>)
private fun request(
account: JSONObject,
address: String,
method: String,
body: String?,
headers: Map<String, String> = emptyMap()
): HttpResult {
val target = URL(address)
val base = URL(account.optString("serverUrl"))
val targetPort = if (target.port >= 0) target.port else target.defaultPort
val basePort = if (base.port >= 0) base.port else base.defaultPort
require(target.protocol == base.protocol && target.host.equals(base.host, true) && targetPort == basePort) {
"The DAV server returned a collection URL on an unexpected host."
}
val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull())
val builder = Request.Builder()
.url(address)
.header("Authorization", basicAuth(account))
.header("User-Agent", "ep-mail-Android")
for ((key, value) in headers) builder.header(key, value)
builder.method(method, requestBody)
httpClient.newCall(builder.build()).execute().use { response ->
val bytes = response.body?.bytes() ?: ByteArray(0)
val responseHeaders = response.headers.toMultimap().mapValues { (_, values) -> values.firstOrNull().orEmpty() }
return HttpResult(response.code, bytes, responseHeaders)
}
}
private fun discoverCollections(serverUrl: String, username: String, password: String, type: String): JSONArray {
val base = JSONObject().put("serverUrl", serverUrl).put("username", username).put("password", password)
val setName = if (type == "caldav") "calendar-home-set" else "addressbook-home-set"
val rootResponse = request(base, serverUrl, "PROPFIND", propfindBody(setName), mapOf(
"Depth" to "0",
"Content-Type" to "application/xml; charset=utf-8"
))
require(rootResponse.code in 200..299 || rootResponse.code == 207) {
"Could not access the DAV server (${rootResponse.code})."
}
val rootDocument = parseXml(rootResponse.body)
var homeUrl = findHref(rootDocument, setName)?.let { resolveUrl(serverUrl, it) }
if (homeUrl == null) {
val principal = findHref(rootDocument, "current-user-principal")
if (principal != null) {
val principalUrl = resolveUrl(serverUrl, principal)
val principalResponse = request(base, principalUrl, "PROPFIND", propfindBody(setName), mapOf(
"Depth" to "0",
"Content-Type" to "application/xml; charset=utf-8"
))
if (principalResponse.code in 200..299 || principalResponse.code == 207) {
homeUrl = findHref(parseXml(principalResponse.body), setName)?.let { resolveUrl(principalUrl, it) }
}
}
}
val collectionUrl = homeUrl ?: serverUrl
val response = request(base, collectionUrl, "PROPFIND", collectionBody(), mapOf(
"Depth" to "1",
"Content-Type" to "application/xml; charset=utf-8"
))
require(response.code in 200..299 || response.code == 207) {
"Could not discover DAV collections (${response.code})."
}
val document = parseXml(response.body)
val requiredType = if (type == "caldav") "calendar" else "addressbook"
val result = JSONArray()
val responses = document.getElementsByTagNameNS("*", "response")
for (index in 0 until responses.length) {
val responseElement = responses.item(index) as? Element ?: continue
val href = childText(responseElement, "href") ?: continue
if (responseElement.getElementsByTagNameNS("*", requiredType).length == 0) continue
val resolved = resolveUrl(collectionUrl, href)
val displayName = textContent(responseElement, "displayname").orEmpty().ifBlank { resolved }
result.put(JSONObject().put("url", resolved).put("name", displayName))
}
return result
}
private fun listObjects(account: JSONObject, collection: JSONObject, type: String): List<JSONObject> {
val collectionUrl = collection.optString("url")
val response = request(account, collectionUrl, "PROPFIND", collectionBody(), mapOf(
"Depth" to "1",
"Content-Type" to "application/xml; charset=utf-8"
))
require(response.code in 200..299 || response.code == 207) {
"Could not read DAV collection ${collection.optString("name")} (${response.code})."
}
val document = parseXml(response.body)
val responses = document.getElementsByTagNameNS("*", "response")
val result = ArrayList<JSONObject>()
for (index in 0 until responses.length) {
val element = responses.item(index) as? Element ?: continue
val href = childText(element, "href") ?: continue
val objectUrl = resolveUrl(collectionUrl, href)
if (objectUrl.trimEnd('/') == collectionUrl.trimEnd('/')) continue
val data = if (type == "caldav") textContent(element, "calendar-data") else textContent(element, "address-data")
val content = if (!data.isNullOrBlank()) data else {
val fetched = request(account, objectUrl, "GET", null)
if (fetched.code !in 200..299) continue
String(fetched.body, StandardCharsets.UTF_8)
}
result.add(JSONObject()
.put("href", objectUrl)
.put("etag", textContent(element, "getetag").orEmpty())
.put("data", content))
}
return result
}
private fun parseCalendar(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
val unfolded = unfold(data)
return Regex("BEGIN:VEVENT(.*?)END:VEVENT", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
.findAll(unfolded).mapNotNull { match ->
val block = match.groupValues[1]
val fields = parseProperties(block)
val uid = fields["UID"].orEmpty().ifBlank { UUID.randomUUID().toString() }
val (date, time) = parseDate(fields["DTSTART"].orEmpty()) ?: return@mapNotNull null
JSONObject()
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
.put("title", unescape(fields["SUMMARY"].orEmpty()).ifBlank { "(no title)" })
.put("date", date)
.put("time", time)
.put("with", Regex("(?im)^ATTENDEE[^:]*:(?:mailto:)?([^\\r\\n]+)").findAll(block)
.map { it.groupValues[1].trim() }.joinToString(", "))
.put("place", unescape(fields["LOCATION"].orEmpty()))
.put("notes", unescape(fields["DESCRIPTION"].orEmpty()))
.put("_dav", JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collection.optString("url"))
.put("objectUrl", resource.optString("href"))
.put("etag", resource.optString("etag"))
.put("uid", uid))
}.toList()
}
private fun parseContacts(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
val cards = Regex("BEGIN:VCARD(.*?)END:VCARD", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
return cards.findAll(unfold(data)).mapNotNull { match ->
val block = match.groupValues[1]
val fields = parseProperties(block)
val name = unescape(fields["FN"].orEmpty()).trim()
if (name.isBlank()) return@mapNotNull null
val uid = fields["UID"].orEmpty()
JSONObject()
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
.put("name", name)
.put("email", unescape(fields["EMAIL"].orEmpty()))
.put("note", unescape(fields["NOTE"].orEmpty()))
.put("initials", name.split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.toString() }
.joinToString("").take(2).uppercase(Locale.getDefault()))
.put("color", "#dce9dd")
.put("_dav", JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collection.optString("url"))
.put("objectUrl", resource.optString("href"))
.put("etag", resource.optString("etag"))
.put("uid", uid))
}.toList()
}
private fun calendarData(event: JSONObject, uid: String): String {
val date = event.optString("date").replace("-", "")
val time = event.optString("time")
val start = if (time.isBlank()) "DTSTART;VALUE=DATE:$date" else "DTSTART;TZID=UTC:${date}T${time.replace(":", "")}00"
val end = if (time.isBlank()) "" else {
val parts = time.split(":")
val mins = (parts.getOrNull(0)?.toIntOrNull() ?: 0) * 60 + (parts.getOrNull(1)?.toIntOrNull() ?: 0) + 60
val endTime = "%04d%02d00".format(Locale.ROOT, (mins / 60) % 24, mins % 60)
"DTEND;TZID=UTC:${date}T$endTime\r\n"
}
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${escape(uid)}\r\nDTSTAMP:${utcNow()}\r\n$start\r\n$end${property("SUMMARY", event.optString("title"))}${property("LOCATION", event.optString("place"))}${property("DESCRIPTION", event.optString("notes"))}END:VEVENT\r\nEND:VCALENDAR\r\n"
}
private fun vcardData(contact: JSONObject, uid: String): String {
val name = contact.optString("name").trim().split(Regex("\\s+"))
val first = name.firstOrNull().orEmpty()
val last = name.drop(1).joinToString(" ")
return "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${escape(uid)}\r\nFN:${escape(contact.optString("name"))}\r\nN:${escape(last)};${escape(first)};;;\r\nEMAIL:${escape(contact.optString("email"))}\r\n${if (contact.optString("note").isNotBlank()) "NOTE:${escape(contact.optString("note"))}\r\n" else ""}END:VCARD\r\n"
}
private fun propfindBody(homeSet: String) = """<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
<d:prop><d:current-user-principal/><d:displayname/><c:$homeSet/><a:$homeSet/></d:prop>
</d:propfind>""".trimIndent()
private fun collectionBody() = """<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
<d:prop><d:resourcetype/><d:displayname/><d:getetag/><c:calendar-data/><a:address-data/></d:prop>
</d:propfind>""".trimIndent()
private fun parseXml(bytes: ByteArray): org.w3c.dom.Document {
val factory = DocumentBuilderFactory.newInstance().apply {
isNamespaceAware = true
isXIncludeAware = false
isExpandEntityReferences = false
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
setFeature("http://xml.org/sax/features/external-general-entities", false)
setFeature("http://xml.org/sax/features/external-parameter-entities", false)
}
return factory.newDocumentBuilder().parse(ByteArrayInputStream(bytes))
}
private fun findHref(document: org.w3c.dom.Document, propertyName: String): String? {
val elements = document.getElementsByTagNameNS("*", propertyName)
for (index in 0 until elements.length) {
val href = (elements.item(index) as? Element)?.getElementsByTagNameNS("*", "href")?.item(0)?.textContent
if (!href.isNullOrBlank()) return href.trim()
}
return null
}
private fun textContent(element: Element, propertyName: String): String? {
val nodes = element.getElementsByTagNameNS("*", propertyName)
return if (nodes.length == 0) null else nodes.item(0)?.textContent?.trim()
}
private fun childText(element: Element, childName: String): String? {
val children = element.childNodes
for (index in 0 until children.length) {
val node = children.item(index)
if (node is Element && node.localName == childName) return node.textContent.trim()
}
return null
}
private fun resolveUrl(base: String, href: String): String = URL(URL(base), href).toString()
private fun basicAuth(account: JSONObject): String {
val raw = "${account.optString("username")}:${account.optString("password")}"
return "Basic " + Base64.encodeToString(raw.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
}
private fun publicDav(account: JSONObject) = JSONObject()
.put("id", account.optString("id"))
.put("serverUrl", account.optString("serverUrl"))
.put("username", account.optString("username"))
.put("collections", account.optJSONArray("collections") ?: JSONArray())
private fun type(value: String) = if (value == "carddav") "carddav" else "caldav"
private fun findCollection(collections: JSONArray, url: String): JSONObject? {
for (index in 0 until collections.length()) {
val collection = collections.getJSONObject(index)
if (url.isBlank() || collection.optString("url") == url) return collection
}
return null
}
private fun encode(value: String) = java.net.URLEncoder.encode(value, "UTF-8")
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")
private fun unescape(value: String) = value.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")
private fun property(name: String, value: String) = if (value.isBlank()) "" else "$name:${escape(value)}\r\n"
private fun utcNow() = java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ROOT)
.apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }.format(java.util.Date())
private fun unfold(data: String) = data.replace("\r\n ", "").replace("\n ", "").replace("\r\n\t", "").replace("\n\t", "")
private fun parseProperties(block: String): Map<String, String> {
val result = LinkedHashMap<String, String>()
for (line in block.lines()) {
val colon = line.indexOf(':')
if (colon <= 0) continue
val name = line.substring(0, colon).substringBefore(';').uppercase(Locale.ROOT)
result.putIfAbsent(name, line.substring(colon + 1).trim())
}
return result
}
private fun parseDate(raw: String): Pair<String, String>? {
if (raw.isBlank()) return null
val rawValue = raw.substringAfter(':', raw)
return try {
when {
rawValue.length == 8 -> "${rawValue.substring(0, 4)}-${rawValue.substring(4, 6)}-${rawValue.substring(6, 8)}" to ""
rawValue.length >= 15 -> {
val digits = rawValue.replace("T", "").replace("Z", "").take(14)
val date = "${digits.substring(0, 4)}-${digits.substring(4, 6)}-${digits.substring(6, 8)}"
val time = "${digits.substring(8, 10)}:${digits.substring(10, 12)}"
date to time
}
else -> null
}
} catch (_: Exception) { null }
}
}
@@ -0,0 +1,455 @@
package studio.daybreak.mail
import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.Html
import android.webkit.MimeTypeMap
import com.sun.mail.imap.IMAPFolder
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.text.DateFormat
import java.util.Date
import java.util.Locale
import java.util.Properties
import java.util.UUID
import javax.mail.Address
import javax.mail.Authenticator
import javax.mail.Flags
import javax.mail.Folder
import javax.mail.Message
import javax.mail.Multipart
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.Store
import javax.mail.Transport
import javax.mail.UIDFolder
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
import javax.mail.internet.MimeUtility
internal object AndroidMailService {
data class SyncResult(val payload: JSONObject, val newCount: Int)
fun connect(account: JSONObject): JSONObject = withStore(account) { session, store ->
val inbox = store.getFolder("INBOX")
check(inbox.exists()) { "The inbox could not be found." }
inbox.open(Folder.READ_ONLY)
val count = inbox.messageCount
inbox.close(false)
val smtpSession = Session.getInstance(smtpProperties(account), credentials(account))
val transport = smtpSession.getTransport("smtp")
try {
transport.connect(
account.optString("smtpHost"),
account.optInt("smtpPort", 587),
account.optString("email"),
account.optString("password")
)
} finally {
if (transport.isConnected) transport.close()
}
JSONObject().put("mailbox", "INBOX").put("messages", count)
}
fun sync(account: JSONObject, requestedFolder: String, offset: Int): JSONObject =
withStore(account) { _, store ->
val folder = resolveFolder(store, requestedFolder)
if (folder == null) return@withStore JSONObject()
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
folder.open(Folder.READ_ONLY)
try {
val total = folder.messageCount
val end = (total - offset.coerceAtLeast(0)).coerceAtLeast(0)
if (end == 0) {
return@withStore JSONObject().put("messages", JSONArray()).put("total", total)
.put("start", 0).put("end", 0).put("folder", requestedFolder)
}
val first = (end - 19).coerceAtLeast(1)
val result = JSONArray()
val batch = folder.getMessages(first, end).reversed()
for (message in batch) {
result.put(messageJson(folder, message, requestedFolder))
}
JSONObject().put("messages", result).put("total", total)
.put("start", first).put("end", end).put("folder", requestedFolder)
} finally {
folder.close(false)
}
}
fun updateMessage(account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store ->
val uid = input.optLong("uid")
require(uid > 0) { "That message could not be identified." }
val action = input.optString("action")
require(action in setOf("star", "unread", "archive", "delete")) { "That mail action is not supported." }
val source = resolveFolder(store, input.optString("folder", "Inbox"))
?: throw IllegalStateException("That mail folder could not be found.")
var expungeDeleted = false
source.open(Folder.READ_WRITE)
try {
val message = (source as? UIDFolder)?.getMessageByUID(uid)
?: throw IllegalStateException("The message is no longer available.")
when (action) {
"star" -> message.setFlag(Flags.Flag.FLAGGED, input.optBoolean("enabled"))
"unread" -> message.setFlag(Flags.Flag.SEEN, !input.optBoolean("enabled"))
"archive", "delete" -> {
expungeDeleted = true
val targetName = if (action == "archive") "Archive" else "Trash"
val target = resolveFolder(store, targetName) ?: store.getFolder(targetName)
if (!target.exists()) target.create(Folder.HOLDS_MESSAGES)
source.copyMessages(arrayOf(message), target)
message.setFlag(Flags.Flag.DELETED, true)
}
}
} finally {
source.close(expungeDeleted)
}
JSONObject().put("ok", true)
}
fun send(account: JSONObject, input: JSONObject): JSONObject {
val recipient = input.optString("to").trim()
require(recipient.isNotEmpty()) { "Add at least one recipient." }
val properties = smtpProperties(account)
val session = Session.getInstance(properties, credentials(account))
val message = MimeMessage(session)
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
val cc = input.optString("cc").trim()
if (cc.isNotEmpty()) message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, true))
message.subject = input.optString("subject", "(no subject)")
message.setText(input.optString("text"), "UTF-8")
message.sentDate = Date()
message.saveChanges()
val transport = session.getTransport("smtp")
try {
transport.connect(
account.optString("smtpHost"),
account.optInt("smtpPort", 587),
account.optString("email"),
account.optString("password")
)
transport.sendMessage(message, message.allRecipients)
} finally {
if (transport.isConnected) transport.close()
}
var savedToSent = false
try {
withStore(account) { _, store ->
val sent = resolveFolder(store, "Sent") ?: store.getFolder("Sent")
if (!sent.exists()) sent.create(Folder.HOLDS_MESSAGES)
sent.appendMessages(arrayOf(message))
savedToSent = true
}
} catch (_: Exception) {
savedToSent = false
}
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
}
fun saveAttachment(context: Context, account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store ->
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
?: throw IllegalStateException("That mail folder could not be found.")
folder.open(Folder.READ_ONLY)
try {
val uid = input.optLong("uid")
val message = (folder as? UIDFolder)?.getMessageByUID(uid)
?: throw IllegalStateException("The message is no longer available.")
val filename = input.optString("filename")
val part = findAttachment(message, filename)
?: throw IllegalStateException("No attachment was found in this message.")
saveAttachmentBytes(context, filename.ifBlank { "attachment" }, part.contentType, part.inputStream.readBytes())
} finally {
folder.close(false)
}
}
fun checkForNewMail(account: JSONObject): Int = withStore(account) { _, store ->
val folder = store.getFolder("INBOX")
folder.open(Folder.READ_ONLY)
try {
val uidFolder = folder as? UIDFolder
?: throw IllegalStateException("The mail server does not support stable message IDs.")
val validity = uidFolder.uidValidity
val latestUid = (uidFolder.uidNext - 1).coerceAtLeast(0)
val oldState = account.optJSONObject("androidInboxSyncState")
val lastUid = if (oldState == null || oldState.optLong("uidValidity") != validity) {
AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid)
return@withStore 0
} else oldState.optLong("lastUid")
if (latestUid <= lastUid) return@withStore 0
val added = uidFolder.getMessagesByUID(lastUid + 1, UIDFolder.LASTUID)
AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid)
added.size
} finally {
folder.close(false)
}
}
fun watchInbox(
account: JSONObject,
onNewMail: (Int) -> Unit,
shouldStop: () -> Boolean,
onConnection: (Store?, Folder?) -> Unit
) {
val props = imapProperties(account).apply {
setProperty("mail.imap.timeout", "0")
setProperty("mail.imap.writetimeout", "60000")
}
val session = Session.getInstance(props, credentials(account))
val store = session.getStore("imap")
try {
store.connect(
account.optString("imapHost"),
account.optInt("imapPort", 143),
account.optString("email"),
account.optString("password")
)
val inbox = store.getFolder("INBOX")
inbox.open(Folder.READ_ONLY)
var previousCount = inbox.messageCount
val uidFolder = inbox as? UIDFolder
val uidValidity = uidFolder?.uidValidity ?: 0L
val initialUid = uidFolder?.let { (it.uidNext - 1).coerceAtLeast(0) } ?: 0L
if (uidValidity > 0) {
AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, initialUid)
}
onConnection(store, inbox)
inbox.addMessageCountListener(object : javax.mail.event.MessageCountListener {
override fun messagesAdded(event: javax.mail.event.MessageCountEvent) {
if (event.type == javax.mail.event.MessageCountEvent.ADDED) {
previousCount = maxOf(previousCount, inbox.messageCount)
val newestUid = event.messages.maxOfOrNull { message ->
try { uidFolder?.getUID(message) ?: 0L } catch (_: Exception) { 0L }
} ?: 0L
if (uidValidity > 0 && newestUid > 0) {
AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, newestUid)
}
onNewMail(event.messages.size)
}
}
override fun messagesRemoved(event: javax.mail.event.MessageCountEvent) = Unit
})
try {
var supportsIdle = inbox is IMAPFolder
while (!shouldStop()) {
try {
if (supportsIdle && inbox is IMAPFolder) {
inbox.idle()
} else {
Thread.sleep(120_000)
val currentCount = inbox.messageCount
if (currentCount > previousCount) onNewMail(currentCount - previousCount)
previousCount = currentCount
}
} catch (error: Exception) {
if (shouldStop()) break
if (error !is javax.mail.MethodNotSupportedException &&
!error.javaClass.simpleName.contains("UnsupportedCommand")) throw error
supportsIdle = false
}
}
} finally {
onConnection(null, null)
if (inbox.isOpen) inbox.close(false)
}
} finally {
if (store.isConnected) store.close()
}
}
fun accountFingerprint(account: JSONObject): String = listOf(
account.optString("email"),
account.optString("imapHost"),
account.optString("password")
).joinToString("|").hashCode().toString()
private fun messageJson(folder: Folder, message: Message, requestedFolder: String): JSONObject {
val uid = (folder as? UIDFolder)?.getUID(message) ?: message.messageNumber.toLong()
val sender = (message.from?.firstOrNull() as? InternetAddress)
val senderName = decode(sender?.personal).ifBlank { sender?.address ?: "Unknown sender" }
val senderEmail = sender?.address ?: ""
val subject = decode(message.subject).ifBlank { "(no subject)" }
val body = ArrayList<String>()
val attachments = JSONArray()
collectParts(message, body, attachments)
val bodyText = body.joinToString("\n\n").trim()
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date()
val tags = JSONArray().put(requestedFolder)
val files = attachmentList(attachments)
val flags = message.flags
val id = uid.toDouble()
return JSONObject()
.put("id", id)
.put("uid", uid)
.put("initials", senderName.split(Regex("[\\s@]+")).filter(String::isNotBlank)
.mapNotNull { it.firstOrNull()?.toString() }.joinToString("").take(2).uppercase(Locale.getDefault()))
.put("color", "#dce6df")
.put("sender", senderName)
.put("email", senderEmail)
.put("subject", subject)
.put("snippet", snippet)
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
.put("unread", !flags.contains(Flags.Flag.SEEN))
.put("star", flags.contains(Flags.Flag.FLAGGED))
.put("tags", tags)
.put("sent", requestedFolder == "Sent")
.put("archived", requestedFolder == "Archive")
.put("deleted", requestedFolder == "Trash")
.put("body", JSONArray().apply {
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
})
.put("attachments", attachments)
.put("attachment", files.firstOrNull()?.optString("filename") ?: JSONObject.NULL)
.put("size", files.firstOrNull()?.optString("size") ?: "")
}
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
(0 until attachments.length()).map { attachments.getJSONObject(it) }
private fun collectParts(part: javax.mail.Part, body: MutableList<String>, attachments: JSONArray) {
val filename = decode(part.fileName)
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
val name = filename.ifBlank { "attachment" }
val size = part.size.coerceAtLeast(0)
attachments.put(JSONObject().put("filename", name).put("size", size))
return
}
val content = try { part.content } catch (_: Exception) { return }
when (content) {
is String -> if (part.isMimeType("text/plain")) {
body.add(content.replace("\r", "").trim())
} else if (part.isMimeType("text/html") && body.isEmpty()) {
body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim())
}
is Multipart -> for (index in 0 until content.count) {
collectParts(content.getBodyPart(index), body, attachments)
}
is javax.mail.BodyPart -> collectParts(content, body, attachments)
}
}
private fun findAttachment(part: javax.mail.Part, filename: String): MimeBodyPart? {
val name = decode(part.fileName)
if ((name == filename || (filename.isBlank() && name.isNotBlank())) && part is MimeBodyPart) return part
val content = try { part.content } catch (_: Exception) { return null }
if (content is Multipart) {
for (index in 0 until content.count) {
findAttachment(content.getBodyPart(index), filename)?.let { return it }
}
}
return null
}
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
val mimeType = contentType.substringBefore(';').ifBlank {
MimeTypeMap.getSingleton().getMimeTypeFromExtension(filename.substringAfterLast('.', "")) ?: "application/octet-stream"
}
if (Build.VERSION.SDK_INT >= 29) {
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, filename)
put(MediaStore.Downloads.MIME_TYPE, mimeType)
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
val uri = context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
?: throw IllegalStateException("Could not create the attachment in Downloads.")
context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
?: throw IllegalStateException("Could not write the attachment.")
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", filename)
}
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
?: throw IllegalStateException("Downloads storage is not available.")
val file = File(directory, filename.replace(Regex("[\\\\/:*?\"<>|]"), "_"))
file.writeBytes(bytes)
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", filename)
}
private fun resolveFolder(store: Store, requested: String): Folder? {
if (requested == "Inbox" || requested == "Starred" || requested == "Snoozed") {
return store.getFolder("INBOX")
}
val (specialUse, candidates) = when (requested) {
"Sent" -> "\\Sent" to setOf("sent", "sent items", "sent mail", "sent messages")
"Archive" -> "\\Archive" to setOf("archive", "archives", "all mail")
"Trash" -> "\\Trash" to setOf("trash", "deleted items", "deleted messages")
else -> return store.getFolder(requested).takeIf { it.exists() }
}
val folders = try { store.defaultFolder.list("*") } catch (_: Exception) { emptyArray() }
return folders.firstOrNull { folder ->
val imapFolder = folder as? IMAPFolder
imapFolder?.attributes?.any { it.equals(specialUse, true) } == true
} ?: folders.firstOrNull { folder ->
folder.fullName.lowercase(Locale.ROOT).split(Regex("[./]")).lastOrNull() in candidates
}
}
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
val session = Session.getInstance(imapProperties(account), credentials(account))
val store = session.getStore("imap")
try {
store.connect(
account.optString("imapHost"),
account.optInt("imapPort", 143),
account.optString("email"),
account.optString("password")
)
return block(session, store)
} finally {
if (store.isConnected) store.close()
}
}
private fun credentials(account: JSONObject) = object : Authenticator() {
override fun getPasswordAuthentication() = PasswordAuthentication(
account.optString("email"),
account.optString("password")
)
}
private fun imapProperties(account: JSONObject) = Properties().apply {
setProperty("mail.store.protocol", "imap")
setProperty("mail.imap.host", account.optString("imapHost"))
setProperty("mail.imap.port", account.optInt("imapPort", 143).toString())
setProperty("mail.imap.auth", "true")
setProperty("mail.imap.starttls.enable", "true")
setProperty("mail.imap.starttls.required", "true")
setProperty("mail.imap.ssl.checkserveridentity", "true")
setProperty("mail.imap.connectiontimeout", "20000")
setProperty("mail.imap.timeout", "30000")
setProperty("mail.imap.writetimeout", "30000")
}
private fun smtpProperties(account: JSONObject) = Properties().apply {
setProperty("mail.smtp.host", account.optString("smtpHost"))
setProperty("mail.smtp.port", account.optInt("smtpPort", 587).toString())
setProperty("mail.smtp.auth", "true")
setProperty("mail.smtp.starttls.enable", "true")
setProperty("mail.smtp.starttls.required", "true")
setProperty("mail.smtp.ssl.checkserveridentity", "true")
setProperty("mail.smtp.connectiontimeout", "20000")
setProperty("mail.smtp.timeout", "30000")
setProperty("mail.smtp.writetimeout", "30000")
}
private fun displayName(account: JSONObject) =
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
private fun decode(value: String?): String = try {
if (value.isNullOrBlank()) "" else MimeUtility.decodeText(value)
} catch (_: Exception) {
value.orEmpty()
}
}
@@ -0,0 +1,294 @@
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 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@]+$")
}
}
@@ -0,0 +1,54 @@
package studio.daybreak.mail
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.util.concurrent.TimeUnit
class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) {
override fun doWork(): Result {
return try {
AndroidAccountVault.initialize(applicationContext)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
val newMessages = AndroidMailService.checkForNewMail(account)
if (newMessages > 0) {
MailIdleService.notifyNewMail(applicationContext, account, newMessages)
}
}
Result.success()
} catch (error: Exception) {
android.util.Log.w(TAG, "Periodic mail fallback sync failed", error)
Result.retry()
}
}
companion object {
private const val TAG = "EpMailFallback"
private const val UNIQUE_WORK_NAME = "ep-mail-periodic-sync"
fun schedule(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<MailFallbackWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context.applicationContext).enqueueUniquePeriodicWork(
UNIQUE_WORK_NAME,
ExistingPeriodicWorkPolicy.KEEP,
request
)
}
fun cancel(context: Context) {
WorkManager.getInstance(context.applicationContext).cancelUniqueWork(UNIQUE_WORK_NAME)
}
}
}
@@ -0,0 +1,227 @@
package studio.daybreak.mail
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import org.json.JSONObject
import javax.mail.Folder
import javax.mail.Store
class MailIdleService : Service() {
private data class Watcher(
val account: JSONObject,
val fingerprint: String,
val stopped: AtomicBoolean = AtomicBoolean(false),
@Volatile var store: Store? = null,
@Volatile var folder: Folder? = null,
@Volatile var thread: Thread? = null
) {
fun stop() {
stopped.set(true)
try { folder?.close(false) } catch (_: Exception) {}
try { store?.close() } catch (_: Exception) {}
thread?.interrupt()
}
}
private val watchers = ConcurrentHashMap<String, Watcher>()
override fun onCreate() {
super.onCreate()
AndroidAccountVault.initialize(applicationContext)
createNotificationChannels()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification())
Thread {
try {
reconcile()
if (watchers.isEmpty()) stopSelf(startId)
} catch (error: Exception) {
android.util.Log.e(TAG, "Could not start mailbox watchers", error)
}
}.start()
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
watchers.values.forEach(Watcher::stop)
watchers.clear()
super.onDestroy()
}
@Synchronized
private fun reconcile() {
val accounts = AndroidAccountVault.accounts()
val desired = LinkedHashMap<String, JSONObject>()
for (index in 0 until accounts.length().coerceAtMost(MAX_WATCHERS)) {
val account = accounts.getJSONObject(index)
desired[account.optString("id")] = account
}
for ((id, watcher) in watchers) {
val account = desired[id]
if (account == null || AndroidMailService.accountFingerprint(account) != watcher.fingerprint) {
watcher.stop()
watchers.remove(id, watcher)
}
}
for ((id, account) in desired) {
if (!watchers.containsKey(id)) startWatcher(id, account)
}
}
private fun startWatcher(id: String, account: JSONObject) {
val watcher = Watcher(account, AndroidMailService.accountFingerprint(account))
watchers[id] = watcher
val thread = Thread({
var failures = 0
while (!watcher.stopped.get()) {
try {
AndroidMailService.watchInbox(
account = account,
onNewMail = { count -> onNewMail(account, count) },
shouldStop = { watcher.stopped.get() },
onConnection = { store, folder ->
watcher.store = store
watcher.folder = folder
}
)
failures = 0
} catch (error: Exception) {
if (!watcher.stopped.get()) android.util.Log.w(TAG, "IMAP watcher disconnected for ${account.optString("email")}", error)
failures += 1
} finally {
watcher.folder = null
watcher.store = null
}
if (!watcher.stopped.get()) {
val delayMs = (15_000L * (1L shl failures.coerceAtMost(5))).coerceAtMost(5 * 60_000L)
try {
Thread.sleep(delayMs)
} catch (_: InterruptedException) {
if (watcher.stopped.get()) break
}
}
}
}, "ep-mail-idle-$id")
thread.isDaemon = true
watcher.thread = thread
thread.start()
}
private fun onNewMail(account: JSONObject, count: Int) {
notifyNewMail(this, account, count)
}
private fun foregroundNotification(): Notification = NotificationCompat.Builder(this, SERVICE_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle(getString(R.string.app_name))
.setContentText("Checking mail in the background")
.setContentIntent(appPendingIntent())
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build()
private fun appPendingIntent(): PendingIntent {
val intent = packageManager.getLaunchIntentForPackage(packageName)
?: Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
private fun createNotificationChannels() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(NotificationChannel(
SERVICE_CHANNEL_ID,
"Background mail sync",
NotificationManager.IMPORTANCE_LOW
).apply { description = "Keeps mail synchronized in the background." })
manager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"New mail",
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = "Notifies you when new mail arrives." })
}
companion object {
const val ACTION_MAIL_SYNC = "studio.daybreak.mail.MAIL_SYNC_UPDATE"
const val EXTRA_SYNC_UPDATE = "syncUpdate"
private const val TAG = "EpMailIdle"
private const val MAX_WATCHERS = 2
private const val FOREGROUND_NOTIFICATION_ID = 3410
private const val SERVICE_CHANNEL_ID = "mail-sync-service"
private const val MAIL_CHANNEL_ID = "mail-new-message"
fun start(context: Context) {
AndroidAccountVault.initialize(context)
if (AndroidAccountVault.accounts().length() == 0) return
MailFallbackWorker.schedule(context)
val intent = Intent(context, MailIdleService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
else context.startService(intent)
}
fun stop(context: Context) {
context.stopService(Intent(context, MailIdleService::class.java))
MailFallbackWorker.cancel(context)
}
fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
if (count <= 0) return
val appContext = context.applicationContext
val email = account.optString("email")
val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
notificationManager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"New mail",
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = "Notifies you when new mail arrives." })
}
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("newCount", count)
.put("foldersChanged", org.json.JSONArray().put("Inbox"))
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
.setPackage(appContext.packageName)
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
?: Intent(appContext, MainActivity::class.java)
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
appContext, 0, launchIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val title = if (count == 1) "New mail" else "$count new messages"
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle(title)
.setContentText(email)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.build()
try {
NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification)
} catch (error: SecurityException) {
android.util.Log.w(TAG, "Notification permission is unavailable", error)
}
}
}
}
@@ -0,0 +1,19 @@
package studio.daybreak.mail;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(EpMailPlugin.class);
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">ep-mail</string>
<string name="title_activity_main">ep-mail</string>
<string name="package_name">studio.daybreak.mail</string>
<string name="custom_url_scheme">studio.daybreak.mail</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -0,0 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}