diff --git a/README.md b/README.md index 6bdbe08..9300447 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,17 @@ The Electron app runs in its own window. With Node.js installed, run `npm instal The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. +## Android app + +The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run: + +```sh +npm install +npm run android:apk +``` + +The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk`. Install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`, or open the project in Android Studio with `npm run android:open`. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management. + ## Run on Windows or Linux Install Python 3, open a terminal in this folder, and run: diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..48354a3 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,101 @@ +# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore + +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +# Uncomment the following line in case you need and you don't have the release build type files in your app +# release/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# IntelliJ +*.iml +.idea/workspace.xml +.idea/tasks.xml +.idea/gradle.xml +.idea/assetWizardSettings.xml +.idea/dictionaries +.idea/libraries +# Android Studio 3 in .gitignore file. +.idea/caches +.idea/modules.xml +# Comment next line if keeping position of elements in Navigation Editor is relevant for you +.idea/navEditor.xml + +# Keystore files +# Uncomment the following lines if you do not want to check your keystore files in. +#*.jks +#*.keystore + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild +.cxx/ + +# Google Services (e.g. APIs or Firebase) +# google-services.json + +# Freeline +freeline.py +freeline/ +freeline_project_description.json + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output +fastlane/readme.md + +# Version control +vcs.xml + +# lint +lint/intermediates/ +lint/generated/ +lint/outputs/ +lint/tmp/ +# lint/reports/ + +# Android Profiling +*.hprof + +# Cordova plugins for Capacitor +capacitor-cordova-android-plugins + +# Copied web assets +app/src/main/assets/public + +# Generated Config files +app/src/main/assets/capacitor.config.json +app/src/main/assets/capacitor.plugins.json +app/src/main/res/xml/config.xml diff --git a/android/app/.gitignore b/android/app/.gitignore new file mode 100644 index 0000000..043df80 --- /dev/null +++ b/android/app/.gitignore @@ -0,0 +1,2 @@ +/build/* +!/build/.npmkeep diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..6fa9c30 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,78 @@ +apply plugin: 'com.android.application' +apply plugin: 'org.jetbrains.kotlin.android' + +def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version +def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() } + +android { + namespace = "studio.daybreak.mail" + compileSdk = rootProject.ext.compileSdkVersion + buildFeatures { + buildConfig true + } + packaging { + resources { + pickFirsts += "META-INF/NOTICE.md" + pickFirsts += "META-INF/LICENSE.md" + } + } + defaultConfig { + applicationId "studio.daybreak.mail" + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode appVersionParts[0] * 10000 + appVersionParts[1] * 100 + appVersionParts[2] + versionName appVersion + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + aaptOptions { + // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. + // Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61 + ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' + } + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_21 + targetCompatibility JavaVersion.VERSION_21 + } + kotlinOptions { + jvmTarget = '21' + } +} + +repositories { + flatDir{ + dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs' + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" + implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" + implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" + implementation project(':capacitor-android') + implementation 'com.sun.mail:android-mail:1.6.7' + implementation 'com.sun.mail:android-activation:1.6.7' + implementation 'com.squareup.okhttp3:okhttp:4.12.0' + implementation 'androidx.work:work-runtime-ktx:2.10.1' + testImplementation "junit:junit:$junitVersion" + androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion" + androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion" + implementation project(':capacitor-cordova-android-plugins') +} + +apply from: 'capacitor.build.gradle' + +try { + def servicesJSON = file('google-services.json') + if (servicesJSON.text) { + apply plugin: 'com.google.gms.google-services' + } +} catch(Exception e) { + logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work") +} diff --git a/android/app/capacitor.build.gradle b/android/app/capacitor.build.gradle new file mode 100644 index 0000000..bbfb44f --- /dev/null +++ b/android/app/capacitor.build.gradle @@ -0,0 +1,19 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN + +android { + compileOptions { + sourceCompatibility JavaVersion.VERSION_21 + targetCompatibility JavaVersion.VERSION_21 + } +} + +apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle" +dependencies { + + +} + + +if (hasProperty('postBuildExtras')) { + postBuildExtras() +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java b/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java new file mode 100644 index 0000000..f2c2217 --- /dev/null +++ b/android/app/src/androidTest/java/com/getcapacitor/myapp/ExampleInstrumentedTest.java @@ -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 Testing documentation + */ +@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()); + } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..5377c57 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt new file mode 100644 index 0000000..cb73bb4 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt @@ -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() + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidDavService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidDavService.kt new file mode 100644 index 0000000..d9e8948 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidDavService.kt @@ -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) + + private fun request( + account: JSONObject, + address: String, + method: String, + body: String?, + headers: Map = 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 { + 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() + 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 { + 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 { + 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) = """ + + + """.trimIndent() + + private fun collectionBody() = """ + + + """.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 { + val result = LinkedHashMap() + 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? { + 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 } + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt new file mode 100644 index 0000000..c7288ab --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -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() + 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 = + (0 until attachments.length()).map { attachments.getJSONObject(it) } + + private fun collectParts(part: javax.mail.Part, body: MutableList, 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 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() + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt new file mode 100644 index 0000000..9ab1209 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -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@]+$") + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/MailFallbackWorker.kt b/android/app/src/main/java/studio/daybreak/mail/MailFallbackWorker.kt new file mode 100644 index 0000000..e8bfe43 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/MailFallbackWorker.kt @@ -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(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) + } + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt b/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt new file mode 100644 index 0000000..fccbce5 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/MailIdleService.kt @@ -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() + + 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() + 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) + } + } + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/MainActivity.java b/android/app/src/main/java/studio/daybreak/mail/MainActivity.java new file mode 100644 index 0000000..3f4ac5d --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/MainActivity.java @@ -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); + } + } +} diff --git a/android/app/src/main/res/drawable-land-hdpi/splash.png b/android/app/src/main/res/drawable-land-hdpi/splash.png new file mode 100644 index 0000000..e31573b Binary files /dev/null and b/android/app/src/main/res/drawable-land-hdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-land-mdpi/splash.png b/android/app/src/main/res/drawable-land-mdpi/splash.png new file mode 100644 index 0000000..f7a6492 Binary files /dev/null and b/android/app/src/main/res/drawable-land-mdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-land-xhdpi/splash.png b/android/app/src/main/res/drawable-land-xhdpi/splash.png new file mode 100644 index 0000000..8077255 Binary files /dev/null and b/android/app/src/main/res/drawable-land-xhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-land-xxhdpi/splash.png b/android/app/src/main/res/drawable-land-xxhdpi/splash.png new file mode 100644 index 0000000..14c6c8f Binary files /dev/null and b/android/app/src/main/res/drawable-land-xxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-land-xxxhdpi/splash.png b/android/app/src/main/res/drawable-land-xxxhdpi/splash.png new file mode 100644 index 0000000..244ca25 Binary files /dev/null and b/android/app/src/main/res/drawable-land-xxxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-hdpi/splash.png b/android/app/src/main/res/drawable-port-hdpi/splash.png new file mode 100644 index 0000000..74faaa5 Binary files /dev/null and b/android/app/src/main/res/drawable-port-hdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-mdpi/splash.png b/android/app/src/main/res/drawable-port-mdpi/splash.png new file mode 100644 index 0000000..e944f4a Binary files /dev/null and b/android/app/src/main/res/drawable-port-mdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-xhdpi/splash.png b/android/app/src/main/res/drawable-port-xhdpi/splash.png new file mode 100644 index 0000000..564a82f Binary files /dev/null and b/android/app/src/main/res/drawable-port-xhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-xxhdpi/splash.png b/android/app/src/main/res/drawable-port-xxhdpi/splash.png new file mode 100644 index 0000000..bfabe68 Binary files /dev/null and b/android/app/src/main/res/drawable-port-xxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-port-xxxhdpi/splash.png b/android/app/src/main/res/drawable-port-xxxhdpi/splash.png new file mode 100644 index 0000000..6929071 Binary files /dev/null and b/android/app/src/main/res/drawable-port-xxxhdpi/splash.png differ diff --git a/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..c7bd21d --- /dev/null +++ b/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..d5fccc5 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/splash.png b/android/app/src/main/res/drawable/splash.png new file mode 100644 index 0000000..f7a6492 Binary files /dev/null and b/android/app/src/main/res/drawable/splash.png differ diff --git a/android/app/src/main/res/layout/activity_main.xml b/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..b5ad138 --- /dev/null +++ b/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..036d09b --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..036d09b --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..c023e50 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..2127973 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..b441f37 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..72905b8 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..8ed0605 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..9502e47 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..4d1e077 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..df0f158 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..853db04 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..6cdf97c Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..2960cbb Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..8e3093a Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..46de6e2 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..d2ea9ab Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..a40d73e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/android/app/src/main/res/values/ic_launcher_background.xml b/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..c5d5899 --- /dev/null +++ b/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..51a7fb9 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ + + + ep-mail + ep-mail + studio.daybreak.mail + studio.daybreak.mail + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..be874e5 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/xml/file_paths.xml b/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..bd0c4d8 --- /dev/null +++ b/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java b/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java new file mode 100644 index 0000000..0297327 --- /dev/null +++ b/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java @@ -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 Testing documentation + */ +public class ExampleUnitTest { + + @Test + public void addition_isCorrect() throws Exception { + assertEquals(4, 2 + 2); + } +} diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..df428a0 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,30 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.13.0' + classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21' + classpath 'com.google.gms:google-services:4.4.4' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +apply from: "variables.gradle" + +allprojects { + repositories { + google() + mavenCentral() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android/capacitor.settings.gradle b/android/capacitor.settings.gradle new file mode 100644 index 0000000..9a5fa87 --- /dev/null +++ b/android/capacitor.settings.gradle @@ -0,0 +1,3 @@ +// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN +include ':capacitor-android' +project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor') diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..2e87c52 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,22 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7705927 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..3b4431d --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,5 @@ +include ':app' +include ':capacitor-cordova-android-plugins' +project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/') + +apply from: 'capacitor.settings.gradle' \ No newline at end of file diff --git a/android/variables.gradle b/android/variables.gradle new file mode 100644 index 0000000..ee4ba41 --- /dev/null +++ b/android/variables.gradle @@ -0,0 +1,16 @@ +ext { + minSdkVersion = 24 + compileSdkVersion = 36 + targetSdkVersion = 36 + androidxActivityVersion = '1.11.0' + androidxAppCompatVersion = '1.7.1' + androidxCoordinatorLayoutVersion = '1.3.0' + androidxCoreVersion = '1.17.0' + androidxFragmentVersion = '1.8.9' + coreSplashScreenVersion = '1.2.0' + androidxWebkitVersion = '1.14.0' + junitVersion = '4.13.2' + androidxJunitVersion = '1.3.0' + androidxEspressoCoreVersion = '3.7.0' + cordovaAndroidVersion = '14.0.1' +} \ No newline at end of file diff --git a/capacitor.config.json b/capacitor.config.json new file mode 100644 index 0000000..0f7ba5a --- /dev/null +++ b/capacitor.config.json @@ -0,0 +1,8 @@ +{ + "appId": "studio.daybreak.mail", + "appName": "ep-mail", + "webDir": "www", + "server": { + "androidScheme": "https" + } +} diff --git a/index.html b/index.html index 2f1d21a..3d1670d 100644 --- a/index.html +++ b/index.html @@ -62,6 +62,7 @@
+ diff --git a/package-lock.json b/package-lock.json index 7dbe89e..29b5e0b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,8 @@ "name": "ep-mail", "version": "0.1.16", "dependencies": { + "@capacitor/android": "^8.5.2", + "@capacitor/core": "^8.5.2", "ical.js": "^2.2.1", "imapflow": "2.2.1", "mailparser": "3.9.33", @@ -15,8 +17,135 @@ "tsdav": "^2.3.4" }, "devDependencies": { + "@capacitor/cli": "^8.5.2", "electron": "44.5.1", - "electron-builder": "26.17.0" + "electron-builder": "26.17.0", + "esbuild": "^0.28.2" + } + }, + "node_modules/@capacitor/android": { + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/@capacitor/android/-/android-8.5.2.tgz", + "integrity": "sha512-rtiaz78egCcS+vs29wkWCL3C+RhazKMSygXcjutwWP8NmO6r5UBxOvGf3Wjz5+ahobyQ723tn9gCePwRwcNDZQ==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^8.5.0" + } + }, + "node_modules/@capacitor/cli": { + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/@capacitor/cli/-/cli-8.5.2.tgz", + "integrity": "sha512-O2kpA5ZPJUAmliDCcmpMf8xnJwMezxlFPUrlyOAjbL3U9MFNY3l4ZpPI/UXwvyPmR8ETcVF9pFr+VdWq61rqTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/cli-framework-output": "^2.2.8", + "@ionic/utils-subprocess": "^3.0.1", + "@ionic/utils-terminal": "^2.3.5", + "commander": "^12.1.0", + "debug": "^4.4.0", + "env-paths": "^2.2.0", + "fs-extra": "^11.2.0", + "kleur": "^4.1.5", + "native-run": "^2.0.3", + "open": "^8.4.0", + "plist": "^3.1.0", + "prompts": "^2.4.2", + "rimraf": "^6.0.1", + "semver": "^7.6.3", + "tar": "^7.5.3", + "tslib": "^2.8.1", + "xcode": "^3.0.1", + "xml2js": "^0.6.2" + }, + "bin": { + "cap": "bin/capacitor", + "capacitor": "bin/capacitor" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@capacitor/cli/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@capacitor/cli/node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/@capacitor/cli/node_modules/fs-extra": { + "version": "11.4.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz", + "integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/@capacitor/cli/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@capacitor/cli/node_modules/rimraf": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-6.1.3.tgz", + "integrity": "sha512-LKg+Cr2ZF61fkcaK1UdkH2yEBBKnYjTyWzTJT6KNPcSPaiT7HSdhtMXQuN5wkTX0Xu72KQ1l8S42rlmexS2hSA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "glob": "^13.0.3", + "package-json-from-dist": "^1.0.1" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@capacitor/core": { + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/@capacitor/core/-/core-8.5.2.tgz", + "integrity": "sha512-agnQbGdhGw/KZFuLf7H9SY2o+oE7upkr/WPQsYaokXP6f9chaE8iVmbKkfN6SVl4w3pmz7oZ3Ur1hbkmy1hx+w==", + "license": "MIT", + "dependencies": { + "tslib": "^2.1.0" } }, "node_modules/@electron-internal/extract-zip": { @@ -323,6 +452,606 @@ "node": ">=14.14" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@ionic/cli-framework-output": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/@ionic/cli-framework-output/-/cli-framework-output-2.2.8.tgz", + "integrity": "sha512-TshtaFQsovB4NWRBydbNFawql6yul7d5bMiW1WYYf17hd99V6xdDdk3vtF51bw6sLkxON3bDQpWsnUc9/hVo3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-terminal": "2.3.5", + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-array": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@ionic/utils-array/-/utils-array-2.1.6.tgz", + "integrity": "sha512-0JZ1Zkp3wURnv8oq6Qt7fMPo5MpjbLoUoa9Bu2Q4PJuSDWM8H8gwF3dQO7VTeUj3/0o1IB1wGkFWZZYgUXZMUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-fs": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@ionic/utils-fs/-/utils-fs-3.1.7.tgz", + "integrity": "sha512-2EknRvMVfhnyhL1VhFkSLa5gOcycK91VnjfrTB0kbqkTFCOXyXgVLI5whzq7SLrgD9t1aqos3lMMQyVzaQ5gVA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/fs-extra": "^8.0.0", + "debug": "^4.0.0", + "fs-extra": "^9.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-fs/node_modules/@types/fs-extra": { + "version": "8.1.5", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-8.1.5.tgz", + "integrity": "sha512-0dzKcwO+S8s2kuF5Z9oUWatQJj5Uq/iqphEtE3GQJVRRYm/tD1LglU2UnXi2A8jLq5umkGouOXOR9y0n613ZwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@ionic/utils-fs/node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@ionic/utils-object": { + "version": "2.1.6", + "resolved": "https://registry.npmjs.org/@ionic/utils-object/-/utils-object-2.1.6.tgz", + "integrity": "sha512-vCl7sl6JjBHFw99CuAqHljYJpcE88YaH2ZW4ELiC/Zwxl5tiwn4kbdP/gxi2OT3MQb1vOtgAmSNRtusvgxI8ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-process": { + "version": "2.1.12", + "resolved": "https://registry.npmjs.org/@ionic/utils-process/-/utils-process-2.1.12.tgz", + "integrity": "sha512-Jqkgyq7zBs/v/J3YvKtQQiIcxfJyplPgECMWgdO0E1fKrrH8EF0QGHNJ9mJCn6PYe2UtHNS8JJf5G21e09DfYg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-object": "2.1.6", + "@ionic/utils-terminal": "2.3.5", + "debug": "^4.0.0", + "signal-exit": "^3.0.3", + "tree-kill": "^1.2.2", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-stream": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@ionic/utils-stream/-/utils-stream-3.1.7.tgz", + "integrity": "sha512-eSELBE7NWNFIHTbTC2jiMvh1ABKGIpGdUIvARsNPMNQhxJB3wpwdiVnoBoTYp+5a6UUIww4Kpg7v6S7iTctH1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-subprocess": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@ionic/utils-subprocess/-/utils-subprocess-3.0.1.tgz", + "integrity": "sha512-cT4te3AQQPeIM9WCwIg8ohroJ8TjsYaMb2G4ZEgv9YzeDqHZ4JpeIKqG2SoaA3GmVQ3sOfhPM6Ox9sxphV/d1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-array": "2.1.6", + "@ionic/utils-fs": "3.1.7", + "@ionic/utils-process": "2.1.12", + "@ionic/utils-stream": "3.1.7", + "@ionic/utils-terminal": "2.3.5", + "cross-spawn": "^7.0.3", + "debug": "^4.0.0", + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@ionic/utils-terminal": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@ionic/utils-terminal/-/utils-terminal-2.3.5.tgz", + "integrity": "sha512-3cKScz9Jx2/Pr9ijj1OzGlBDfcmx7OMVBt4+P1uRR0SSW4cm1/y3Mo4OY3lfkuaYifMNBW8Wz6lQHbs1bihr7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/slice-ansi": "^4.0.0", + "debug": "^4.0.0", + "signal-exit": "^3.0.3", + "slice-ansi": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "tslib": "^2.0.1", + "untildify": "^4.0.0", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/@isaacs/fs-minipass": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", @@ -584,6 +1313,13 @@ "@types/node": "*" } }, + "node_modules/@types/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@types/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-+OpjSaq85gvlZAYINyzKpLeiFkSC4EsC6IIiT6v6TLSU5k5U83fHGj9Lel8oKEXM0HqgrMVCjXPDPVICtxF7EQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@xmldom/xmldom": { "version": "0.8.15", "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.15.tgz", @@ -853,6 +1589,16 @@ "node": ">=12.0.0" } }, + "node_modules/astral-regex": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", + "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/async": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", @@ -934,6 +1680,16 @@ ], "license": "MIT" }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "dev": true, + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, "node_modules/bluebird": { "version": "3.7.2", "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", @@ -950,6 +1706,29 @@ "license": "MIT", "optional": true }, + "node_modules/bplist-creator": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/bplist-creator/-/bplist-creator-0.1.0.tgz", + "integrity": "sha512-sXaHZicyEEmY86WyueLTQesbeoH/mquvarJaQNbjuOQO+7gbFcDEWqKmcWA4cOTLzFlfgvkiVxolk1k5bBIpmg==", + "dev": true, + "license": "MIT", + "dependencies": { + "stream-buffers": "2.2.x" + } + }, + "node_modules/bplist-parser": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.3.2.tgz", + "integrity": "sha512-apC2+fspHGI3mMKj+dGevkGo/tCqVB8jMb6i+OX+E29p0Iposz07fABkRIfVUPNd5A5VbuOz1bZbnmkKLYF+wQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "big-integer": "1.6.x" + }, + "engines": { + "node": ">= 5.10.0" + } + }, "node_modules/brace-expansion": { "version": "5.0.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", @@ -963,6 +1742,16 @@ "node": "20 || >=22" } }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -1349,6 +2138,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/define-lazy-prop": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", + "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/define-properties": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", @@ -1702,6 +2501,26 @@ "node": ">= 4.0.0" } }, + "node_modules/elementtree": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/elementtree/-/elementtree-0.1.7.tgz", + "integrity": "sha512-wkgGT6kugeQk/P6VZ/f4T+4HB41BVgNBq5CDIZVbQ02nvTVqAiVTbskxxu3eA/X96lMlfYOwnLQpN2v5E1zDEg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "sax": "1.1.4" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/elementtree/node_modules/sax": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.1.4.tgz", + "integrity": "sha512-5f3k2PbGGp+YtKJjOItpg3P99IMD84E4HOvcfleTb5joCHNXYLsR9yWFPOYGgaeMPDubQILTCMdsFb2OMeOjtg==", + "dev": true, + "license": "ISC" + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -1817,6 +2636,48 @@ "license": "MIT", "optional": true }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -1872,6 +2733,16 @@ ], "license": "BSD-3-Clause" }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + } + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -2427,6 +3298,16 @@ "dev": true, "license": "ISC" }, + "node_modules/ini": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.3.tgz", + "integrity": "sha512-X7rqawQBvfdjS10YU1y1YVreA3SsLrW9dX2CewP2EbBJM4ypVNLDkO5y04gejPwKIY9lR+7r9gn3rFPt/kmWFg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/ip-address": { "version": "10.7.3", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz", @@ -2436,6 +3317,22 @@ "node": ">= 12" } }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -2446,6 +3343,19 @@ "node": ">=8" } }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/isarray": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", @@ -2585,6 +3495,16 @@ "json-buffer": "3.0.1" } }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/lazy-val": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/lazy-val/-/lazy-val-1.0.5.tgz", @@ -2843,6 +3763,32 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "license": "MIT" }, + "node_modules/native-run": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/native-run/-/native-run-2.0.3.tgz", + "integrity": "sha512-U1PllBuzW5d1gfan+88L+Hky2eZx+9gv3Pf6rNBxKbORxi7boHzqiA6QFGSnqMem4j0A9tZ08NMIs5+0m/VS1Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@ionic/utils-fs": "^3.1.7", + "@ionic/utils-terminal": "^2.3.4", + "bplist-parser": "^0.3.2", + "debug": "^4.3.4", + "elementtree": "^0.1.7", + "ini": "^4.1.1", + "plist": "^3.1.0", + "split2": "^4.2.0", + "through2": "^4.0.2", + "tslib": "^2.6.2", + "yauzl": "^2.10.0" + }, + "bin": { + "native-run": "bin/native-run" + }, + "engines": { + "node": ">=16.0.0" + } + }, "node_modules/node-abi": { "version": "4.35.0", "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-4.35.0.tgz", @@ -3012,6 +3958,24 @@ "wrappy": "1" } }, + "node_modules/open": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz", + "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-lazy-prop": "^2.0.0", + "is-docker": "^2.1.1", + "is-wsl": "^2.2.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/p-cancelable": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz", @@ -3038,6 +4002,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/parseley": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/parseley/-/parseley-0.13.1.tgz", @@ -3071,6 +4042,33 @@ "node": ">=8" } }, + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/pe-library": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz", @@ -3095,6 +4093,13 @@ "url": "https://github.com/sponsors/KillyMXI" } }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -3275,6 +4280,30 @@ "node": ">=10" } }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/prompts/node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/proper-lockfile": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", @@ -3607,6 +4636,31 @@ "dev": true, "license": "ISC" }, + "node_modules/simple-plist": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/simple-plist/-/simple-plist-1.3.1.tgz", + "integrity": "sha512-iMSw5i0XseMnrhtIzRb7XpQEXepa9xhWxGUojHBL43SIpQuDQkh3Wpy67ZbDzZVr6EKxvwVChnVpdl8hEVLDiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "bplist-creator": "0.1.0", + "bplist-parser": "0.3.1", + "plist": "^3.0.5" + } + }, + "node_modules/simple-plist/node_modules/bplist-parser": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.3.1.tgz", + "integrity": "sha512-PyJxiNtA5T2PlLIeBot4lbp7rj4OadzjnMZD/G5zuBNt8ei/yCU7+wW0h2bag9vr8c+/WuRWmSxbqAl9hL1rBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "big-integer": "1.6.x" + }, + "engines": { + "node": ">= 5.10.0" + } + }, "node_modules/simple-update-notifier": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", @@ -3620,6 +4674,31 @@ "node": ">=10" } }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/slice-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", + "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "astral-regex": "^2.0.0", + "is-fullwidth-code-point": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, "node_modules/smart-buffer": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", @@ -3701,6 +4780,16 @@ "node": ">= 6" } }, + "node_modules/stream-buffers": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/stream-buffers/-/stream-buffers-2.2.0.tgz", + "integrity": "sha512-uyQK/mx5QjHun80FLJTfaWE7JtwfRMKBLkMne6udYOmvH0CawotVa7TfgYHzAnpphn4+TweIx1QKMnRIbipmUg==", + "dev": true, + "license": "Unlicense", + "engines": { + "node": ">= 0.10.0" + } + }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -3836,6 +4925,31 @@ "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", "license": "MIT" }, + "node_modules/through2": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/through2/-/through2-4.0.2.tgz", + "integrity": "sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "readable-stream": "3" + } + }, + "node_modules/through2/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/tiny-async-pool": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/tiny-async-pool/-/tiny-async-pool-1.3.0.tgz", @@ -3902,6 +5016,16 @@ "tmp": "^0.2.0" } }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "license": "MIT", + "bin": { + "tree-kill": "cli.js" + } + }, "node_modules/truncate-utf8-bytes": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/truncate-utf8-bytes/-/truncate-utf8-bytes-1.0.2.tgz", @@ -3929,7 +5053,6 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, "license": "0BSD" }, "node_modules/type-fest": { @@ -3980,6 +5103,16 @@ "node": ">= 10.0.0" } }, + "node_modules/untildify": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/untildify/-/untildify-4.0.0.tgz", + "integrity": "sha512-KK8xQ1mkzZeg9inewmFVDNkg3l5LUhoq9kN6iWYB/CC9YMG8HA+c1Q8HwDe6dEX7kErrEVNVBO3fWsVq5iDgtw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/unzipper": { "version": "0.12.5", "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.12.5.tgz", @@ -4023,6 +5156,17 @@ "dev": true, "license": "MIT" }, + "node_modules/uuid": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-7.0.3.tgz", + "integrity": "sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==", + "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).", + "dev": true, + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/webcrypto-core": { "version": "1.9.2", "resolved": "https://registry.npmjs.org/webcrypto-core/-/webcrypto-core-1.9.2.tgz", @@ -4078,6 +5222,20 @@ "dev": true, "license": "ISC" }, + "node_modules/xcode": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/xcode/-/xcode-3.0.1.tgz", + "integrity": "sha512-kCz5k7J7XbJtjABOvkc5lJmkiDh8VhjVCGNiqdKCscmVpdVUpEAyXv1xmCLkQJ5dsHqx3IPO4XW+NTDhU/fatA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "simple-plist": "^1.1.0", + "uuid": "^7.0.3" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/xml-js": { "version": "1.6.11", "resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz", @@ -4090,6 +5248,30 @@ "xml-js": "bin/cli.js" } }, + "node_modules/xml2js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", + "dev": true, + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xml2js/node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, "node_modules/xmlbuilder": { "version": "15.1.1", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", @@ -4146,6 +5328,17 @@ "node": ">=12" } }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/package.json b/package.json index 191de7d..14c0eef 100644 --- a/package.json +++ b/package.json @@ -15,11 +15,17 @@ "dist:linux": "electron-builder --linux AppImage deb", "dist:linux:appimage": "electron-builder --linux AppImage", "dist:linux:deb": "electron-builder --linux deb", - "bump:build": "npm version patch --no-git-tag-version" + "bump:build": "npm version patch --no-git-tag-version", + "build:android-web": "node scripts/prepare-android-web.cjs", + "android:sync": "npm run build:android-web && cap sync android", + "android:open": "npm run android:sync && cap open android", + "android:apk": "npm run android:sync && node scripts/build-android-apk.cjs" }, "devDependencies": { + "@capacitor/cli": "^8.5.2", "electron": "44.5.1", - "electron-builder": "26.17.0" + "electron-builder": "26.17.0", + "esbuild": "^0.28.2" }, "build": { "appId": "studio.daybreak.mail", @@ -27,6 +33,7 @@ "asar": true, "files": [ "index.html", + "platform-bridge.js", "styles.css", "branding.css", "app.js", @@ -71,6 +78,8 @@ "electron-winstaller@5.4.0": true }, "dependencies": { + "@capacitor/android": "^8.5.2", + "@capacitor/core": "^8.5.2", "ical.js": "^2.2.1", "imapflow": "2.2.1", "mailparser": "3.9.33", diff --git a/platform-bridge.js b/platform-bridge.js new file mode 100644 index 0000000..49611ec --- /dev/null +++ b/platform-bridge.js @@ -0,0 +1,545 @@ +(() => { + // node_modules/@capacitor/core/dist/index.js + var ExceptionCode; + (function(ExceptionCode2) { + ExceptionCode2["Unimplemented"] = "UNIMPLEMENTED"; + ExceptionCode2["Unavailable"] = "UNAVAILABLE"; + })(ExceptionCode || (ExceptionCode = {})); + var CapacitorException = class extends Error { + constructor(message, code, data) { + super(message); + this.message = message; + this.code = code; + this.data = data; + } + }; + var getPlatformId = (win) => { + var _a, _b; + if (win === null || win === void 0 ? void 0 : win.androidBridge) { + return "android"; + } else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) { + return "ios"; + } else { + return "web"; + } + }; + var createCapacitor = (win) => { + const capCustomPlatform = win.CapacitorCustomPlatform || null; + const cap = win.Capacitor || {}; + const Plugins = cap.Plugins = cap.Plugins || {}; + const getPlatform = () => { + return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win); + }; + const isNativePlatform = () => getPlatform() !== "web"; + const isPluginAvailable = (pluginName) => { + const plugin = registeredPlugins.get(pluginName); + if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) { + return true; + } + if (getPluginHeader(pluginName)) { + return true; + } + return false; + }; + const getPluginHeader = (pluginName) => { + var _a; + return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find((h) => h.name === pluginName); + }; + const handleError = (err) => win.console.error(err); + const registeredPlugins = /* @__PURE__ */ new Map(); + const registerPlugin2 = (pluginName, jsImplementations = {}) => { + const registeredPlugin = registeredPlugins.get(pluginName); + if (registeredPlugin) { + console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`); + return registeredPlugin.proxy; + } + const platform = getPlatform(); + const pluginHeader = getPluginHeader(pluginName); + let jsImplementation; + const loadPluginImplementation = async () => { + if (!jsImplementation && platform in jsImplementations) { + jsImplementation = typeof jsImplementations[platform] === "function" ? jsImplementation = await jsImplementations[platform]() : jsImplementation = jsImplementations[platform]; + } else if (capCustomPlatform !== null && !jsImplementation && "web" in jsImplementations) { + jsImplementation = typeof jsImplementations["web"] === "function" ? jsImplementation = await jsImplementations["web"]() : jsImplementation = jsImplementations["web"]; + } + return jsImplementation; + }; + const createPluginMethod = (impl, prop) => { + var _a, _b; + if (pluginHeader) { + const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find((m) => prop === m.name); + if (methodHeader) { + if (methodHeader.rtype === "promise") { + return (options) => cap.nativePromise(pluginName, prop.toString(), options); + } else { + return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback); + } + } else if (impl) { + return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl); + } + } else if (impl) { + return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl); + } else { + throw new CapacitorException(`"${pluginName}" plugin is not implemented on ${platform}`, ExceptionCode.Unimplemented); + } + }; + const createPluginMethodWrapper = (prop) => { + let remove; + const wrapper = (...args) => { + const p = loadPluginImplementation().then((impl) => { + const fn = createPluginMethod(impl, prop); + if (fn) { + const p2 = fn(...args); + remove = p2 === null || p2 === void 0 ? void 0 : p2.remove; + return p2; + } else { + throw new CapacitorException(`"${pluginName}.${prop}()" is not implemented on ${platform}`, ExceptionCode.Unimplemented); + } + }); + if (prop === "addListener") { + p.remove = async () => remove(); + } + return p; + }; + wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`; + Object.defineProperty(wrapper, "name", { + value: prop, + writable: false, + configurable: false + }); + return wrapper; + }; + const addListener = createPluginMethodWrapper("addListener"); + const removeListener = createPluginMethodWrapper("removeListener"); + const addListenerNative = (eventName, callback) => { + const call = addListener({ eventName }, callback); + const remove = async () => { + const callbackId = await call; + removeListener({ + eventName, + callbackId + }, callback); + }; + const p = new Promise((resolve) => call.then(() => resolve({ remove }))); + p.remove = async () => { + console.warn(`Using addListener() without 'await' is deprecated.`); + await remove(); + }; + return p; + }; + const proxy = new Proxy({}, { + get(_, prop) { + switch (prop) { + // https://github.com/facebook/react/issues/20030 + case "$$typeof": + return void 0; + case "toJSON": + return () => ({}); + case "addListener": + return pluginHeader ? addListenerNative : addListener; + case "removeListener": + return removeListener; + default: + return createPluginMethodWrapper(prop); + } + } + }); + Plugins[pluginName] = proxy; + registeredPlugins.set(pluginName, { + name: pluginName, + proxy, + platforms: /* @__PURE__ */ new Set([...Object.keys(jsImplementations), ...pluginHeader ? [platform] : []]) + }); + return proxy; + }; + if (!cap.convertFileSrc) { + cap.convertFileSrc = (filePath) => filePath; + } + cap.getPlatform = getPlatform; + cap.handleError = handleError; + cap.isNativePlatform = isNativePlatform; + cap.isPluginAvailable = isPluginAvailable; + cap.registerPlugin = registerPlugin2; + cap.Exception = CapacitorException; + cap.DEBUG = !!cap.DEBUG; + cap.isLoggingEnabled = !!cap.isLoggingEnabled; + return cap; + }; + var initCapacitorGlobal = (win) => win.Capacitor = createCapacitor(win); + var Capacitor = /* @__PURE__ */ initCapacitorGlobal(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); + var registerPlugin = Capacitor.registerPlugin; + var WebPlugin = class { + constructor() { + this.listeners = {}; + this.retainedEventArguments = {}; + this.windowListeners = {}; + } + addListener(eventName, listenerFunc) { + let firstListener = false; + const listeners = this.listeners[eventName]; + if (!listeners) { + this.listeners[eventName] = []; + firstListener = true; + } + this.listeners[eventName].push(listenerFunc); + const windowListener = this.windowListeners[eventName]; + if (windowListener && !windowListener.registered) { + this.addWindowListener(windowListener); + } + if (firstListener) { + this.sendRetainedArgumentsForEvent(eventName); + } + const remove = async () => this.removeListener(eventName, listenerFunc); + const p = Promise.resolve({ remove }); + return p; + } + async removeAllListeners() { + this.listeners = {}; + for (const listener in this.windowListeners) { + this.removeWindowListener(this.windowListeners[listener]); + } + this.windowListeners = {}; + } + notifyListeners(eventName, data, retainUntilConsumed) { + const listeners = this.listeners[eventName]; + if (!listeners) { + if (retainUntilConsumed) { + let args = this.retainedEventArguments[eventName]; + if (!args) { + args = []; + } + args.push(data); + this.retainedEventArguments[eventName] = args; + } + return; + } + listeners.forEach((listener) => listener(data)); + } + hasListeners(eventName) { + var _a; + return !!((_a = this.listeners[eventName]) === null || _a === void 0 ? void 0 : _a.length); + } + registerWindowListener(windowEventName, pluginEventName) { + this.windowListeners[pluginEventName] = { + registered: false, + windowEventName, + pluginEventName, + handler: (event) => { + this.notifyListeners(pluginEventName, event); + } + }; + } + unimplemented(msg = "not implemented") { + return new Capacitor.Exception(msg, ExceptionCode.Unimplemented); + } + unavailable(msg = "not available") { + return new Capacitor.Exception(msg, ExceptionCode.Unavailable); + } + async removeListener(eventName, listenerFunc) { + const listeners = this.listeners[eventName]; + if (!listeners) { + return; + } + const index = listeners.indexOf(listenerFunc); + if (index !== -1) { + this.listeners[eventName].splice(index, 1); + } + if (!this.listeners[eventName].length) { + this.removeWindowListener(this.windowListeners[eventName]); + } + } + addWindowListener(handle) { + window.addEventListener(handle.windowEventName, handle.handler); + handle.registered = true; + } + removeWindowListener(handle) { + if (!handle) { + return; + } + window.removeEventListener(handle.windowEventName, handle.handler); + handle.registered = false; + } + sendRetainedArgumentsForEvent(eventName) { + const args = this.retainedEventArguments[eventName]; + if (!args) { + return; + } + delete this.retainedEventArguments[eventName]; + args.forEach((arg) => { + this.notifyListeners(eventName, arg); + }); + } + }; + var encode = (str) => encodeURIComponent(str).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape); + var decode = (str) => str.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); + var CapacitorCookiesPluginWeb = class extends WebPlugin { + async getCookies() { + const cookies = document.cookie; + const cookieMap = {}; + cookies.split(";").forEach((cookie) => { + if (cookie.length <= 0) + return; + let [key, value] = cookie.replace(/=/, "CAP_COOKIE").split("CAP_COOKIE"); + key = decode(key).trim(); + value = decode(value).trim(); + cookieMap[key] = value; + }); + return cookieMap; + } + async setCookie(options) { + try { + const encodedKey = encode(options.key); + const encodedValue = encode(options.value); + const expires = options.expires ? `; expires=${options.expires.replace("expires=", "")}` : ""; + const path = (options.path || "/").replace("path=", ""); + const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : ""; + document.cookie = `${encodedKey}=${encodedValue || ""}${expires}; path=${path}; ${domain};`; + } catch (error) { + return Promise.reject(error); + } + } + async deleteCookie(options) { + try { + document.cookie = `${options.key}=; Max-Age=0`; + } catch (error) { + return Promise.reject(error); + } + } + async clearCookies() { + try { + const cookies = document.cookie.split(";") || []; + for (const cookie of cookies) { + document.cookie = cookie.replace(/^ +/, "").replace(/=.*/, `=;expires=${(/* @__PURE__ */ new Date()).toUTCString()};path=/`); + } + } catch (error) { + return Promise.reject(error); + } + } + async clearAllCookies() { + try { + await this.clearCookies(); + } catch (error) { + return Promise.reject(error); + } + } + }; + var CapacitorCookies = registerPlugin("CapacitorCookies", { + web: () => new CapacitorCookiesPluginWeb() + }); + var readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => { + const base64String = reader.result; + resolve(base64String.indexOf(",") >= 0 ? base64String.split(",")[1] : base64String); + }; + reader.onerror = (error) => reject(error); + reader.readAsDataURL(blob); + }); + var normalizeHttpHeaders = (headers = {}) => { + const originalKeys = Object.keys(headers); + const loweredKeys = Object.keys(headers).map((k) => k.toLocaleLowerCase()); + const normalized = loweredKeys.reduce((acc, key, index) => { + acc[key] = headers[originalKeys[index]]; + return acc; + }, {}); + return normalized; + }; + var buildUrlParams = (params, shouldEncode = true) => { + if (!params) + return null; + const output = Object.entries(params).reduce((accumulator, entry) => { + const [key, value] = entry; + let encodedValue; + let item; + if (Array.isArray(value)) { + item = ""; + value.forEach((str) => { + encodedValue = shouldEncode ? encodeURIComponent(str) : str; + item += `${key}=${encodedValue}&`; + }); + item.slice(0, -1); + } else { + encodedValue = shouldEncode ? encodeURIComponent(value) : value; + item = `${key}=${encodedValue}`; + } + return `${accumulator}&${item}`; + }, ""); + return output.substr(1); + }; + var buildRequestInit = (options, extra = {}) => { + const output = Object.assign({ method: options.method || "GET", headers: options.headers }, extra); + const headers = normalizeHttpHeaders(options.headers); + const type = headers["content-type"] || ""; + if (typeof options.data === "string") { + output.body = options.data; + } else if (type.includes("application/x-www-form-urlencoded")) { + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(options.data || {})) { + params.set(key, value); + } + output.body = params.toString(); + } else if (type.includes("multipart/form-data") || options.data instanceof FormData) { + const form = new FormData(); + if (options.data instanceof FormData) { + options.data.forEach((value, key) => { + form.append(key, value); + }); + } else { + for (const key of Object.keys(options.data)) { + form.append(key, options.data[key]); + } + } + output.body = form; + const headers2 = new Headers(output.headers); + headers2.delete("content-type"); + output.headers = headers2; + } else if (type.includes("application/json") || typeof options.data === "object") { + output.body = JSON.stringify(options.data); + } + return output; + }; + var CapacitorHttpPluginWeb = class extends WebPlugin { + /** + * Perform an Http request given a set of options + * @param options Options to build the HTTP request + */ + async request(options) { + const requestInit = buildRequestInit(options, options.webFetchExtra); + const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams); + const url = urlParams ? `${options.url}?${urlParams}` : options.url; + const response = await fetch(url, requestInit); + const contentType = response.headers.get("content-type") || ""; + let { responseType = "text" } = response.ok ? options : {}; + if (contentType.includes("application/json")) { + responseType = "json"; + } + let data; + let blob; + switch (responseType) { + case "arraybuffer": + case "blob": + blob = await response.blob(); + data = await readBlobAsBase64(blob); + break; + case "json": + data = await response.json(); + break; + case "document": + case "text": + default: + data = await response.text(); + } + const headers = {}; + response.headers.forEach((value, key) => { + headers[key] = value; + }); + return { + data, + headers, + status: response.status, + url: response.url + }; + } + /** + * Perform an Http GET request given a set of options + * @param options Options to build the HTTP request + */ + async get(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "GET" })); + } + /** + * Perform an Http POST request given a set of options + * @param options Options to build the HTTP request + */ + async post(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "POST" })); + } + /** + * Perform an Http PUT request given a set of options + * @param options Options to build the HTTP request + */ + async put(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "PUT" })); + } + /** + * Perform an Http PATCH request given a set of options + * @param options Options to build the HTTP request + */ + async patch(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "PATCH" })); + } + /** + * Perform an Http DELETE request given a set of options + * @param options Options to build the HTTP request + */ + async delete(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "DELETE" })); + } + }; + var CapacitorHttp = registerPlugin("CapacitorHttp", { + web: () => new CapacitorHttpPluginWeb() + }); + var SystemBarsStyle; + (function(SystemBarsStyle2) { + SystemBarsStyle2["Dark"] = "DARK"; + SystemBarsStyle2["Light"] = "LIGHT"; + SystemBarsStyle2["Default"] = "DEFAULT"; + })(SystemBarsStyle || (SystemBarsStyle = {})); + var SystemBarType; + (function(SystemBarType2) { + SystemBarType2["StatusBar"] = "StatusBar"; + SystemBarType2["NavigationBar"] = "NavigationBar"; + })(SystemBarType || (SystemBarType = {})); + var SystemBarsPluginWeb = class extends WebPlugin { + async setStyle() { + this.unavailable("not available for web"); + } + async setAnimation() { + this.unavailable("not available for web"); + } + async show() { + this.unavailable("not available for web"); + } + async hide() { + this.unavailable("not available for web"); + } + }; + var SystemBars = registerPlugin("SystemBars", { + web: () => new SystemBarsPluginWeb() + }); + + // scripts/android-bridge.js + var EpMail = registerPlugin("EpMail"); + if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") { + window.daybreakMail = { + getAppVersion: () => EpMail.getAppVersion().then((result) => result.version), + getAccount: () => EpMail.getAccount(), + listAccounts: () => EpMail.listAccounts(), + selectAccount: (id) => EpMail.selectAccount({ id }), + removeAccount: (id) => EpMail.removeAccount({ id }), + connect: (details) => EpMail.connect(details), + updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), + syncFolder: (folder, offset) => EpMail.syncFolder({ folder, offset }), + syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }), + onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback), + updateMessage: (details) => EpMail.updateMessage(details), + saveAttachment: (details) => EpMail.saveAttachment(details), + send: (message) => EpMail.send(message), + disconnect: (id) => EpMail.removeAccount({ id }), + davList: () => EpMail.davList(), + davConnect: (config) => EpMail.davConnect(config), + davActivate: (type, id) => EpMail.davActivate({ type, id }), + davRemove: (type, id) => EpMail.davRemove({ type, id }), + davSync: (type) => EpMail.davSync({ type }), + davSaveEvent: (event) => EpMail.davSaveEvent(event), + davDeleteEvent: (remote) => EpMail.davDeleteEvent(remote), + davSaveContact: (contact) => EpMail.davSaveContact(contact), + davDeleteContact: (remote) => EpMail.davDeleteContact(remote) + }; + } +})(); +/*! Bundled license information: + +@capacitor/core/dist/index.js: + (*! Capacitor: https://capacitorjs.com/ - MIT License *) +*/ diff --git a/scripts/android-bridge.js b/scripts/android-bridge.js new file mode 100644 index 0000000..3b70cc4 --- /dev/null +++ b/scripts/android-bridge.js @@ -0,0 +1,31 @@ +import { Capacitor, registerPlugin } from '@capacitor/core'; + +const EpMail = registerPlugin('EpMail'); + +if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { + window.daybreakMail = { + getAppVersion: () => EpMail.getAppVersion().then(result => result.version), + getAccount: () => EpMail.getAccount(), + listAccounts: () => EpMail.listAccounts(), + selectAccount: id => EpMail.selectAccount({ id }), + removeAccount: id => EpMail.removeAccount({ id }), + connect: details => EpMail.connect(details), + updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), + syncFolder: (folder, offset) => EpMail.syncFolder({ folder, offset }), + syncInbox: () => EpMail.syncFolder({ folder: 'Inbox', offset: 0 }), + onSyncUpdate: callback => EpMail.addListener('mailSyncUpdate', callback), + updateMessage: details => EpMail.updateMessage(details), + saveAttachment: details => EpMail.saveAttachment(details), + send: message => EpMail.send(message), + disconnect: id => EpMail.removeAccount({ id }), + davList: () => EpMail.davList(), + davConnect: config => EpMail.davConnect(config), + davActivate: (type, id) => EpMail.davActivate({ type, id }), + davRemove: (type, id) => EpMail.davRemove({ type, id }), + davSync: type => EpMail.davSync({ type }), + davSaveEvent: event => EpMail.davSaveEvent(event), + davDeleteEvent: remote => EpMail.davDeleteEvent(remote), + davSaveContact: contact => EpMail.davSaveContact(contact), + davDeleteContact: remote => EpMail.davDeleteContact(remote) + }; +} diff --git a/scripts/build-android-apk.cjs b/scripts/build-android-apk.cjs new file mode 100644 index 0000000..de9b838 --- /dev/null +++ b/scripts/build-android-apk.cjs @@ -0,0 +1,17 @@ +const { spawnSync } = require('node:child_process'); +const path = require('node:path'); + +const androidDir = path.resolve(__dirname, '..', 'android'); +const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew'; +const result = spawnSync(gradleWrapper, ['assembleDebug'], { + cwd: androidDir, + stdio: 'inherit', + shell: process.platform === 'win32' +}); + +if (result.error) { + console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`); + process.exitCode = 1; +} else { + process.exitCode = result.status ?? 1; +} diff --git a/scripts/prepare-android-web.cjs b/scripts/prepare-android-web.cjs new file mode 100644 index 0000000..939d0bb --- /dev/null +++ b/scripts/prepare-android-web.cjs @@ -0,0 +1,43 @@ +const fs = require('node:fs/promises'); +const path = require('node:path'); +const esbuild = require('esbuild'); + +const root = path.resolve(__dirname, '..'); +const output = path.join(root, 'www'); +const assets = [ + 'index.html', + 'styles.css', + 'branding.css', + 'app.js', + 'mail-ui.js', + 'productivity.js', + 'account-ui.js', + 'dav-ui.js', + 'icon.svg', + 'logo-ep-daylight.svg', + 'logo-ep-wasteland.svg', + 'manifest.webmanifest', + 'service-worker.js' +]; + +async function prepare() { + await fs.rm(output, { recursive: true, force: true }); + await fs.mkdir(output, { recursive: true }); + for (const asset of assets) { + await fs.copyFile(path.join(root, asset), path.join(output, asset)); + } + const bridgePath = path.join(root, 'platform-bridge.js'); + await esbuild.build({ + entryPoints: [path.join(root, 'scripts', 'android-bridge.js')], + outfile: bridgePath, + bundle: true, + platform: 'browser', + format: 'iife' + }); + await fs.copyFile(bridgePath, path.join(output, 'platform-bridge.js')); +} + +prepare().catch(error => { + console.error('Could not prepare Android web assets:', error); + process.exitCode = 1; +}); diff --git a/service-worker.js b/service-worker.js index 8473b56..fd93ee0 100644 --- a/service-worker.js +++ b/service-worker.js @@ -1,5 +1,5 @@ const CACHE='ep-mail-v2'; -const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./mail-ui.js','./productivity.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; +const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); diff --git a/www/account-ui.js b/www/account-ui.js new file mode 100644 index 0000000..dafa9ff --- /dev/null +++ b/www/account-ui.js @@ -0,0 +1,26 @@ +async function openAccountManager(){ + const root=$('#modal-root'); + try{ + const data=await window.daybreakMail.listAccounts(); + const accounts=data.accounts||[]; + const rows=accounts.map(account=>``).join(''); + root.innerHTML=``; + const close=()=>root.innerHTML=''; + root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close); + root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + root.querySelector('#add-mail-account').onclick=()=>{close();openMailAccount()}; + root.onclick=async event=>{ + const switchButton=event.target.closest('[data-switch-account]'); + if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return} + const davButton=event.target.closest('[data-open-dav]'); + if(davButton){close();openDavManager(davButton.dataset.openDav);return} + const editButton=event.target.closest('[data-edit-account]'); + if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)openMailAccount(account);return} + const removeButton=event.target.closest('[data-remove-account]'); + if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;connectedMailAccount=active;if(active){updateAccountCard(active);close();activeFolder='Inbox';mailPageOffset=0;await syncMailbox(false,{offset:0})}else{updateAccountCard({email:'Connect a mailbox',imapHost:''});messages.splice(0,messages.length);renderList();$('#reader-pane').innerHTML=emptyReader();toast('Mail account removed');openAccountManager()}}catch(error){toast(error.message||'Could not remove the account');removeButton.disabled=false}return} + }; + }catch(error){toast(error.message||'Could not load mail accounts')} +} + +document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true); +document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true); diff --git a/www/app.js b/www/app.js new file mode 100644 index 0000000..369f5e4 --- /dev/null +++ b/www/app.js @@ -0,0 +1,17 @@ +if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{})); +const messages = []; +const contacts=[]; +let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set(); +const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; +function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))} +function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`
${m.initials}
${esc(m.sender)}
${esc(m.subject)}
${esc(m.snippet)}
${esc(m.time)}
`).join(''):`
⌕

No messages here

Try another folder or search.

`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()} +function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`
${m.tags.map((t,i)=>`${esc(t)}`).join('')}

${esc(m.subject)}

${m.initials}
${esc(m.sender)}${esc(m.email)} · to me
${esc(m.date)}
${m.body.map(p=>`

