Ver V0.1.16 Add Android version to project

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

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

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

After

Width:  |  Height:  |  Size: 3.9 KiB

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

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">ep-mail</string>
<string name="title_activity_main">ep-mail</string>
<string name="package_name">studio.daybreak.mail</string>
<string name="custom_url_scheme">studio.daybreak.mail</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -0,0 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
+30
View File
@@ -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
}
+3
View File
@@ -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')
+22
View File
@@ -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
Binary file not shown.
+7
View File
@@ -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
+251
View File
@@ -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" "$@"
+94
View File
@@ -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
+5
View File
@@ -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'
+16
View File
@@ -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'
}
+8
View File
@@ -0,0 +1,8 @@
{
"appId": "studio.daybreak.mail",
"appName": "ep-mail",
"webDir": "www",
"server": {
"androidScheme": "https"
}
}
+1
View File
@@ -62,6 +62,7 @@
<div id="modal-root"></div> <div id="modal-root"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div> <div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="app.js"></script> <script src="app.js"></script>
<script src="platform-bridge.js"></script>
<script src="mail-ui.js"></script> <script src="mail-ui.js"></script>
<script src="productivity.js"></script> <script src="productivity.js"></script>
<script src="account-ui.js"></script> <script src="account-ui.js"></script>
+1195 -2
View File
File diff suppressed because it is too large Load Diff
+11 -2
View File
@@ -15,11 +15,17 @@
"dist:linux": "electron-builder --linux AppImage deb", "dist:linux": "electron-builder --linux AppImage deb",
"dist:linux:appimage": "electron-builder --linux AppImage", "dist:linux:appimage": "electron-builder --linux AppImage",
"dist:linux:deb": "electron-builder --linux deb", "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": { "devDependencies": {
"@capacitor/cli": "^8.5.2",
"electron": "44.5.1", "electron": "44.5.1",
"electron-builder": "26.17.0" "electron-builder": "26.17.0",
"esbuild": "^0.28.2"
}, },
"build": { "build": {
"appId": "studio.daybreak.mail", "appId": "studio.daybreak.mail",
@@ -27,6 +33,7 @@
"asar": true, "asar": true,
"files": [ "files": [
"index.html", "index.html",
"platform-bridge.js",
"styles.css", "styles.css",
"branding.css", "branding.css",
"app.js", "app.js",
@@ -71,6 +78,8 @@
"electron-winstaller@5.4.0": true "electron-winstaller@5.4.0": true
}, },
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
"ical.js": "^2.2.1", "ical.js": "^2.2.1",
"imapflow": "2.2.1", "imapflow": "2.2.1",
"mailparser": "3.9.33", "mailparser": "3.9.33",
+545
View File
@@ -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 *)
*/
+31
View File
@@ -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)
};
}
+17
View File
@@ -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;
}
+43
View File
@@ -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;
});
+1 -1
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v2'; 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('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('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'))))}); 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'))))});
+26
View File
@@ -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=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.displayName||account.email)}</strong><small>${esc(account.email)} · ${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
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);
+17
View File
@@ -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=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[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=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.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=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div><div class="reader-body">${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('')}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;$('#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 `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send&nbsp; ↗</button></div></div></div>`;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);
+30
View File
@@ -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;
}
+38
View File
@@ -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=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.username)}</strong><small>${esc(account.serverUrl)} · ${account.collections.length} ${type==='caldav'?'calendars':'address books'}</small><small>${account.collections.map(collection=>esc(collection.name)).join(', ')}</small></div><div class="account-row-actions">${account.id===activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-dav-activate="${esc(account.id)}">Use</button>`}<button class="discard" data-dav-remove="${esc(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${label} servers</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||`<p class="account-note">No ${label} server connected.</p>`}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-dav-server">+ Add server</button></div></div></div>`;
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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Connect ${label} server</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Use the DAV server URL from your provider. Your password is encrypted in the OS credential store; secure HTTPS is required.</p><label class="compose-line"><span>Server URL</span><input id="dav-server-url" type="url" placeholder="https://dav.example.com/remote.php/dav"></label><label class="compose-line"><span>Username</span><input id="dav-username" autocomplete="username" placeholder="name@example.com"></label><label class="compose-line"><span>Password</span><input id="dav-password" type="password" autocomplete="current-password" placeholder="App password"></label><p id="dav-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="dav-cancel">Cancel</button><button class="send-button" id="dav-connect">Test &amp; connect</button></div></div></div>`;
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);
+10
View File
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="12" fill="#0a0c0b"/>
<g fill="none" stroke="#eee9de">
<circle cx="32" cy="32" r="27" stroke-width="3"/>
<path d="M32 4v56" stroke-width="4"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="3" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="3" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="2" opacity=".75" transform="rotate(45 32 32)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 552 B