${esc(p)}

`).join('')}

${esc(m.signature||m.sender)}

${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`
${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}
${esc(file.filename)}${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}
`).join('')}
`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)} +function emptyReader(){return `
✉

Your inbox, at your pace

Select a message to read it here.

`} +function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)} +function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=``;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()} +function switchView(view){activeView=view;$$('.rail-button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('.mail-layout').classList.toggle('hidden',view!=='mail');$('#calendar-view').classList.toggle('hidden',view!=='calendar');$('#contacts-view').classList.toggle('hidden',view!=='contacts');$('#sidebar-title').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';$('#crumb-parent').textContent=view==='mail'?'Mail':'Workspace';$('#crumb-current').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';} +function renderCalendar(){} +function showEvent(){} +function renderContacts(){} +function showContact(){} +$$('.folder').forEach(b=>b.onclick=()=>{activeFolder=b.dataset.folder;$$('.folder').forEach(x=>x.classList.toggle('active',x===b));$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()});$$('.rail-button[data-view]').forEach(b=>b.onclick=()=>{switchView(b.dataset.view);if(b.dataset.view==='calendar')renderCalendar();if(b.dataset.view==='contacts')renderContacts()});function applyTheme(theme,showToast=false){const themes=['daylight','wasteland','ep-wasteland','ep-daylight'];const selected=themes.includes(theme)?theme:'ep-wasteland';const info={daylight:{name:'Eternity Daylight',icon:'☼'},wasteland:{name:'Wasteland',icon:'☾'},'ep-wasteland':{name:'EP Wasteland',icon:'◈'},'ep-daylight':{name:'EP Daylight',icon:'☀'}}[selected];document.body.classList.remove('wasteland','ep-wasteland','ep-daylight');if(selected!=='daylight')document.body.classList.add(selected);document.querySelector('meta[name=theme-color]')?.setAttribute('content',selected==='ep-wasteland'?'#161210':selected==='ep-daylight'?'#f1f1e9':selected==='wasteland'?'#eee8db':'#f4f5f1');localStorage.setItem('daybreak-theme',selected);const brandLogo=$("#brand-logo");if(brandLogo)brandLogo.src=selected==='ep-wasteland'?'logo-ep-wasteland.svg':'logo-ep-daylight.svg';if(showToast)toast(`${info.name} theme`)}applyTheme(localStorage.getItem('daybreak-theme')||'ep-wasteland');$('#search').oninput=e=>{query=e.target.value;renderList()};$('#search').addEventListener('keydown',e=>{if(e.key==='Escape'){e.target.value='';query='';renderList()}});$('#compose').onclick=()=>showCompose();$('#refresh').onclick=()=>{toast('You’re all up to date');renderList()};$('#select-all').onclick=()=>{const visible=messages.filter(m=>!m.archived&&!m.deleted);const all=visible.every(m=>selectedIds.has(m.id));visible.forEach(m=>all?selectedIds.delete(m.id):selectedIds.add(m.id));renderList()};$('#archive-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.archived=true);selectedIds.clear();renderList();toast('Selected messages archived')};$('#delete-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.deleted=true);selectedIds.clear();renderList();toast('Selected messages moved to Trash')};$('#sidebar-menu').onclick=()=>toast('More mailbox options');$$('.settings-button,.help-button,.tiny-plus,.text-button').forEach(b=>b.onclick=()=>toast('You’re all caught up'));document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#search').focus()}if(e.key==='Escape')$('#modal-root').innerHTML=''});$('#today-label').textContent=new Intl.DateTimeFormat('en-US',{weekday:'long',month:'long',day:'numeric'}).format(new Date()).toUpperCase();$('#reader-pane').innerHTML=emptyReader();renderList();openMessage(activeMessage); diff --git a/www/branding.css b/www/branding.css new file mode 100644 index 0000000..2f5021f --- /dev/null +++ b/www/branding.css @@ -0,0 +1,30 @@ +.brand-mark, +body.wasteland .brand-mark, +body.ep-wasteland .brand-mark, +body.ep-daylight .brand-mark { + background: transparent !important; + box-shadow: none !important; + border-radius: 0; +} + +.brand-mark img { + display: block; + width: 35px; + height: 35px; + object-fit: contain; +} + +.settings-select { + flex: 1; + border: 0; + padding: 5px 0; + background: transparent; + color: var(--text); + font: inherit; + text-align: right; +} + +body.ep-wasteland .settings-select, +body.ep-daylight .settings-select { + color-scheme: inherit; +} diff --git a/www/dav-ui.js b/www/dav-ui.js new file mode 100644 index 0000000..0ac11c6 --- /dev/null +++ b/www/dav-ui.js @@ -0,0 +1,38 @@ +function davTypeName(type){return type==='caldav'?'calendar':'contacts'} +async function syncDav(type, uploadLocal=false){ + try{ + const localOnly=type==='caldav'?savedEvents.filter(item=>!item._dav):savedContacts.filter(item=>!item._dav); + const result=await window.daybreakMail.davSync(type); + if(type==='caldav'){ + if(uploadLocal)for(const event of localOnly){try{event._dav=await window.daybreakMail.davSaveEvent(event)}catch(error){toast(`Could not upload “${event.title}”: ${error.message}`)}} + savedEvents=[...localOnly,...result.items]; + productWrite(productKeys.events,savedEvents);renderCalendar();toast(`Synced ${result.items.length} calendar events`); + }else{ + if(uploadLocal)for(const contact of localOnly){try{contact._dav=await window.daybreakMail.davSaveContact(contact)}catch(error){toast(`Could not upload “${contact.name}”: ${error.message}`)}} + savedContacts=[...localOnly,...result.items]; + productWrite(productKeys.contacts,savedContacts);renderContacts();toast(`Synced ${result.items.length} contacts`); + } + }catch(error){toast(error.message||`Could not sync ${davTypeName(type)}`)} +} +async function openDavManager(type){ + const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV'; + try{ + const data=await window.daybreakMail.davList(),accounts=data[type]||[],activeId=data[type==='caldav'?'activeCaldavId':'activeCarddavId']; + const rows=accounts.map(account=>``).join(''); + root.innerHTML=``; + const close=()=>root.innerHTML='';root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + root.querySelector('#add-dav-server').onclick=()=>showDavConnect(type); + root.onclick=async event=>{ + const activate=event.target.closest('[data-dav-activate]');if(activate){try{await window.daybreakMail.davActivate(type,activate.dataset.davActivate);close();await syncDav(type)}catch(error){toast(error.message)}return} + const remove=event.target.closest('[data-dav-remove]');if(remove){if(!confirm(`Remove this ${label} server from ep-mail?`))return;try{const result=await window.daybreakMail.davRemove(type,remove.dataset.davRemove);close();if(result.activeId)await syncDav(type);else if(type==='caldav'){savedEvents=savedEvents.filter(item=>!item._dav);productWrite(productKeys.events,savedEvents);renderCalendar()}else{savedContacts=savedContacts.filter(item=>!item._dav);productWrite(productKeys.contacts,savedContacts);renderContacts()}await openDavManager(type)}catch(error){toast(error.message)} } + }; + }catch(error){toast(error.message||`Could not load ${label} servers`)} +} +function showDavConnect(type){ + const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV'; + root.innerHTML=``; + const close=()=>root.innerHTML='';root.querySelector('.modal-close').onclick=close;root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};root.querySelector('#dav-cancel').onclick=close; + root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}}; + root.querySelector('#dav-server-url').focus(); +} +document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true); diff --git a/www/icon.svg b/www/icon.svg new file mode 100644 index 0000000..72dfd11 --- /dev/null +++ b/www/icon.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/www/index.html b/www/index.html new file mode 100644 index 0000000..3d1670d --- /dev/null +++ b/www/index.html @@ -0,0 +1,71 @@ + + + + + + + + + ep-mail + + + + + +
+ + + + +
+
⌕⌘ K
+ +
+
+

Good morning

+
1–8 of 24
+
+
All caught up with your mail
+
+
+
+ + + +
+
+ +
+ + + + + + + + diff --git a/www/logo-ep-daylight.svg b/www/logo-ep-daylight.svg new file mode 100644 index 0000000..ffd0b2c --- /dev/null +++ b/www/logo-ep-daylight.svg @@ -0,0 +1,9 @@ + diff --git a/www/logo-ep-wasteland.svg b/www/logo-ep-wasteland.svg new file mode 100644 index 0000000..d4dbe6e --- /dev/null +++ b/www/logo-ep-wasteland.svg @@ -0,0 +1,9 @@ + diff --git a/www/mail-ui.js b/www/mail-ui.js new file mode 100644 index 0000000..107c52f --- /dev/null +++ b/www/mail-ui.js @@ -0,0 +1,237 @@ +let connectedMailAccount = null; +let mailPageOffset = 0; +let mailTotal = 0; +let mailboxSyncPromise = null; +let mailboxSyncQueued = false; +let mailboxRefreshPending = false; + +function updateAccountCard(account) { + const card = $('#account-settings'); + if (!card) return; + const email = account.email || ''; + const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase()); + const displayName = account.displayName?.trim() || profileSettings.name.trim() || localName; + const initials = displayName.split(/\s+/).filter(Boolean).map(part => part[0]).join('').slice(0, 2); + card.querySelector('.account-avatar').textContent = initials || 'M'; + card.querySelector('.account-info strong').textContent = displayName; + card.querySelector('.account-info span').textContent = email; + card.title = `${displayName} <${email}>`; + card.querySelector('.online-dot').style.background = '#70ad7b'; + const profileButton = $('.top-avatar'); + if (profileButton) { + profileButton.textContent = initials || 'M'; + profileButton.title = `${displayName} <${email}>`; + profileButton.setAttribute('aria-label', `${displayName} account settings`); + } +} +function openMailAccount(existingAccount = null) { + const root = $('#modal-root'); + const editing = Boolean(existingAccount); + const displayName = existingAccount?.displayName || profileSettings.name || ''; + root.innerHTML = ``; + const close = () => { root.innerHTML = ''; }; + $$('.modal-close').forEach(button => button.onclick = close); + $('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); }); + $('#disconnect-mail').onclick = close; + $('#connect-mail').onclick = async () => { + const button = $('#connect-mail'); + const status = $('#mail-account-status'); + const password = $('#mail-account-password').value; + const name = $('#mail-account-display-name').value.trim(); + if (!name) { status.textContent = 'Enter a display name for this mail account.'; $('#mail-account-display-name').focus(); return; } + if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; } + button.disabled = true; + button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…'; + status.textContent = editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.'; + try { + const details = { + email: $('#mail-account-email').value, + password, + displayName: name, + imapHost: $('#mail-account-imap').value, + smtpHost: $('#mail-account-smtp').value + }; + const account = editing + ? await window.daybreakMail.updateAccount(existingAccount.id, details) + : await window.daybreakMail.connect(details); + if (editing) { + const accountList = await window.daybreakMail.listAccounts(); + if (accountList.activeId === account.id) { + connectedMailAccount = account; + updateAccountCard(account); + mailPageOffset = 0; + close(); + await syncMailbox(false, { offset: 0 }); + } else { + close(); + } + toast('Mailbox settings updated'); + } else { + connectedMailAccount = account; + updateAccountCard(account); + close(); + toast('Mailbox connected securely'); + await syncMailbox(true); + } + } catch (error) { + status.textContent = error.message || 'Could not connect. Check the account details and try again.'; + button.disabled = false; + button.textContent = editing ? 'Save & reconnect' : 'Test & connect'; + } + }; + $('#mail-account-email').focus(); +} +async function syncMailbox(showToast, options = {}) { + if (mailboxSyncPromise) { + mailboxSyncQueued = true; + return mailboxSyncPromise; + } + if (!connectedMailAccount || !window.daybreakMail) { + openMailAccount(); + return; + } + const refresh = $('#refresh'); + if (refresh) refresh.disabled = true; + const sync = (async () => { + try { + const previouslyActiveMessage = activeMessage; + const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset); + const result = await window.daybreakMail.syncFolder(activeFolder, offset); + if (options.append) messages.push(...result.messages); + else messages.splice(0, messages.length, ...result.messages); + messages.forEach(message => { + try { + const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]'); + message.tags = [...new Set([...(message.tags || []), ...localTags])]; + } catch {} + }); + if (!options.append) mailPageOffset = offset; + mailTotal = result.total; + activeMessage = messages.some(message => message.id === previouslyActiveMessage) + ? previouslyActiveMessage + : messages[0]?.id; + selectedIds.clear(); + const unread = messages.filter(message => message.unread).length; + const inboxCount = $('.folder[data-folder="Inbox"] .count'); + if (inboxCount) inboxCount.textContent = String(unread); + const pagination = $('#pagination'); + if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages'; + const loadMore = $('#load-more'); + if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total); + renderList(); + if (activeMessage) { + openMessage(activeMessage); + const current = messages.find(message => message.id === activeMessage); + if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: activeFolder, action: 'unread', enabled: false }).catch(() => {}); + } + else $('#reader-pane').innerHTML = emptyReader(); + updateAccountCard(connectedMailAccount); + if (showToast) toast(`Synced ${messages.length} messages`); + } catch (error) { + toast(error.message || 'Could not sync the inbox'); + } finally { + if (refresh) refresh.disabled = false; + } + })(); + mailboxSyncPromise = sync; + try { + await sync; + } finally { + mailboxSyncPromise = null; + if (mailboxSyncQueued) { + mailboxSyncQueued = false; + void syncMailbox(false); + } + } +} + +if (window.daybreakMail) { + window.daybreakMail.getAppVersion().then(version => { + document.title = `ep-mail v${version}`; + }).catch(error => { + console.error('Could not read app version:', error); + }); + window.daybreakMail.onSyncUpdate(update => { + if (update.accountId !== connectedMailAccount?.id) return; + if (update.error) { + toast(update.error); + return; + } + if (update.newCount || (update.foldersChanged || []).length) { + if (document.visibilityState === 'visible') { + syncMailbox(false, update.newCount ? { offset: 0 } : {}); + } + else mailboxRefreshPending = true; + } + }); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible' && mailboxRefreshPending) { + mailboxRefreshPending = false; + syncMailbox(false, { offset: 0 }); + } + }); + window.addEventListener('focus', () => { + if (connectedMailAccount) syncMailbox(false); + }); + setInterval(() => { + if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') { + syncMailbox(false); + } + }, 60 * 1000); + $('#account-settings').addEventListener('click', openMailAccount); + $('#account-settings').addEventListener('keydown', event => { + if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); } + }); + $('#settings-button').onclick = () => openPreferences(); + $('#refresh').onclick = () => syncMailbox(true); + $$('.folder').forEach(button => button.addEventListener('click', () => { + if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred'].includes(button.dataset.folder)) { + mailPageOffset = 0; + syncMailbox(false, { offset: 0 }); + } + })); + $('#previous-page').onclick = () => { + if (mailPageOffset <= 0) return; + mailPageOffset = Math.max(0, mailPageOffset - 20); + syncMailbox(false, { offset: mailPageOffset }); + }; + $('#next-page').onclick = () => { + if (mailPageOffset + 20 >= mailTotal) return; + mailPageOffset += 20; + syncMailbox(false, { offset: mailPageOffset }); + }; + $('#load-more').onclick = () => syncMailbox(false, { append: true }); + document.addEventListener('click', async event => { + const sendButton = event.target.closest('#send'); + if (!sendButton || !connectedMailAccount) return; + event.preventDefault(); + event.stopImmediatePropagation(); + const recipient = $('#compose-to').value.trim(); + if (!recipient) { $('#compose-to').focus(); toast('Add a recipient to send your message'); return; } + sendButton.disabled = true; + sendButton.textContent = 'Sending…'; + try { + const result = await window.daybreakMail.send({ + to: recipient, + cc: $('#compose-cc').value, + subject: $('#compose-subject').value.trim(), + text: $('#compose-body').value, + displayName: connectedMailAccount.displayName || profileSettings.name + }); + $('#modal-root').innerHTML = ''; + toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved'); + if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 }); + } catch (error) { + sendButton.disabled = false; + sendButton.textContent = 'Send ↗'; + toast(error.message || 'Message could not be sent'); + } + }, true); + + window.daybreakMail.getAccount().then(account => { + if (!account) return; + connectedMailAccount = account; + updateAccountCard(account); + syncMailbox(false); + }).catch(() => {}); +} diff --git a/www/manifest.webmanifest b/www/manifest.webmanifest new file mode 100644 index 0000000..e389539 --- /dev/null +++ b/www/manifest.webmanifest @@ -0,0 +1,10 @@ +{ + "name": "ep-mail", + "short_name": "ep-mail", + "description": "Eternity Project mail, calendar, and contacts.", + "start_url": "./", + "display": "standalone", + "background_color": "#f4f5f1", + "theme_color": "#f4f5f1", + "icons": [{"src":"icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}] +} diff --git a/www/platform-bridge.js b/www/platform-bridge.js new file mode 100644 index 0000000..49611ec --- /dev/null +++ b/www/platform-bridge.js @@ -0,0 +1,545 @@ +(() => { + // node_modules/@capacitor/core/dist/index.js + var ExceptionCode; + (function(ExceptionCode2) { + ExceptionCode2["Unimplemented"] = "UNIMPLEMENTED"; + ExceptionCode2["Unavailable"] = "UNAVAILABLE"; + })(ExceptionCode || (ExceptionCode = {})); + var CapacitorException = class extends Error { + constructor(message, code, data) { + super(message); + this.message = message; + this.code = code; + this.data = data; + } + }; + var getPlatformId = (win) => { + var _a, _b; + if (win === null || win === void 0 ? void 0 : win.androidBridge) { + return "android"; + } else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) { + return "ios"; + } else { + return "web"; + } + }; + var createCapacitor = (win) => { + const capCustomPlatform = win.CapacitorCustomPlatform || null; + const cap = win.Capacitor || {}; + const Plugins = cap.Plugins = cap.Plugins || {}; + const getPlatform = () => { + return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win); + }; + const isNativePlatform = () => getPlatform() !== "web"; + const isPluginAvailable = (pluginName) => { + const plugin = registeredPlugins.get(pluginName); + if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) { + return true; + } + if (getPluginHeader(pluginName)) { + return true; + } + return false; + }; + const getPluginHeader = (pluginName) => { + var _a; + return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find((h) => h.name === pluginName); + }; + const handleError = (err) => win.console.error(err); + const registeredPlugins = /* @__PURE__ */ new Map(); + const registerPlugin2 = (pluginName, jsImplementations = {}) => { + const registeredPlugin = registeredPlugins.get(pluginName); + if (registeredPlugin) { + console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`); + return registeredPlugin.proxy; + } + const platform = getPlatform(); + const pluginHeader = getPluginHeader(pluginName); + let jsImplementation; + const loadPluginImplementation = async () => { + if (!jsImplementation && platform in jsImplementations) { + jsImplementation = typeof jsImplementations[platform] === "function" ? jsImplementation = await jsImplementations[platform]() : jsImplementation = jsImplementations[platform]; + } else if (capCustomPlatform !== null && !jsImplementation && "web" in jsImplementations) { + jsImplementation = typeof jsImplementations["web"] === "function" ? jsImplementation = await jsImplementations["web"]() : jsImplementation = jsImplementations["web"]; + } + return jsImplementation; + }; + const createPluginMethod = (impl, prop) => { + var _a, _b; + if (pluginHeader) { + const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find((m) => prop === m.name); + if (methodHeader) { + if (methodHeader.rtype === "promise") { + return (options) => cap.nativePromise(pluginName, prop.toString(), options); + } else { + return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback); + } + } else if (impl) { + return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl); + } + } else if (impl) { + return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl); + } else { + throw new CapacitorException(`"${pluginName}" plugin is not implemented on ${platform}`, ExceptionCode.Unimplemented); + } + }; + const createPluginMethodWrapper = (prop) => { + let remove; + const wrapper = (...args) => { + const p = loadPluginImplementation().then((impl) => { + const fn = createPluginMethod(impl, prop); + if (fn) { + const p2 = fn(...args); + remove = p2 === null || p2 === void 0 ? void 0 : p2.remove; + return p2; + } else { + throw new CapacitorException(`"${pluginName}.${prop}()" is not implemented on ${platform}`, ExceptionCode.Unimplemented); + } + }); + if (prop === "addListener") { + p.remove = async () => remove(); + } + return p; + }; + wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`; + Object.defineProperty(wrapper, "name", { + value: prop, + writable: false, + configurable: false + }); + return wrapper; + }; + const addListener = createPluginMethodWrapper("addListener"); + const removeListener = createPluginMethodWrapper("removeListener"); + const addListenerNative = (eventName, callback) => { + const call = addListener({ eventName }, callback); + const remove = async () => { + const callbackId = await call; + removeListener({ + eventName, + callbackId + }, callback); + }; + const p = new Promise((resolve) => call.then(() => resolve({ remove }))); + p.remove = async () => { + console.warn(`Using addListener() without 'await' is deprecated.`); + await remove(); + }; + return p; + }; + const proxy = new Proxy({}, { + get(_, prop) { + switch (prop) { + // https://github.com/facebook/react/issues/20030 + case "$$typeof": + return void 0; + case "toJSON": + return () => ({}); + case "addListener": + return pluginHeader ? addListenerNative : addListener; + case "removeListener": + return removeListener; + default: + return createPluginMethodWrapper(prop); + } + } + }); + Plugins[pluginName] = proxy; + registeredPlugins.set(pluginName, { + name: pluginName, + proxy, + platforms: /* @__PURE__ */ new Set([...Object.keys(jsImplementations), ...pluginHeader ? [platform] : []]) + }); + return proxy; + }; + if (!cap.convertFileSrc) { + cap.convertFileSrc = (filePath) => filePath; + } + cap.getPlatform = getPlatform; + cap.handleError = handleError; + cap.isNativePlatform = isNativePlatform; + cap.isPluginAvailable = isPluginAvailable; + cap.registerPlugin = registerPlugin2; + cap.Exception = CapacitorException; + cap.DEBUG = !!cap.DEBUG; + cap.isLoggingEnabled = !!cap.isLoggingEnabled; + return cap; + }; + var initCapacitorGlobal = (win) => win.Capacitor = createCapacitor(win); + var Capacitor = /* @__PURE__ */ initCapacitorGlobal(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); + var registerPlugin = Capacitor.registerPlugin; + var WebPlugin = class { + constructor() { + this.listeners = {}; + this.retainedEventArguments = {}; + this.windowListeners = {}; + } + addListener(eventName, listenerFunc) { + let firstListener = false; + const listeners = this.listeners[eventName]; + if (!listeners) { + this.listeners[eventName] = []; + firstListener = true; + } + this.listeners[eventName].push(listenerFunc); + const windowListener = this.windowListeners[eventName]; + if (windowListener && !windowListener.registered) { + this.addWindowListener(windowListener); + } + if (firstListener) { + this.sendRetainedArgumentsForEvent(eventName); + } + const remove = async () => this.removeListener(eventName, listenerFunc); + const p = Promise.resolve({ remove }); + return p; + } + async removeAllListeners() { + this.listeners = {}; + for (const listener in this.windowListeners) { + this.removeWindowListener(this.windowListeners[listener]); + } + this.windowListeners = {}; + } + notifyListeners(eventName, data, retainUntilConsumed) { + const listeners = this.listeners[eventName]; + if (!listeners) { + if (retainUntilConsumed) { + let args = this.retainedEventArguments[eventName]; + if (!args) { + args = []; + } + args.push(data); + this.retainedEventArguments[eventName] = args; + } + return; + } + listeners.forEach((listener) => listener(data)); + } + hasListeners(eventName) { + var _a; + return !!((_a = this.listeners[eventName]) === null || _a === void 0 ? void 0 : _a.length); + } + registerWindowListener(windowEventName, pluginEventName) { + this.windowListeners[pluginEventName] = { + registered: false, + windowEventName, + pluginEventName, + handler: (event) => { + this.notifyListeners(pluginEventName, event); + } + }; + } + unimplemented(msg = "not implemented") { + return new Capacitor.Exception(msg, ExceptionCode.Unimplemented); + } + unavailable(msg = "not available") { + return new Capacitor.Exception(msg, ExceptionCode.Unavailable); + } + async removeListener(eventName, listenerFunc) { + const listeners = this.listeners[eventName]; + if (!listeners) { + return; + } + const index = listeners.indexOf(listenerFunc); + if (index !== -1) { + this.listeners[eventName].splice(index, 1); + } + if (!this.listeners[eventName].length) { + this.removeWindowListener(this.windowListeners[eventName]); + } + } + addWindowListener(handle) { + window.addEventListener(handle.windowEventName, handle.handler); + handle.registered = true; + } + removeWindowListener(handle) { + if (!handle) { + return; + } + window.removeEventListener(handle.windowEventName, handle.handler); + handle.registered = false; + } + sendRetainedArgumentsForEvent(eventName) { + const args = this.retainedEventArguments[eventName]; + if (!args) { + return; + } + delete this.retainedEventArguments[eventName]; + args.forEach((arg) => { + this.notifyListeners(eventName, arg); + }); + } + }; + var encode = (str) => encodeURIComponent(str).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape); + var decode = (str) => str.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); + var CapacitorCookiesPluginWeb = class extends WebPlugin { + async getCookies() { + const cookies = document.cookie; + const cookieMap = {}; + cookies.split(";").forEach((cookie) => { + if (cookie.length <= 0) + return; + let [key, value] = cookie.replace(/=/, "CAP_COOKIE").split("CAP_COOKIE"); + key = decode(key).trim(); + value = decode(value).trim(); + cookieMap[key] = value; + }); + return cookieMap; + } + async setCookie(options) { + try { + const encodedKey = encode(options.key); + const encodedValue = encode(options.value); + const expires = options.expires ? `; expires=${options.expires.replace("expires=", "")}` : ""; + const path = (options.path || "/").replace("path=", ""); + const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : ""; + document.cookie = `${encodedKey}=${encodedValue || ""}${expires}; path=${path}; ${domain};`; + } catch (error) { + return Promise.reject(error); + } + } + async deleteCookie(options) { + try { + document.cookie = `${options.key}=; Max-Age=0`; + } catch (error) { + return Promise.reject(error); + } + } + async clearCookies() { + try { + const cookies = document.cookie.split(";") || []; + for (const cookie of cookies) { + document.cookie = cookie.replace(/^ +/, "").replace(/=.*/, `=;expires=${(/* @__PURE__ */ new Date()).toUTCString()};path=/`); + } + } catch (error) { + return Promise.reject(error); + } + } + async clearAllCookies() { + try { + await this.clearCookies(); + } catch (error) { + return Promise.reject(error); + } + } + }; + var CapacitorCookies = registerPlugin("CapacitorCookies", { + web: () => new CapacitorCookiesPluginWeb() + }); + var readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => { + const base64String = reader.result; + resolve(base64String.indexOf(",") >= 0 ? base64String.split(",")[1] : base64String); + }; + reader.onerror = (error) => reject(error); + reader.readAsDataURL(blob); + }); + var normalizeHttpHeaders = (headers = {}) => { + const originalKeys = Object.keys(headers); + const loweredKeys = Object.keys(headers).map((k) => k.toLocaleLowerCase()); + const normalized = loweredKeys.reduce((acc, key, index) => { + acc[key] = headers[originalKeys[index]]; + return acc; + }, {}); + return normalized; + }; + var buildUrlParams = (params, shouldEncode = true) => { + if (!params) + return null; + const output = Object.entries(params).reduce((accumulator, entry) => { + const [key, value] = entry; + let encodedValue; + let item; + if (Array.isArray(value)) { + item = ""; + value.forEach((str) => { + encodedValue = shouldEncode ? encodeURIComponent(str) : str; + item += `${key}=${encodedValue}&`; + }); + item.slice(0, -1); + } else { + encodedValue = shouldEncode ? encodeURIComponent(value) : value; + item = `${key}=${encodedValue}`; + } + return `${accumulator}&${item}`; + }, ""); + return output.substr(1); + }; + var buildRequestInit = (options, extra = {}) => { + const output = Object.assign({ method: options.method || "GET", headers: options.headers }, extra); + const headers = normalizeHttpHeaders(options.headers); + const type = headers["content-type"] || ""; + if (typeof options.data === "string") { + output.body = options.data; + } else if (type.includes("application/x-www-form-urlencoded")) { + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(options.data || {})) { + params.set(key, value); + } + output.body = params.toString(); + } else if (type.includes("multipart/form-data") || options.data instanceof FormData) { + const form = new FormData(); + if (options.data instanceof FormData) { + options.data.forEach((value, key) => { + form.append(key, value); + }); + } else { + for (const key of Object.keys(options.data)) { + form.append(key, options.data[key]); + } + } + output.body = form; + const headers2 = new Headers(output.headers); + headers2.delete("content-type"); + output.headers = headers2; + } else if (type.includes("application/json") || typeof options.data === "object") { + output.body = JSON.stringify(options.data); + } + return output; + }; + var CapacitorHttpPluginWeb = class extends WebPlugin { + /** + * Perform an Http request given a set of options + * @param options Options to build the HTTP request + */ + async request(options) { + const requestInit = buildRequestInit(options, options.webFetchExtra); + const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams); + const url = urlParams ? `${options.url}?${urlParams}` : options.url; + const response = await fetch(url, requestInit); + const contentType = response.headers.get("content-type") || ""; + let { responseType = "text" } = response.ok ? options : {}; + if (contentType.includes("application/json")) { + responseType = "json"; + } + let data; + let blob; + switch (responseType) { + case "arraybuffer": + case "blob": + blob = await response.blob(); + data = await readBlobAsBase64(blob); + break; + case "json": + data = await response.json(); + break; + case "document": + case "text": + default: + data = await response.text(); + } + const headers = {}; + response.headers.forEach((value, key) => { + headers[key] = value; + }); + return { + data, + headers, + status: response.status, + url: response.url + }; + } + /** + * Perform an Http GET request given a set of options + * @param options Options to build the HTTP request + */ + async get(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "GET" })); + } + /** + * Perform an Http POST request given a set of options + * @param options Options to build the HTTP request + */ + async post(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "POST" })); + } + /** + * Perform an Http PUT request given a set of options + * @param options Options to build the HTTP request + */ + async put(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "PUT" })); + } + /** + * Perform an Http PATCH request given a set of options + * @param options Options to build the HTTP request + */ + async patch(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "PATCH" })); + } + /** + * Perform an Http DELETE request given a set of options + * @param options Options to build the HTTP request + */ + async delete(options) { + return this.request(Object.assign(Object.assign({}, options), { method: "DELETE" })); + } + }; + var CapacitorHttp = registerPlugin("CapacitorHttp", { + web: () => new CapacitorHttpPluginWeb() + }); + var SystemBarsStyle; + (function(SystemBarsStyle2) { + SystemBarsStyle2["Dark"] = "DARK"; + SystemBarsStyle2["Light"] = "LIGHT"; + SystemBarsStyle2["Default"] = "DEFAULT"; + })(SystemBarsStyle || (SystemBarsStyle = {})); + var SystemBarType; + (function(SystemBarType2) { + SystemBarType2["StatusBar"] = "StatusBar"; + SystemBarType2["NavigationBar"] = "NavigationBar"; + })(SystemBarType || (SystemBarType = {})); + var SystemBarsPluginWeb = class extends WebPlugin { + async setStyle() { + this.unavailable("not available for web"); + } + async setAnimation() { + this.unavailable("not available for web"); + } + async show() { + this.unavailable("not available for web"); + } + async hide() { + this.unavailable("not available for web"); + } + }; + var SystemBars = registerPlugin("SystemBars", { + web: () => new SystemBarsPluginWeb() + }); + + // scripts/android-bridge.js + var EpMail = registerPlugin("EpMail"); + if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") { + window.daybreakMail = { + getAppVersion: () => EpMail.getAppVersion().then((result) => result.version), + getAccount: () => EpMail.getAccount(), + listAccounts: () => EpMail.listAccounts(), + selectAccount: (id) => EpMail.selectAccount({ id }), + removeAccount: (id) => EpMail.removeAccount({ id }), + connect: (details) => EpMail.connect(details), + updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }), + syncFolder: (folder, offset) => EpMail.syncFolder({ folder, offset }), + syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }), + onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback), + updateMessage: (details) => EpMail.updateMessage(details), + saveAttachment: (details) => EpMail.saveAttachment(details), + send: (message) => EpMail.send(message), + disconnect: (id) => EpMail.removeAccount({ id }), + davList: () => EpMail.davList(), + davConnect: (config) => EpMail.davConnect(config), + davActivate: (type, id) => EpMail.davActivate({ type, id }), + davRemove: (type, id) => EpMail.davRemove({ type, id }), + davSync: (type) => EpMail.davSync({ type }), + davSaveEvent: (event) => EpMail.davSaveEvent(event), + davDeleteEvent: (remote) => EpMail.davDeleteEvent(remote), + davSaveContact: (contact) => EpMail.davSaveContact(contact), + davDeleteContact: (remote) => EpMail.davDeleteContact(remote) + }; + } +})(); +/*! Bundled license information: + +@capacitor/core/dist/index.js: + (*! Capacitor: https://capacitorjs.com/ - MIT License *) +*/ diff --git a/www/productivity.js b/www/productivity.js new file mode 100644 index 0000000..5b5026a --- /dev/null +++ b/www/productivity.js @@ -0,0 +1,49 @@ +// Persistent profile, calendar and contact tools, plus actions for the mail UI. +const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' }; +const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } }; +const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value)); +let profileSettings = productRead(productKeys.profile, { name: '' }); +if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); } +let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1); +const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']); +let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase())); +productWrite(productKeys.contacts, savedContacts); +let savedEvents = productRead(productKeys.events, []); +let customLabels = productRead(productKeys.labels, []); +let snoozedIds = productRead(productKeys.snoozed, []); +function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); } +function openAccountSettings() { + const root=$('#modal-root'); + root.innerHTML=``; + const close=()=>root.innerHTML=''; + $$('.modal-close').forEach(button=>button.onclick=close); + $('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + $('#save-profile').onclick=()=>{const name=$('#profile-name').value.trim();if(!name){toast('Enter your display name');return}setProfileName(name);close();toast('Account settings saved')}; + $('#profile-name').focus(); +} +function openPreferences() { + const root=$('#modal-root'); + const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']]; + const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland'; + const options=themes.map(([value,label])=>``).join(''); + root.innerHTML=``; + const close=()=>root.innerHTML=''; + $$('.modal-close').forEach(button=>button.onclick=close); + $('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + $('#save-appearance').onclick=()=>{applyTheme($('#theme-select').value);close();toast('Appearance saved')}; + $('#theme-select').focus(); +} +function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=``; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); } +function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`
${d.getDate()}${items.slice(0,3).map(e=>`
${esc(e.time?`${e.time} `:'')}${esc(e.title)}
`).join('')}${items.length>3?`+${items.length-3} more`:''}
`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`

YOUR TIME, WITH ROOM TO BREATHE

${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}

${savedEvents.length} saved events

${days.map(d=>`${d}`).join('')}
${cells}

Coming up

${upcoming.length?upcoming.map(e=>``).join(''):'

No upcoming events yet.

'}
`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}} +function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=``;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()} +function renderContacts(){const cards=savedContacts.map((c,i)=>`
${esc(c.initials)}
${esc(c.name)}${esc(c.email)}${esc(c.note)}
`).join('');$('#contacts-view').innerHTML=`

THE PEOPLE WHO MAKE LIFE FULLER

Your people

${savedContacts.length} contacts, all in one place.

${cards||'

No contacts yet. Add someone to get started.

'}
`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}} +function renderLabels(){const box=$('#custom-labels');if(!box)return;box.innerHTML=customLabels.map(label=>``).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})} +function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')} +function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:activeFolder,action,enabled:action==='star'?!message.star:true})}return Promise.resolve()} +async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}} +document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';}); +function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()} +const baseMessageRenderer=renderList; +renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='
✎

No saved drafts

Compose a message to get started.

';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?snoozedIds.includes(m.id):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='
⌕

No messages here

Try another folder or label.

';return}baseMessageRenderer()}; +document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true); + diff --git a/www/service-worker.js b/www/service-worker.js new file mode 100644 index 0000000..fd93ee0 --- /dev/null +++ b/www/service-worker.js @@ -0,0 +1,5 @@ +const CACHE='ep-mail-v2'; +const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; +self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); +self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); +self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); diff --git a/www/styles.css b/www/styles.css new file mode 100644 index 0000000..ef71f99 --- /dev/null +++ b/www/styles.css @@ -0,0 +1,116 @@ +:root{font-family:'DM Sans',Inter,ui-sans-serif,system-ui,-apple-system,'Segoe UI',sans-serif;color:#252a28;background:#f4f5f1;font-synthesis:none;text-rendering:optimizeLegibility;--bg:#f4f5f1;--panel:#fff;--line:#eaede8;--text:#252a28;--muted:#8b918b;--subtle:#f7f8f5;--accent:#55816c;--accent-soft:#edf4ef;--shadow:0 2px 10px #2636290b} +*{box-sizing:border-box}body{margin:0;min-width:760px;min-height:100vh;background:var(--bg);color:var(--text)}button,input,textarea{font:inherit}button{color:inherit;cursor:pointer}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid #7eae90;outline-offset:2px}.app-shell{height:100vh;min-height:640px;display:flex;overflow:hidden}.rail{width:66px;flex:none;background:#edf0ea;border-right:1px solid #e5e9e2;display:flex;align-items:center;flex-direction:column;padding:17px 0 13px;gap:10px}.brand-mark{height:35px;width:35px;border-radius:12px;background:#5b826c;color:white;display:grid;place-items:center;font-size:24px;margin-bottom:21px;box-shadow:0 3px 8px #476c541d}.rail-button{height:39px;width:39px;border:0;background:transparent;color:#7e8780;border-radius:11px;font-size:20px;display:grid;place-items:center;transition:.18s}.rail-button:hover{background:#e2e8e1;color:#446a54}.rail-button.active{color:#477253;background:#dce9dd}.rail-spacer{flex:1}.avatar{border:0;border-radius:50%;height:34px;width:34px;background:#e7cbb6;color:#614c3c;font-size:11px;font-weight:700;display:grid;place-items:center}.avatar.tiny{height:27px;width:27px;font-size:9px} +.sidebar{width:244px;flex:none;background:#fff;border-right:1px solid var(--line);padding:26px 17px 14px;display:flex;flex-direction:column}.sidebar-head{display:flex;align-items:center;justify-content:space-between;padding:0 5px;margin-bottom:21px}.eyebrow{color:#969c95;font-size:9px;font-weight:700;letter-spacing:1.25px;margin:0 0 5px}.sidebar-head h1{font-family:'DM Serif Display',Georgia,serif;font-size:24px;font-weight:400;margin:0}.icon-button{border:0;background:transparent;color:#89918a;height:30px;min-width:30px;border-radius:8px;font-size:19px;display:inline-grid;place-items:center}.icon-button:hover{background:var(--subtle);color:#47544a}.account-card{display:flex;align-items:center;gap:10px;padding:10px 9px;background:#f7f8f5;border:1px solid #eff1ec;border-radius:10px;margin:0 0 22px}.account-avatar{height:30px;width:30px;border-radius:9px;background:#dce9dd;color:#477253;display:grid;place-items:center;font-family:Georgia,serif;font-weight:bold}.account-info{min-width:0;display:flex;flex-direction:column;gap:2px;flex:1}.account-info strong{font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.account-info span{color:#929891;font-size:9px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.online-dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:#70ad7b}.folder-nav{display:grid;gap:3px}.folder{width:100%;border:0;background:transparent;display:flex;align-items:center;gap:12px;text-align:left;padding:9px 10px;border-radius:8px;font-size:11px;color:#707970}.folder:hover,.label-link:hover{background:#f6f8f5}.folder.active{background:#edf4ee;color:#487354;font-weight:600}.nav-glyph{width:15px;text-align:center;font-size:15px;color:#879188}.folder.active .nav-glyph{color:#578366}.count{margin-left:auto;padding:2px 6px;min-width:19px;text-align:center;border-radius:5px;background:#fff;color:#61836a;font-size:9px}.count.muted{color:#969c95}.sidebar-divider{height:1px;background:#edf0ec;margin:18px 4px 16px}.section-label{display:flex;justify-content:space-between;align-items:center;font-size:9px;letter-spacing:1.1px;font-weight:700;color:#a0a59f;padding:0 6px;margin-bottom:9px}.tiny-plus{border:0;background:transparent;color:#929990;font-size:18px}.label-link{border:0;background:transparent;border-radius:7px;text-align:left;display:flex;align-items:center;gap:10px;color:#727970;font-size:11px;padding:8px 10px}.label-dot{width:8px;height:8px;border-radius:50%}.dot-amber{background:#dda854}.dot-blue{background:#79a4c9}.dot-green{background:#82ab83}.sidebar-bottom{margin-top:auto}.storage{padding:13px 10px 14px;border-bottom:1px solid #eef0ec}.storage-top{display:flex;justify-content:space-between;color:#606960;font-size:10px}.storage-top span+span{color:#979d97;font-size:9px}.storage-bar{height:4px;background:#edf0eb;margin:9px 0 7px;border-radius:5px;overflow:hidden}.storage-bar i{display:block;width:28%;height:100%;background:#79a785;border-radius:5px}.storage small{font-size:9px;color:#9ba19a}.settings-button{border:0;background:transparent;color:#7e867f;display:flex;gap:10px;align-items:center;margin:10px 0 0 4px;font-size:11px;padding:7px} +.main-area{flex:1;min-width:0;display:flex;flex-direction:column}.topbar{height:57px;flex:none;background:#fff;border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;padding:0 24px}.breadcrumbs{display:flex;align-items:center;gap:10px;font-size:10px;color:#969c96}.breadcrumbs strong{font-weight:600;color:#475048}.crumb-divider{color:#c6cbc5}.top-actions{display:flex;align-items:center;gap:13px}.search-wrap{height:31px;width:218px;background:#f6f7f4;border:1px solid #eff0ec;border-radius:8px;display:flex;align-items:center;padding:0 9px;gap:7px;color:#90978f}.search-wrap>span{font-size:19px}.search-wrap input{border:0;outline:0;background:transparent;width:100%;font-size:10px;color:#3f4740}.search-wrap kbd{font:9px 'DM Sans',sans-serif;border:1px solid #e3e6e1;border-radius:4px;padding:2px 4px;white-space:nowrap;color:#999f99}.help-button{font-size:12px;border:1px solid #e7eae6;border-radius:50%;height:20px;min-width:20px;font-weight:600}.top-avatar{width:27px;height:27px;font-size:9px} +.content-view{flex:1;min-height:0}.mail-layout{display:grid;grid-template-columns:minmax(330px,44%) minmax(340px,1fr);padding:18px 20px 20px;gap:14px}.list-pane,.reader-pane{background:var(--panel);border:1px solid var(--line);border-radius:12px;box-shadow:var(--shadow);min-height:0}.list-pane{display:flex;flex-direction:column;overflow:hidden}.list-heading{padding:20px 19px 15px;display:flex;align-items:center;justify-content:space-between}.date-line{font-size:8px;font-weight:700;letter-spacing:1.25px;color:#a0a69f;margin-bottom:7px}.list-heading h2{font-family:'DM Serif Display',Georgia,serif;font-size:20px;font-weight:400;margin:0;color:#303732}.sun{font-family:sans-serif;font-size:14px;color:#dda95f;vertical-align:2px}.compose-button{border:0;border-radius:7px;background:#5b8068;color:white;padding:8px 12px;font-size:10px;font-weight:600;box-shadow:0 2px 4px #406e4f20}.compose-button:hover{background:#476f56}.compose-button span{font-size:15px;vertical-align:-1px;margin-right:4px}.toolbar{height:39px;border-top:1px solid #f2f3f1;border-bottom:1px solid #f0f2ee;display:flex;align-items:center;padding:0 12px;gap:6px;color:#888f88}.toolbar .icon-button{font-size:15px;height:26px;min-width:26px}.tool-checkbox{font-size:14px;color:#818981;border:0;background:transparent;width:25px}.toolbar-divider{height:16px;width:1px;background:#e9ece8;margin:0 3px}.toolbar-spacer{flex:1}.pagination{font-size:9px;color:#90968f;white-space:nowrap}.message-list{overflow-y:auto;flex:1}.message{min-height:68px;display:grid;grid-template-columns:18px 32px minmax(0,1fr) auto;align-items:center;gap:9px;padding:9px 12px;border-bottom:1px solid #f0f2ef;cursor:pointer;transition:background .14s}.message:hover{background:#fafbf9}.message.selected{background:#f3f7f2;box-shadow:inset 2px 0 #669074}.message.unread .sender,.message.unread .subject{font-weight:700;color:#303832}.row-check{appearance:none;width:13px;height:13px;border:1px solid #d7dcd6;border-radius:3px;cursor:pointer;margin:0}.row-check:checked{appearance:auto;accent-color:#63866d}.contact-avatar{width:31px;height:31px;border-radius:50%;display:grid;place-items:center;font-size:9px;font-weight:700;color:#55483d;background:#e9d8c9}.message-body{min-width:0;overflow:hidden}.sender{font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#626a63;margin-bottom:4px}.subject{font-size:10px;color:#3e4640;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:3px}.snippet{font-size:9px;color:#a1a69f;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.message-meta{height:100%;display:flex;flex-direction:column;justify-content:space-between;align-items:flex-end;padding:2px 0;min-width:31px}.time{font-size:8px;color:#989e98;white-space:nowrap}.star{border:0;background:transparent;color:#c9cec8;font-size:14px;line-height:1;padding:0}.star.on{color:#dcaa56}.list-foot{height:37px;flex:none;border-top:1px solid #f0f2ef;display:flex;align-items:center;justify-content:space-between;padding:0 14px;color:#929991;font-size:9px}.list-foot .online-dot{margin-right:6px}.text-button{border:0;background:transparent;color:#708878;font-size:9px}.reader-pane{overflow-y:auto;padding:0 24px 24px}.reader-empty{height:100%;display:grid;place-items:center;text-align:center;color:#9ca39c}.empty-icon{height:52px;width:52px;margin:0 auto 12px;border-radius:17px;background:#f1f5ef;color:#71937a;display:grid;place-items:center;font-size:24px}.reader-empty h3{font-family:'DM Serif Display',Georgia,serif;font-weight:400;font-size:19px;color:#525a53;margin:0 0 6px}.reader-empty p{font-size:10px;color:#9aa098;margin:0}.reader-header{padding:24px 0 17px;border-bottom:1px solid #edf0ec}.reader-topline{display:flex;align-items:center;justify-content:space-between;margin-bottom:17px}.reader-tags{display:flex;gap:6px}.tag{font-size:8px;border-radius:4px;padding:4px 7px;background:#f4f3e9;color:#a38a52}.tag.green{background:#edf4ee;color:#62816a}.reader-tools{display:flex;gap:2px}.reader-subject{font-family:'DM Serif Display',Georgia,serif;font-size:22px;line-height:1.25;margin:0 0 17px;font-weight:400;color:#343a35}.sender-row{display:flex;align-items:center;gap:9px}.sender-row .contact-avatar{width:34px;height:34px;font-size:10px}.sender-details{min-width:0;flex:1}.sender-details strong{display:block;font-size:10px;color:#434a44}.sender-details span{display:block;font-size:9px;color:#999f99;margin-top:3px}.message-date{font-size:8px;color:#999f99;white-space:nowrap}.reader-body{padding:21px 1px 15px;font-size:11px;line-height:1.85;color:#616a62}.reader-body p{margin:0 0 13px}.reader-body .signoff{margin-top:24px}.attachment{margin-top:18px;padding:11px;border:1px solid #e8ece7;border-radius:8px;display:flex;align-items:center;gap:10px;max-width:260px}.file-icon{height:33px;width:30px;border-radius:6px;background:#f4eeec;color:#ad7466;display:grid;place-items:center;font-size:15px}.attachment-info{flex:1}.attachment-info strong{display:block;font-size:9px;color:#59615a}.attachment-info small{font-size:8px;color:#a1a69f}.download{border:0;background:transparent;color:#8b938b}.reply-bar{border-top:1px solid #edf0ec;padding-top:15px;display:flex;gap:8px}.reply-button{padding:8px 12px;border:1px solid #e3e8e3;border-radius:7px;background:#fff;color:#6e786e;font-size:9px}.reply-button:hover{background:#f6f8f5}.reply-button.primary{background:#5b8068;border-color:#5b8068;color:white}.page-view{padding:22px 28px;overflow:auto}.hidden{display:none!important} +.modal-overlay{position:fixed;inset:0;background:#2028204a;z-index:10;display:grid;place-items:center;padding:20px}.compose-modal{width:min(600px,95vw);background:white;border-radius:13px;box-shadow:0 18px 65px #17271c35;overflow:hidden}.modal-head{padding:15px 19px;background:#f6f7f4;border-bottom:1px solid #ebeee9;display:flex;justify-content:space-between;align-items:center;font-size:11px;font-weight:600}.modal-close{border:0;background:transparent;color:#89908a;font-size:19px}.compose-fields{padding:9px 20px 0}.compose-line{display:flex;align-items:center;gap:10px;min-height:39px;border-bottom:1px solid #f0f1ef;color:#969d96;font-size:10px}.compose-line input{flex:1;border:0;outline:0;font-size:10px;color:#424942}.compose-line input::placeholder{color:#aeb3ad}.compose-subject{border:0;width:100%;font-size:14px!important;padding:15px 0;outline:0;color:#303831}.compose-body{width:100%;height:220px;resize:vertical;border:0;border-top:1px solid #f0f1ef;padding:15px 20px;outline:0;font-size:11px;line-height:1.6;color:#414941}.compose-footer{display:flex;justify-content:space-between;align-items:center;padding:12px 20px 15px}.send-button{border:0;border-radius:6px;background:#5b8068;color:white;padding:8px 16px;font-weight:600;font-size:10px}.discard{border:0;background:transparent;color:#929890;font-size:10px}.toast{position:fixed;bottom:22px;left:50%;transform:translate(-50%,15px);opacity:0;pointer-events:none;background:#293b2e;color:#fff;padding:10px 16px;border-radius:8px;font-size:11px;box-shadow:0 5px 20px #1c2b2030;transition:.2s;z-index:20}.toast.visible{opacity:1;transform:translate(-50%,0)} +/* Wasteland: warm paper, weathered ink and rust. */ +body.wasteland{--bg:#eee8db;--panel:#faf6ed;--line:#e6dccb;--text:#373129;--muted:#998a76;--subtle:#f3ede1;--accent:#a75d3d;--accent-soft:#f5e8dc;--shadow:0 2px 10px #44351d0c}body.wasteland .rail{background:#e7dece;border-color:#dfd4c2}body.wasteland .brand-mark{background:#ad6847}body.wasteland .rail-button.active{background:#f1dfcd;color:#a15a39}body.wasteland .rail-button:hover{background:#eee2d2;color:#9a5739}body.wasteland .sidebar,body.wasteland .topbar{background:#faf6ed;border-color:#e6dccb}body.wasteland .account-card{background:#f4eee2;border-color:#ece2d2}body.wasteland .account-avatar{background:#ead8bf;color:#9b633e}body.wasteland .folder.active{background:#f3e6d7;color:#995c3d}body.wasteland .folder.active .nav-glyph{color:#a76645}body.wasteland .count{color:#9e6947}body.wasteland .list-pane,body.wasteland .reader-pane,body.wasteland .compose-modal{background:#faf6ed;border-color:#e6dccb}body.wasteland .compose-button,body.wasteland .send-button,body.wasteland .reply-button.primary{background:#a76645;border-color:#a76645}body.wasteland .compose-button:hover{background:#905538}body.wasteland .message.selected{background:#f5ede0;box-shadow:inset 2px 0 #ad704c}body.wasteland .reader-empty .empty-icon{background:#f3e8d8;color:#a8734c}body.wasteland .reader-button,body.wasteland .reply-button{background:#faf6ed} +@media(max-width:1040px){.sidebar{width:205px;padding-inline:13px}.mail-layout{grid-template-columns:minmax(310px,47%) minmax(320px,1fr);padding:13px;gap:10px}.reader-pane{padding:0 17px 20px}.topbar{padding:0 16px}.message{gap:7px;padding-inline:9px}.list-heading{padding-inline:14px}} +@media(max-width:800px){.sidebar{width:174px;padding-inline:10px}.mail-layout{grid-template-columns:minmax(290px,1fr) minmax(290px,1fr);padding:9px;gap:8px}.reader-pane{padding-inline:13px}.list-heading h2{font-size:17px}.search-wrap{width:170px}} +.page-heading{display:flex;align-items:center;justify-content:space-between;margin:5px 0 20px}.page-heading h2{font-family:'DM Serif Display',Georgia,serif;font-size:28px;font-weight:400;margin:0 0 5px}.page-subtitle{font-size:11px;color:#929991;margin:0}.cal-actions{display:flex;align-items:center;gap:7px}.outline-button{border:1px solid #e3e8e2;background:#fff;border-radius:6px;padding:7px 10px;color:#69736a;font-size:10px}.calendar-card{background:var(--panel);border:1px solid var(--line);border-radius:11px;overflow:hidden;box-shadow:var(--shadow)}.calendar-week{height:38px;display:grid;grid-template-columns:repeat(7,1fr);border-bottom:1px solid var(--line);align-items:center;text-align:center;color:#969d95;font-size:9px;font-weight:600}.calendar-grid{display:grid;grid-template-columns:repeat(7,1fr)}.cal-cell{height:100px;border-right:1px solid #f0f1ee;border-bottom:1px solid #f0f1ee;padding:8px 7px;cursor:pointer;min-width:0}.cal-cell:nth-child(7n){border-right:0}.cal-cell:hover{background:#fafbf9}.cal-cell.outside{background:#fafbf9;color:#d3d7d1}.cal-number{display:grid;place-items:center;width:21px;height:21px;border-radius:50%;font-size:9px;color:#737c73;margin-bottom:4px}.cal-cell.today .cal-number{background:#5b8068;color:#fff}.event-chip{padding:4px 5px;margin:3px 0;border-radius:4px;font-size:8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;background:#edf4ee;color:#5b8068}.event-chip.gold{background:#f7f1e4;color:#a28449}.event-chip.blue{background:#edf2f7;color:#6885a5}.upcoming{margin:20px 0 0}.upcoming h3{font-family:'DM Serif Display',Georgia,serif;font-size:17px;font-weight:400;margin:0 0 8px}.upcoming-row{display:flex;gap:12px;align-items:center;padding:10px 12px;border:1px solid var(--line);background:var(--panel);border-radius:8px;margin:6px 0;max-width:380px}.event-date{width:36px;height:38px;border-radius:7px;background:#edf4ee;color:#62816a;display:grid;place-content:center;text-align:center;font-size:8px;line-height:1.3}.event-date strong{font-size:14px}.gold-date{background:#f7f1e4;color:#a28449}.upcoming-row div{display:grid;gap:4px}.upcoming-row div strong{font-size:10px}.upcoming-row small{font-size:9px;color:#979e97}.contact-search{height:38px;max-width:370px;display:flex;align-items:center;gap:8px;padding:0 12px;background:var(--panel);border:1px solid var(--line);border-radius:8px;color:#8c958c;margin-bottom:15px}.contact-search input{border:0;background:transparent;outline:0;flex:1;font-size:10px}.contacts-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(245px,1fr));gap:10px}.contact-card{position:relative;display:flex;align-items:center;gap:11px;padding:14px;background:var(--panel);border:1px solid var(--line);border-radius:9px;box-shadow:var(--shadow)}.contact-card>.contact-avatar{height:39px;width:39px;font-size:11px;flex:none}.contact-card>div:nth-child(2){min-width:0;display:grid;gap:4px}.contact-card>div:nth-child(2) strong{font-size:10px}.contact-card>div:nth-child(2) span{font-size:9px;color:#838b83;overflow:hidden;text-overflow:ellipsis}.contact-card>div:nth-child(2) small{font-size:8px;color:#a0a69f}.contact-more{margin-left:auto;align-self:flex-start}.contact-email{position:absolute;right:12px;bottom:10px;border:0;background:transparent;color:#829386;font-size:12px}body.wasteland .outline-button,body.wasteland .upcoming-row{background:#faf6ed;border-color:#e6dccb}body.wasteland .calendar-card{background:#faf6ed;border-color:#e6dccb}body.wasteland .cal-cell:hover{background:#f7f0e4}body.wasteland .event-chip{background:#f2e9da;color:#996445}body.wasteland .cal-cell.today .cal-number{background:#a76645} +.account-card[role="button"]{cursor:pointer;appearance:none}.account-card[role="button"]:hover{border-color:#dce5dc}.account-card[role="button"]:focus-visible{outline:2px solid #7eae90;outline-offset:2px}.account-note{font-size:10px;line-height:1.5;color:#848c84;margin:7px 0 12px}.account-note+.compose-line{margin-top:1px}.account-status{font-size:10px;line-height:1.5;color:#9a6346;min-height:15px;margin:9px 0 2px} +.attachment{box-sizing:border-box;width:100%;max-width:420px;min-width:0}.attachment-info{min-width:0;overflow:hidden}.attachment-info strong{max-width:100%;overflow-wrap:anywhere;word-break:break-word;line-height:1.4}.attachment .download{flex:none}.account-list{max-height:55vh;overflow-y:auto}.account-row{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid #edf0ec}.account-row-info{min-width:0;display:grid;gap:5px}.account-row-info strong{font-size:11px;overflow-wrap:anywhere}.account-row-info small{font-size:9px;color:#929991;overflow-wrap:anywhere}.account-row-actions{display:flex;align-items:center;gap:8px;flex:none}.account-current{font-size:9px;color:#61836a}.account-row .outline-button{padding:6px 9px}.account-row .discard{padding:6px} + +/* EP Wasteland follows the Eternity Project Gitea theme palette. */ +body.ep-wasteland{color-scheme:dark;--bg:#161210;--panel:#1b1714;--line:#4a3f33;--text:#d4cbbc;--muted:#a89a86;--subtle:#241e19;--accent:#8fae3d;--accent-soft:#2b301d;--shadow:0 2px 12px #0008;background:var(--bg);color:var(--text)} +body.ep-wasteland .rail,body.ep-wasteland .sidebar-head,body.ep-wasteland .topbar,body.ep-wasteland .modal-head{background:#211b17;border-color:#4a3f33} +body.ep-wasteland .brand-mark,body.ep-wasteland .compose-button,body.ep-wasteland .send-button,body.ep-wasteland .reply-button.primary{background:#8fae3d;border-color:#8fae3d;color:#161210} +body.ep-wasteland .brand-mark{box-shadow:0 3px 10px #0006} +body.ep-wasteland .avatar{background:#4a3f33;color:#e7e2d3} +body.ep-wasteland .compose-button:hover{background:#a2bd5b;border-color:#a2bd5b} +body.ep-wasteland .rail-button{color:#b5a995} +body.ep-wasteland .rail-button:hover,body.ep-wasteland .icon-button:hover,body.ep-wasteland .folder:hover,body.ep-wasteland .label-link:hover{background:#2b241e;color:#e7e2d3} +body.ep-wasteland .rail-button.active,body.ep-wasteland .folder.active{background:#343b22;color:#a2bd5b} +body.ep-wasteland .sidebar,body.ep-wasteland .list-pane,body.ep-wasteland .reader-pane,body.ep-wasteland .page-view{background:#1b1714;color:#d4cbbc} +body.ep-wasteland .sidebar{border-color:#4a3f33} +body.ep-wasteland .account-card,body.ep-wasteland .search-wrap,body.ep-wasteland .toolbar,body.ep-wasteland .calendar-card,body.ep-wasteland .contact-search,body.ep-wasteland .contact-card,body.ep-wasteland .upcoming-row,body.ep-wasteland .compose-modal{background:#211b17;border-color:#4a3f33;color:#d4cbbc} +body.ep-wasteland .account-avatar,body.ep-wasteland .contact-avatar{background:#343b22;color:#a2bd5b} +body.ep-wasteland .account-info span,body.ep-wasteland .storage small,body.ep-wasteland .section-label,body.ep-wasteland .date-line,body.ep-wasteland .page-subtitle,body.ep-wasteland .pagination,body.ep-wasteland .time,body.ep-wasteland .sender-details span,body.ep-wasteland .message-date,body.ep-wasteland .contact-card>div:nth-child(2) span,body.ep-wasteland .contact-card>div:nth-child(2) small,body.ep-wasteland .upcoming-row small{color:#a89a86} +body.ep-wasteland .sidebar-head h1,body.ep-wasteland .breadcrumbs strong,body.ep-wasteland .list-heading h2,body.ep-wasteland .page-heading h2,body.ep-wasteland .upcoming h3,body.ep-wasteland .sender-details strong,body.ep-wasteland .reader-subject,body.ep-wasteland .reader-empty h3,body.ep-wasteland .contact-card>div:nth-child(2) strong,body.ep-wasteland .upcoming-row div strong{color:#e7e2d3} +body.ep-wasteland .eyebrow,body.ep-wasteland .breadcrumbs,body.ep-wasteland .icon-button,body.ep-wasteland .folder,body.ep-wasteland .label-link,body.ep-wasteland .settings-button,body.ep-wasteland .nav-glyph,body.ep-wasteland .search-wrap,body.ep-wasteland .help-button{color:#b5a995} +body.ep-wasteland .online-dot{background:#8fae3d} +body.ep-wasteland .folder.active .nav-glyph,body.ep-wasteland .count,body.ep-wasteland .text-button,body.ep-wasteland .contact-email,body.ep-wasteland .account-current{color:#a2bd5b} +body.ep-wasteland .count{background:#2b301d} +body.ep-wasteland .sidebar-divider,body.ep-wasteland .storage,body.ep-wasteland .storage-bar,body.ep-wasteland .toolbar-divider,body.ep-wasteland .reader-header,body.ep-wasteland .reply-bar,body.ep-wasteland .message,body.ep-wasteland .list-foot,body.ep-wasteland .account-row{border-color:#4a3f33} +body.ep-wasteland .storage-bar{background:#4a3f33} +body.ep-wasteland .storage-bar i{background:#8fae3d} +body.ep-wasteland .message{background:#1b1714} +body.ep-wasteland .message:hover,body.ep-wasteland .message.selected{background:#241e19} +body.ep-wasteland .message.selected{box-shadow:inset 2px 0 #8fae3d} +body.ep-wasteland .sender,body.ep-wasteland .subject,body.ep-wasteland .message.unread .sender,body.ep-wasteland .message.unread .subject{color:#e7e2d3} +body.ep-wasteland .snippet,body.ep-wasteland .list-foot,body.ep-wasteland .reader-body{color:#b5a995} +body.ep-wasteland .star{color:#8f8170} +body.ep-wasteland .star.on{color:#a2bd5b} +body.ep-wasteland .reader-empty{color:#a89a86} +body.ep-wasteland .empty-icon,body.ep-wasteland .event-date,body.ep-wasteland .cal-cell.today .cal-number{background:#343b22;color:#a2bd5b} +body.ep-wasteland .attachment,body.ep-wasteland .file-icon{background:#211b17;border-color:#4a3f33;color:#a2bd5b} +body.ep-wasteland .attachment-info strong,body.ep-wasteland .attachment-info small{color:#d4cbbc} +body.ep-wasteland .reply-button,body.ep-wasteland .outline-button{background:#211b17;border-color:#4a3f33;color:#d4cbbc} +body.ep-wasteland .reply-button:hover,body.ep-wasteland .outline-button:hover{background:#2b241e} +body.ep-wasteland .modal-overlay{background:#000b} +body.ep-wasteland .compose-fields,body.ep-wasteland .compose-footer{background:#1b1714} +body.ep-wasteland .compose-line,body.ep-wasteland .compose-body{border-color:#4a3f33;color:#b5a995} +body.ep-wasteland .compose-line input,body.ep-wasteland .compose-subject,body.ep-wasteland .compose-body,body.ep-wasteland .contact-search input{background:transparent;color:#e7e2d3} +body.ep-wasteland .compose-line input::placeholder,body.ep-wasteland .compose-body::placeholder{color:#8f8170} +body.ep-wasteland .modal-close,body.ep-wasteland .discard{color:#a89a86} +body.ep-wasteland .toast{background:#211b17;color:#e7e2d3;border:1px solid #4a3f33} +body.ep-wasteland .calendar-week{border-color:#4a3f33;color:#a89a86} +body.ep-wasteland .cal-cell{border-color:#342c24;color:#d4cbbc} +body.ep-wasteland .cal-cell:hover,body.ep-wasteland .cal-cell.outside{background:#241e19} +body.ep-wasteland .cal-cell.outside{color:#8f8170} +body.ep-wasteland .cal-number{color:#d4cbbc} +body.ep-wasteland .event-chip,body.ep-wasteland .gold-date{background:#343b22;color:#a2bd5b} +body.ep-wasteland .event-chip.gold,body.ep-wasteland .event-chip.blue{background:#2b241e;color:#d4cbbc} +body.ep-wasteland .tag,body.ep-wasteland .tag.green{background:#343b22;color:#a2bd5b} +body.ep-wasteland .row-check{border-color:#8f8170} +body.ep-wasteland .row-check:checked{accent-color:#8fae3d} + +/* EP Daylight follows the Eternity Project Gitea theme palette. */ +body.ep-daylight{color-scheme:light;--bg:#f1f1e9;--panel:#fbfbf6;--line:#b9c5bc;--text:#263a3d;--muted:#70827b;--subtle:#e9eee4;--accent:#526a2c;--accent-soft:#e9eee4;--shadow:0 2px 10px #11212b12;background:var(--bg);color:var(--text)} +body.ep-daylight .rail,body.ep-daylight .sidebar-head,body.ep-daylight .topbar,body.ep-daylight .modal-head{background:#e8e9df;border-color:#b9c5bc} +body.ep-daylight .brand-mark,body.ep-daylight .compose-button,body.ep-daylight .send-button,body.ep-daylight .reply-button.primary{background:#526a2c;border-color:#526a2c;color:#f1f1e9} +body.ep-daylight .brand-mark{box-shadow:0 3px 8px #11212b20} +body.ep-daylight .compose-button:hover{background:#435722;border-color:#435722} +body.ep-daylight .sidebar,body.ep-daylight .list-pane,body.ep-daylight .reader-pane,body.ep-daylight .page-view{background:#fbfbf6;color:#263a3d} +body.ep-daylight .sidebar{border-color:#b9c5bc} +body.ep-daylight .account-card,body.ep-daylight .search-wrap,body.ep-daylight .toolbar,body.ep-daylight .calendar-card,body.ep-daylight .contact-search,body.ep-daylight .contact-card,body.ep-daylight .upcoming-row,body.ep-daylight .compose-modal{background:#fbfbf6;border-color:#b9c5bc;color:#263a3d} +body.ep-daylight .rail-button,body.ep-daylight .icon-button,body.ep-daylight .folder,body.ep-daylight .label-link,body.ep-daylight .settings-button,body.ep-daylight .nav-glyph,body.ep-daylight .help-button{color:#59706b} +body.ep-daylight .rail-button:hover,body.ep-daylight .icon-button:hover,body.ep-daylight .folder:hover,body.ep-daylight .label-link:hover,body.ep-daylight .reply-button:hover,body.ep-daylight .outline-button:hover{background:#e9eee4;color:#263a3d} +body.ep-daylight .rail-button.active,body.ep-daylight .folder.active{background:#e9eee4;color:#526a2c} +body.ep-daylight .account-avatar,body.ep-daylight .contact-avatar{background:#e9eee4;color:#526a2c} +body.ep-daylight .avatar{background:#b9c5bc;color:#11212b} +body.ep-daylight .sidebar-head h1,body.ep-daylight .breadcrumbs strong,body.ep-daylight .list-heading h2,body.ep-daylight .page-heading h2,body.ep-daylight .upcoming h3,body.ep-daylight .sender-details strong,body.ep-daylight .reader-subject,body.ep-daylight .reader-empty h3,body.ep-daylight .contact-card>div:nth-child(2) strong,body.ep-daylight .upcoming-row div strong{color:#11212b} +body.ep-daylight .eyebrow,body.ep-daylight .breadcrumbs,body.ep-daylight .date-line,body.ep-daylight .page-subtitle,body.ep-daylight .section-label,body.ep-daylight .account-info span,body.ep-daylight .storage small,body.ep-daylight .pagination,body.ep-daylight .time,body.ep-daylight .sender-details span,body.ep-daylight .message-date,body.ep-daylight .contact-card>div:nth-child(2) span,body.ep-daylight .contact-card>div:nth-child(2) small,body.ep-daylight .upcoming-row small{color:#59706b} +body.ep-daylight .online-dot,body.ep-daylight .storage-bar i{background:#8fae3d} +body.ep-daylight .folder.active .nav-glyph,body.ep-daylight .count,body.ep-daylight .text-button,body.ep-daylight .contact-email,body.ep-daylight .account-current{color:#526a2c} +body.ep-daylight .count{background:#e9eee4} +body.ep-daylight .sidebar-divider,body.ep-daylight .storage,body.ep-daylight .reader-header,body.ep-daylight .reply-bar,body.ep-daylight .message,body.ep-daylight .list-foot,body.ep-daylight .account-row,body.ep-daylight .calendar-week,body.ep-daylight .cal-cell{border-color:#b9c5bc} +body.ep-daylight .storage-bar,body.ep-daylight .toolbar-divider{background:#b9c5bc} +body.ep-daylight .message{background:#fbfbf6} +body.ep-daylight .message:hover,body.ep-daylight .message.selected{background:#e9eee4} +body.ep-daylight .message.selected{box-shadow:inset 2px 0 #8fae3d} +body.ep-daylight .sender,body.ep-daylight .subject,body.ep-daylight .message.unread .sender,body.ep-daylight .message.unread .subject{color:#11212b} +body.ep-daylight .snippet,body.ep-daylight .list-foot,body.ep-daylight .reader-body{color:#59706b} +body.ep-daylight .star{color:#70827b} +body.ep-daylight .star.on{color:#526a2c} +body.ep-daylight .reader-empty{color:#59706b} +body.ep-daylight .empty-icon,body.ep-daylight .event-date,body.ep-daylight .cal-cell.today .cal-number{background:#e9eee4;color:#526a2c} +body.ep-daylight .attachment,body.ep-daylight .file-icon{background:#fbfbf6;border-color:#b9c5bc;color:#526a2c} +body.ep-daylight .attachment-info strong{color:#263a3d} +body.ep-daylight .attachment-info small{color:#59706b} +body.ep-daylight .reply-button,body.ep-daylight .outline-button{background:#fbfbf6;border-color:#b9c5bc;color:#263a3d} +body.ep-daylight .tag,body.ep-daylight .tag.green,body.ep-daylight .event-chip{background:#e9eee4;color:#526a2c} +body.ep-daylight .event-chip.gold,body.ep-daylight .event-chip.blue,body.ep-daylight .gold-date{background:#e8e9df;color:#59706b} +body.ep-daylight .cal-cell{color:#263a3d} +body.ep-daylight .cal-cell:hover,body.ep-daylight .cal-cell.outside{background:#e9eee4} +body.ep-daylight .cal-cell.outside{color:#70827b} +body.ep-daylight .cal-number{color:#263a3d} +body.ep-daylight .modal-overlay{background:#11212b55} +body.ep-daylight .compose-fields,body.ep-daylight .compose-footer{background:#fbfbf6} +body.ep-daylight .compose-line,body.ep-daylight .compose-body{border-color:#b9c5bc;color:#59706b} +body.ep-daylight .compose-line input,body.ep-daylight .compose-subject,body.ep-daylight .compose-body,body.ep-daylight .contact-search input{background:transparent;color:#11212b} +body.ep-daylight .compose-line input::placeholder,body.ep-daylight .compose-body::placeholder{color:#70827b} +body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b} +body.ep-daylight .toast{background:#11212b;color:#f1f1e9} +body.ep-daylight .row-check:checked{accent-color:#526a2c}