+71
View File
@@ -0,0 +1,71 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4f5f1">
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'none'">
<title>ep-mail</title>
<link rel="manifest" href="manifest.webmanifest">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="branding.css">
</head>
<body>
<div class="app-shell">
<aside class="rail" aria-label="Main navigation">
<div class="brand-mark" title="ep-mail"><img id="brand-logo" src="logo-ep-daylight.svg" alt="Eternity Project"></div>
<button class="rail-button active" data-view="mail" aria-label="Mail"><span>✉</span></button>
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
<div class="rail-spacer"></div>
</aside>
<aside class="sidebar">
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
<button class="folder" data-folder="Snoozed"><span class="nav-glyph">◷</span><span>Snoozed</span></button>
<button class="folder" data-folder="Sent"><span class="nav-glyph">↗</span><span>Sent</span></button>
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
</nav>
<div class="sidebar-divider"></div>
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
<button class="label-link" data-label="Travel"><i class="label-dot dot-blue"></i>Travel</button>
<button class="label-link" data-label="Personal"><i class="label-dot dot-green"></i>Personal</button>
<div id="custom-labels"></div>
<div class="sidebar-bottom"><div class="storage"><div class="storage-top"><span>Storage</span><span>4.2 / 15 GB</span></div><div class="storage-bar"><i></i></div><small>Plenty of room for the good things.</small></div><button class="settings-button" id="settings-button"><span>⚙</span> Settings</button></div>
</aside>
<main class="main-area">
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button></div></header>
<section id="mail-view" class="content-view mail-layout">
<div class="list-pane">
<div class="list-heading"><div><div class="date-line" id="today-label">MONDAY, OCTOBER 4</div><h2 id="welcome-heading">Good morning<span id="greeting-name" hidden></span></h2></div><button class="compose-button" id="compose"><span>+</span> Compose</button></div>
<div class="toolbar"><button class="tool-checkbox" id="select-all" aria-label="Select all">□</button><button class="icon-button" id="refresh" title="Refresh">↻</button><span class="toolbar-divider"></span><button class="icon-button" id="archive-selected" title="Archive">▱</button><button class="icon-button" id="delete-selected" title="Delete">⌫</button><button class="icon-button" id="mark-unread" title="Mark unread">✉</button><span class="toolbar-spacer"></span><button class="icon-button" id="previous-page" title="Previous page">‹</button><span class="pagination" id="pagination">1–8 of 24</span><button class="icon-button" id="next-page" title="Next page">›</button></div>
<div class="message-list" id="message-list" aria-label="Messages"></div>
<div class="list-foot"><span><i class="online-dot"></i> <span id="mail-status">All caught up with your mail</span></span><button class="text-button" id="load-more">Load more <span>↓</span></button></div>
</div>
<article class="reader-pane" id="reader-pane"></article>
</section>
<section id="calendar-view" class="content-view page-view hidden"></section>
<section id="contacts-view" class="content-view page-view hidden"></section>
</main>
</div>
<div id="modal-root"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="app.js"></script>
<script src="platform-bridge.js"></script>
<script src="mail-ui.js"></script>
<script src="productivity.js"></script>
<script src="account-ui.js"></script>
<script src="dav-ui.js"></script>
</body>
</html>
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
<g fill="none" stroke="#181b19">
<circle cx="32" cy="32" r="28" stroke-width="2"/>
<path d="M32 3v58" stroke-width="3"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 534 B

+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
<g fill="none" stroke="#e7e2d3">
<circle cx="32" cy="32" r="28" stroke-width="2"/>
<path d="M32 3v58" stroke-width="3"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 534 B

+237
View File
@@ -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 = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><p class="account-note">This display name is saved for this mailbox and used on outgoing messages. IMAP uses STARTTLS on port 143 · SMTP uses STARTTLS on port 587.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save &amp; reconnect' : 'Test &amp; connect'}</button></div></div></div>`;
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(() => {});
}
+10
View File
@@ -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"}]
}
+545
View File
@@ -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 *)
*/
+49
View File
@@ -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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
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])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`;
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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; 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+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}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=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#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=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;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)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#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=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})}
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')}
function 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='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
const baseMessageRenderer=renderList;
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#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='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';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);
+5
View File
@@ -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'))))});
+116
View File
File diff suppressed because one or more lines are too long