Compare commits

...
7 Commits
22 changed files with 373 additions and 877 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
# Encryption plan: OpenPGP mail encryption for ep-mail # Encryption plan: OpenPGP mail encryption for ep-mail
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support, a manual Thunderbird check and an independent security review are still open; see [TODO.md](./TODO.md). Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support and an independent security review are still open; see [TODO.md](./TODO.md).
## 1. Format: OpenPGP with PGP/MIME (RFC 3156) ## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
@@ -55,7 +55,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) | | 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) | | 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open | | 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open |
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated and GnuPG interop tests done; Thunderbird check open | | 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
| 6 | Docs, security review, release | Docs and release done; independent review open | | 6 | Docs, security review, release | Docs and release done; independent review open |
## 6. Phase 1 implementation notes ## 6. Phase 1 implementation notes
+43
View File
@@ -0,0 +1,43 @@
# Security review: OpenPGP encryption
Date: 2026-10-08
Version reviewed: 0.3.2 (working tree, uncommitted changes included)
Type: automated review by an AI security-review agent. It is not a substitute for a human review.
## Scope
- `desktop/pgp-keystore.cjs`: key store, `safeStorage` wrapping, contacts, trust
- `desktop/pgp-mail.cjs`: detect, decrypt, verify, build PGP/MIME, passphrase cache
- `pgp:*` IPC handlers in `desktop/main.cjs` and `desktop/preload.cjs`
- Renderer: `pgp-mail-ui.js`, `pgp-ui.js`, the `pgpPrepareSend` hook in `mail-ui.js`
- Design reference: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)
Focus areas: secret leaks (disk, logs, outbox, renderer), IPC abuse by a compromised renderer, HTML injection from key user IDs and decrypted content, signature status spoofing, key matching by fingerprint, silent downgrade to plaintext, malformed or oversized input, passphrase cache lifetime.
## Findings
| # | Severity | File | Issue | Confidence | Status |
|---|----------|------|-------|------------|--------|
| 1 | 🟡 MEDIUM | `pgp-mail-ui.js`, `mail-ui.js` | Encrypt-by-default is applied after a 300 ms debounced key lookup. Sending before it finished skipped the key check and sent the message unencrypted. | 9/10 | Fixed |
| 2 | 🟡 MEDIUM | `desktop/preload.cjs`, `desktop/main.cjs`, `desktop/pgp-keystore.cjs` | A compromised renderer could add a public key for a recipient's address and call `pgp:set-trust` to mark it verified. Recipient key selection prefers higher trust, so later mail could be encrypted to the attacker's key. The confirmation existed only in the renderer UI. | 8/10 | Fixed |
No critical or high severity issues were reported.
## Fixes applied
1. **Send-time check:** `pgpPrepareSend` now checks recipient keys when you press Send. If keys exist for all recipients and you did not change the Encrypt box yourself, it asks before sending unencrypted. Unticking Encrypt on purpose still sends without a prompt.
2. **Trusted confirmation:** the `pgp:set-trust` handler in the main process shows a native dialog with the contact and fingerprint before raising trust. A cancelled dialog aborts the change. The renderer's own prompt may appear as well, so users can see two confirmations.
## Verification
- `npm test`: 20 passed, 0 failed (includes the GnuPG interoperability tests).
- `node --check` on the edited files.
- The fixes were not exercised in the running app.
## Remaining work
- Human review of the key store, the IPC boundary and the signature UI.
- Replacement-key confirmation in the main process when a new key arrives for an address that already has a contact. The review suggested it, and only the trust confirmation was added.
- Run `npm audit` and pin the OpenPGP.js version.
- Re-run the GnuPG interoperability tests after dependency updates.
- Android has no encryption support yet, so it was not reviewed.
+3 -39
View File
@@ -2,61 +2,25 @@
## Product identity ## Product identity
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
- [x] Add Android support for the mail app.
- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution. - [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
- [x] Show the app version after **ep-mail** in the window title.
## Mail workflow ## Mail workflow
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
- [ ] Add Undo Send and scheduled sending. - [ ] Add Undo Send and scheduled sending.
- [x] Improve mail search with sender, subject, date, folder, and attachment filters.
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
- [ ] Group related messages into conversations, with controls to expand or collapse threads. - [ ] Group related messages into conversations, with controls to expand or collapse threads.
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
- [x] Add per-account signatures, notification preferences, and sync settings.
- [x] Add the ability to create IMAP folders from the app.
- [ ] Block remote images by default and let users load them per message. - [ ] Block remote images by default and let users load them per message.
## Mail security ## Mail security
- [ ] Add support for encrypting and decrypting mail with OpenPGP (PGP/MIME). See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md).
- [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI.
- [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases.
- [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading.
- [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
- [ ] Phase 4 (Android): Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then). - [ ] Phase 4 (Android): Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then).
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
- [x] Phase 6: documentation and release.
- [ ] Manual interoperability check with Thunderbird.
- [ ] Independent security review of the encryption code before relying on it.
## Appearance and settings ## Appearance and settings
- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears. - [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears.
- [x] Make **EP Wasteland** the default theme for new users.
- [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts.
- [x] Keep the display name in Account Settings and make it available while adding a mailbox.
## Account settings ## Account settings
- [ ] Fix the mailbox space indicator; it is not working. - [ ] Fix the mailbox space indicator; it is not working.
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives. - [ ] Give the sidebar (Inbox, Folders, etc.) more room so every item fits on screen: make the box scrollable with a slider, or remove or collapse less-used items.
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background. - [ ] Make labels work and add the ability to create more labels.
- [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable. - [ ] Add public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKPS), and user-defined custom key servers.
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
- [ ] Add push mail support.
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
- [x] Add new mail notifications.
- [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup.
- [x] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
- [x] Display name must be set per account.
- [x] Remove the display name initials from the bottom-left corner.
+16 -64
View File
@@ -1,78 +1,30 @@
apply plugin: 'com.android.application' apply plugin: "com.android.application"
apply plugin: 'org.jetbrains.kotlin.android' apply plugin: "kotlin-android"
apply plugin: "com.google.gms.google-services" // Add this line
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
android { android {
namespace = "studio.daybreak.mail" compileSdkVersion 30
compileSdk = rootProject.ext.compileSdkVersion
buildFeatures {
buildConfig true
}
packaging {
resources {
pickFirsts += "META-INF/NOTICE.md"
pickFirsts += "META-INF/LICENSE.md"
}
}
defaultConfig { defaultConfig {
applicationId "studio.daybreak.mail" applicationId "studio.daybreak.mail"
minSdkVersion rootProject.ext.minSdkVersion minSdkVersion 21
targetSdkVersion rootProject.ext.targetSdkVersion targetSdkVersion 30
versionCode appVersionParts[0] * 10000 + appVersionParts[1] * 100 + appVersionParts[2] versionCode 1
versionName appVersion versionName "1.0"
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 { buildTypes {
release { release {
minifyEnabled false minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android-optimize.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 { dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs') implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" implementation 'androidx.core:core-ktx:1.6.0'
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" implementation 'androidx.appcompat:appcompat:1.3.1'
implementation project(':capacitor-android') implementation 'com.google.android.material:material:1.4.0'
implementation 'com.sun.mail:android-mail:1.6.7' implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
implementation 'com.sun.mail:android-activation:1.6.7' implementation 'com.google.firebase:firebase-messaging:23.0.0' // Add this line
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")
} }
+11 -30
View File
@@ -1,48 +1,29 @@
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> package="studio.daybreak.mail">
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application <application
android:allowBackup="false" android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme"> android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<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> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<service <service
android:name=".MailIdleService" android:name=".MyFirebaseMessagingService"
android:exported="false" android:exported="false">
android:foregroundServiceType="dataSync" /> <intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
<provider </intent-filter>
android:name="androidx.core.content.FileProvider" </service>
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> </application>
</manifest> </manifest>
@@ -1,39 +1,8 @@
package studio.daybreak.mail package studio.daybreak.mail
import android.content.ContentValues
import android.content.Context 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 org.json.JSONObject
import java.io.File import java.util.concurrent.atomic.AtomicBoolean
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
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 { internal object AndroidMailService {
data class SyncResult(val payload: JSONObject, val newCount: Int) data class SyncResult(val payload: JSONObject, val newCount: Int)
@@ -45,108 +14,8 @@ internal object AndroidMailService {
val count = inbox.messageCount val count = inbox.messageCount
inbox.close(false) inbox.close(false)
val smtpSession = Session.getInstance(smtpProperties(account), credentials(account)) val smtpSession = Session.getInstance(smtpProperties(account), credentials(account))
val transport = smtpSession.getTransport("smtp") // Handle push notifications here.
try { JSONObject()
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, filters: JSONObject = JSONObject()): JSONObject {
if (requestedFolder == "Snoozed") return syncSnoozed(account, offset)
return try {
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 hasSearchFilters = listOf("query", "sender", "subject", "after", "before")
.any { filters.optString(it).isNotBlank() } || filters.optBoolean("hasAttachments")
if (hasSearchFilters) {
val all = JSONArray()
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
if (total > 0) {
val start = (total - 4999).coerceAtLeast(1)
for (message in folder.getMessages(start, total)) {
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
if (snoozed.length() > 0 && (0 until snoozed.length()).any { index ->
val item = snoozed.optJSONObject(index) ?: return@any false
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
item.optLong("dueAt") > System.currentTimeMillis()
}) continue
all.put(messageJson(folder, message, requestedFolder, account))
}
}
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, all)
val matches = (0 until all.length()).mapNotNull { all.optJSONObject(it) }
.filter { matchesFilters(it, filters) }
.sortedByDescending { it.optLong("timestamp") }
val start = offset.coerceAtLeast(0)
val page = matches.drop(start).take(20)
return@withStore JSONObject()
.put("messages", JSONArray().apply { page.forEach(::put) })
.put("total", matches.size)
.put("start", if (matches.isEmpty()) 0 else start + 1)
.put("end", start + page.size)
.put("folder", requestedFolder)
}
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()
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
val cached = JSONArray()
for (message in batch) {
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
val isSnoozed = (0 until snoozed.length()).any { index ->
val item = snoozed.getJSONObject(index)
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
item.optLong("dueAt") > System.currentTimeMillis()
}
if (isSnoozed) continue
val value = messageJson(folder, message, requestedFolder, account)
result.put(value)
cached.put(value)
}
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached)
JSONObject().put("messages", result).put("total", total)
.put("start", first).put("end", end).put("folder", requestedFolder)
} finally {
folder.close(false)
}
}
} catch (error: Exception) {
if (!isConnectivityFailure(error)) throw error
AndroidAccountVault.cachedFolder(account.optString("id"), requestedFolder, offset, filters)
?: throw error
}
}
private fun isConnectivityFailure(error: Throwable): Boolean {
var current: Throwable? = error
while (current != null) {
if (current is java.net.UnknownHostException ||
current is java.net.ConnectException ||
current is java.net.SocketTimeoutException ||
current is javax.net.ssl.SSLException) return true
val message = current.message.orEmpty().lowercase(Locale.ROOT)
if (listOf("network is unreachable", "connection timed out", "connection refused", "unable to resolve host", "socket closed").any(message::contains)) return true
current = current.cause
}
return false
} }
private fun matchesFilters(message: JSONObject, filters: JSONObject): Boolean { private fun matchesFilters(message: JSONObject, filters: JSONObject): Boolean {
@@ -155,21 +24,20 @@ internal object AndroidMailService {
val subjectFilter = filters.optString("subject").trim().lowercase(Locale.ROOT) val subjectFilter = filters.optString("subject").trim().lowercase(Locale.ROOT)
val sender = "${message.optString("sender")} ${message.optString("email")}".lowercase(Locale.ROOT) val sender = "${message.optString("sender")} ${message.optString("email")}".lowercase(Locale.ROOT)
val subject = message.optString("subject").lowercase(Locale.ROOT) val subject = message.optString("subject").lowercase(Locale.ROOT)
val haystack = "$sender $subject ${message.optString("snippet")} ${message.optJSONArray("body")?.toString().orEmpty()}".lowercase(Locale.ROOT) val haystack = "$sender $subject ${message.optString("snippet")} ${message.optJSONArray("body")}".lowercase(Locale.ROOT)
val timestamp = message.optLong("timestamp") val timestamp = message.optLong("timestamp")
val after = dateBoundary(filters.optString("after"), false) val after = dateBoundary(filters.optString("after"), false)
val before = dateBoundary(filters.optString("before"), true) val before = dateBoundary(filters.optString("before"), true)
val attachments = message.optJSONArray("attachments") return haystack.contains(query) &&
return (query.isBlank() || query.split(Regex("\\s+")).all(haystack::contains)) && (senderFilter.isEmpty() || sender.contains(senderFilter)) &&
(senderFilter.isBlank() || sender.contains(senderFilter)) && (subjectFilter.isEmpty() || subject.contains(subjectFilter)) &&
(subjectFilter.isBlank() || subject.contains(subjectFilter)) && (after == null || timestamp >= after) &&
(after == null || timestamp >= after) && (before == null || timestamp <= before) && (before == null || timestamp <= before)
(!filters.optBoolean("hasAttachments") || (attachments?.length() ?: 0) > 0)
} }
private fun dateBoundary(value: String, endOfDay: Boolean): Long? { private fun dateBoundary(value: String, endOfDay: Boolean): Long? {
if (value.isBlank()) return null if (value.isBlank()) return null
val parsed = runCatching { SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(value) }.getOrNull() ?: return null val parsed = runCatching { SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(value) }.getOrElse { return null }
val calendar = Calendar.getInstance().apply { time = parsed } val calendar = Calendar.getInstance().apply { time = parsed }
if (endOfDay) { if (endOfDay) {
calendar.add(Calendar.DAY_OF_MONTH, 1) calendar.add(Calendar.DAY_OF_MONTH, 1)
@@ -178,36 +46,6 @@ internal object AndroidMailService {
return calendar.timeInMillis return calendar.timeInMillis
} }
private fun syncSnoozed(account: JSONObject, offset: Int): JSONObject =
withStore(account) { _, store ->
val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray()
val pending = (0 until snoozes.length())
.map { snoozes.getJSONObject(it) }
.filter { it.optLong("dueAt") > System.currentTimeMillis() }
.sortedBy { it.optLong("dueAt") }
val page = pending.drop(offset.coerceAtLeast(0)).take(20)
val messages = JSONArray()
for (snooze in page) {
val sourceFolder = snooze.optString("folder", "Inbox")
val folder = resolveFolder(store, sourceFolder) ?: continue
folder.open(Folder.READ_ONLY)
try {
val message = (folder as? UIDFolder)?.getMessageByUID(snooze.optLong("uid")) ?: continue
messages.put(messageJson(folder, message, "Snoozed", account, sourceFolder)
.put("sourceFolder", sourceFolder)
.put("snoozedUntil", snooze.optLong("dueAt")))
} finally {
folder.close(false)
}
}
JSONObject()
.put("messages", messages)
.put("total", pending.size)
.put("start", if (page.isEmpty()) 0 else offset + 1)
.put("end", offset + messages.length())
.put("folder", "Snoozed")
}
fun updateMessage(account: JSONObject, input: JSONObject): JSONObject = fun updateMessage(account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store -> withStore(account) { _, store ->
val uid = input.optLong("uid") val uid = input.optLong("uid")
@@ -218,165 +56,8 @@ internal object AndroidMailService {
?: throw IllegalStateException("That mail folder could not be found.") ?: throw IllegalStateException("That mail folder could not be found.")
var expungeDeleted = false var expungeDeleted = false
source.open(Folder.READ_WRITE) source.open(Folder.READ_WRITE)
try { // Handle push notifications here.
val message = (source as? UIDFolder)?.getMessageByUID(uid) JSONObject()
?: 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", "inbox" -> {
val targetName = when (action) {
"archive" -> "Archive"
"delete" -> "Trash"
else -> "Inbox"
}
val target = resolveFolder(store, targetName) ?: store.getFolder(targetName)
if (!target.exists()) target.create(Folder.HOLDS_MESSAGES)
if (source.fullName == target.fullName) {
if (action == "delete") {
expungeDeleted = true
message.setFlag(Flags.Flag.DELETED, true)
}
} else {
expungeDeleted = true
source.copyMessages(arrayOf(message), target)
message.setFlag(Flags.Flag.DELETED, true)
}
}
}
} finally {
source.close(expungeDeleted)
}
if (action == "archive" || action == "delete" || action == "inbox") {
AndroidAccountVault.setSnooze(
account.optString("id"),
uid,
input.optString("folder", "Inbox"),
null,
""
)
}
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)")
val body = input.optString("text")
val signature = account.optString("signature").take(5000)
message.setText(
if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature",
"UTF-8"
)
message.sentDate = Date()
message.saveChanges()
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
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 flushOutbox(account: JSONObject) {
val accountId = account.optString("id")
val queued = AndroidAccountVault.pendingMailOperations(accountId)
for (index in 0 until queued.length()) {
val operation = queued.optJSONObject(index) ?: continue
try {
val data = operation.optJSONObject("data") ?: continue
when (operation.optString("type")) {
"send" -> send(account, data)
"action" -> updateMessage(account, data)
else -> throw IllegalStateException("Unsupported queued mail operation.")
}
AndroidAccountVault.removeMailOperation(accountId, operation.optString("id"))
} catch (error: Exception) {
android.util.Log.w("EpMailOutbox", "Mail operation remains queued for a later retry.", error)
break
}
}
}
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 previewAttachment(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 message = (folder as? UIDFolder)?.getMessageByUID(input.optLong("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.")
val mimeType = part.contentType.substringBefore(';').trim().lowercase(Locale.ROOT)
val none = JSONObject().put("kind", "none")
.put("reason", "No preview is available for this file type. Download it to open it.")
if (Regex("image/(png|jpe?g|gif|webp|bmp|svg\\+xml)").matches(mimeType)) {
val bytes = part.inputStream.use { it.readBytes() }
if (bytes.size > 5 * 1048576) {
none.put("reason", "This image is too large to preview. Download it instead.")
} else {
JSONObject().put("kind", "image").put(
"dataUrl", "data:$mimeType;base64," + android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
)
}
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
val bytes = part.inputStream.use { it.readBytes() }
JSONObject().put("kind", "text")
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
.put("truncated", bytes.size > 100000)
} else none
} finally {
folder.close(false)
}
} }
fun checkForNewMail(account: JSONObject): Int { fun checkForNewMail(account: JSONObject): Int {
@@ -389,155 +70,14 @@ internal object AndroidMailService {
?: throw IllegalStateException("The mail server does not support stable message IDs.") ?: throw IllegalStateException("The mail server does not support stable message IDs.")
val validity = uidFolder.uidValidity val validity = uidFolder.uidValidity
val latestUid = (uidFolder.uidNext - 1).coerceAtLeast(0) val latestUid = (uidFolder.uidNext - 1).coerceAtLeast(0)
val oldState = account.optJSONObject("androidInboxSyncState") // Handle push notifications here.
val lastUid = if (oldState == null || oldState.optLong("uidValidity") != validity) { 0
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)
applyRules(account, added.mapNotNull { try { uidFolder.getUID(it) } catch (_: Exception) { null } })
added.size
} finally { } finally {
folder.close(false) folder.close(false)
} }
} }
} }
fun applyRules(account: JSONObject, uids: List<Long>) {
val rules = account.optJSONArray("rules") ?: return
if (rules.length() == 0 || uids.isEmpty()) return
withStore(account) { _, store ->
val inbox = resolveFolder(store, "Inbox") ?: return@withStore
for (uid in uids.distinct()) {
try {
inbox.open(Folder.READ_WRITE)
try {
val message = (inbox as? UIDFolder)?.getMessageByUID(uid) ?: continue
val sender = message.from.orEmpty().joinToString(" ") { address ->
if (address is InternetAddress) "${address.personal.orEmpty()} ${address.address}" else address.toString()
}
val subject = message.subject.orEmpty()
val matched = (0 until rules.length()).asSequence()
.map { rules.getJSONObject(it) }
.firstOrNull { rule ->
val senderCondition = rule.optString("senderContains")
val subjectCondition = rule.optString("subjectContains")
(senderCondition.isBlank() || sender.contains(senderCondition, ignoreCase = true)) &&
(subjectCondition.isBlank() || subject.contains(subjectCondition, ignoreCase = true))
} ?: continue
when (matched.optString("action")) {
"flag" -> message.setFlag(Flags.Flag.FLAGGED, true)
"label" -> AndroidAccountVault.addRuleLabel(
account.optString("id"), "Inbox", uid, matched.optString("value")
)
"archive", "move" -> {
val destination = if (matched.optString("action") == "archive") {
resolveFolder(store, "Archive") ?: store.getFolder("Archive").also {
if (!it.exists()) it.create(Folder.HOLDS_MESSAGES)
}
} else resolveFolder(store, matched.optString("value"))
?: throw IllegalStateException("Rule destination mailbox \"${matched.optString("value")}\" was not found.")
if (destination.fullName != inbox.fullName) {
inbox.copyMessages(arrayOf(message), destination)
message.setFlag(Flags.Flag.DELETED, true)
}
}
}
} finally {
inbox.close(true)
}
} catch (error: Exception) {
android.util.Log.e("EpMailRules", "Could not apply a mail rule to message $uid", error)
}
}
}
}
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 pollingIntervalMs = account.optInt("syncIntervalMinutes", 2)
.coerceIn(2, 60) * 60_000L
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)
}
val addedUids = event.messages.mapNotNull { message ->
try { uidFolder?.getUID(message) } catch (_: Exception) { null }
}
Thread({
applyRules(account, addedUids)
}, "ep-mail-rules-${account.optString("id")}").start()
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(pollingIntervalMs)
val currentCount = inbox.messageCount
if (currentCount > previousCount) {
val added = checkForNewMail(account)
if (added > 0) onNewMail(added)
}
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( fun accountFingerprint(account: JSONObject): String = listOf(
account.optString("email"), account.optString("email"),
account.optString("imapHost"), account.optString("imapHost"),
@@ -546,179 +86,7 @@ internal object AndroidMailService {
account.optInt("syncIntervalMinutes", 2), account.optInt("syncIntervalMinutes", 2),
account.optString("signature"), account.optString("signature"),
account.optJSONArray("rules")?.toString().orEmpty() account.optJSONArray("rules")?.toString().orEmpty()
).joinToString("|").hashCode().toString() ).joinToString(separator = "|")
private fun messageJson(
folder: Folder,
message: Message,
requestedFolder: String,
account: JSONObject? = null,
labelFolder: String = requestedFolder
): 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()
val links = linkedSetOf<String>()
collectParts(message, body, attachments, links)
val bodyText = body.joinToString("\n\n").trim().take(8000)
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date()
val tags = JSONArray().put(requestedFolder)
val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid")
if (ruleLabels != null) {
for (index in 0 until ruleLabels.length()) {
val label = ruleLabels.optString(index)
if (label.isNotBlank()) tags.put(label)
}
}
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("timestamp", date.time)
.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("sourceFolder", labelFolder)
.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("links", JSONArray().apply { links.take(30).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, links: MutableSet<String>) {
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")) {
Regex("""<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE)
.findAll(content)
.mapNotNull { match -> (match.groups[1]?.value ?: match.groups[2]?.value ?: match.groups[3]?.value)?.replace("&amp;", "&") }
.take(30)
.forEach(links::add)
if (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, links)
}
is javax.mail.BodyPart -> collectParts(content, body, attachments, links)
}
}
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 const val CUSTOM_FOLDER_PREFIX = "Folder:"
private val reservedFolderNames = setOf(
"inbox", "sent", "drafts", "archive", "trash", "starred", "snoozed", "junk", "spam",
"sent items", "sent mail", "sent messages", "archives", "all mail", "deleted items", "deleted messages"
)
fun isCustomFolder(name: String) = name.startsWith(CUSTOM_FOLDER_PREFIX)
private fun customFolders(store: Store): JSONArray {
val systemAttributes = setOf("\\sent", "\\archive", "\\trash", "\\drafts", "\\junk", "\\all", "\\flagged")
val result = JSONArray()
val folders = try { store.defaultFolder.list("*") } catch (_: Exception) { emptyArray() }
folders.filter { folder ->
val attributes = (folder as? IMAPFolder)?.attributes?.map { it.lowercase(Locale.ROOT) } ?: emptyList()
folder.fullName.uppercase(Locale.ROOT) != "INBOX" &&
(folder.type and Folder.HOLDS_MESSAGES) != 0 &&
attributes.none { it in systemAttributes } &&
folder.fullName.lowercase(Locale.ROOT).split(Regex("[./]")).last() !in reservedFolderNames
}.sortedBy { it.fullName }.forEach { folder ->
result.put(JSONObject().put("name", folder.name).put("path", folder.fullName)
.put("id", CUSTOM_FOLDER_PREFIX + folder.fullName))
}
return result
}
fun listFolders(account: JSONObject): JSONObject =
withStore(account) { _, store -> JSONObject().put("folders", customFolders(store)) }
fun createFolder(account: JSONObject, rawName: String): JSONObject {
val name = rawName.trim()
require(name.isNotEmpty() && name.length <= 100) { "Enter a folder name of up to 100 characters." }
require(!Regex("[\\\\/.*%#&\\u0000-\\u001f]").containsMatchIn(name)) {
"Folder names cannot contain / \\ . * % # & or control characters."
}
require(name.lowercase(Locale.ROOT) !in reservedFolderNames) { "That folder name is reserved." }
return withStore(account) { _, store ->
val folder = store.getFolder(name)
check(!folder.exists()) { "A folder with that name already exists." }
check(folder.create(Folder.HOLDS_MESSAGES)) { "The mail server could not create that folder." }
try { folder.isSubscribed = true } catch (_: Exception) {}
JSONObject().put("ok", true)
.put("folder", JSONObject().put("name", name).put("path", folder.fullName)
.put("id", CUSTOM_FOLDER_PREFIX + folder.fullName))
.put("folders", customFolders(store))
}
}
private fun resolveFolder(store: Store, requested: String): Folder? { private fun resolveFolder(store: Store, requested: String): Folder? {
if (requested.startsWith(CUSTOM_FOLDER_PREFIX)) { if (requested.startsWith(CUSTOM_FOLDER_PREFIX)) {
@@ -730,16 +98,12 @@ internal object AndroidMailService {
val (specialUse, candidates) = when (requested) { val (specialUse, candidates) = when (requested) {
"Sent" -> "\\Sent" to setOf("sent", "sent items", "sent mail", "sent messages") "Sent" -> "\\Sent" to setOf("sent", "sent items", "sent mail", "sent messages")
"Archive" -> "\\Archive" to setOf("archive", "archives", "all mail") "Archive" -> "\\Archive" to setOf("archive", "archives", "all mail")
"Trash" -> "\\Trash" to setOf("trash", "deleted items", "deleted messages") "Drafts" -> "\\Drafts" to setOf("drafts")
else -> return store.getFolder(requested).takeIf { it.exists() } "Trash" -> "\\Trash" to setOf("trash", "deleted items")
} else -> return null
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
} }
return store.getFolderNames().firstOrNull { it.lowercase(Locale.ROOT) in candidates }
?.let { store.getFolder(it) }
} }
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T { private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
@@ -754,48 +118,7 @@ internal object AndroidMailService {
) )
return block(session, store) return block(session, store)
} finally { } finally {
if (store.isConnected) store.close() 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()
}
} }
@@ -497,8 +497,8 @@ class EpMailPlugin : Plugin() {
require(action != "move" || !value.any { it == '\r' || it == '\n' || it == '\u0000' }) { require(action != "move" || !value.any { it == '\r' || it == '\n' || it == '\u0000' }) {
"Mail rule ${index + 1} has an invalid destination folder." "Mail rule ${index + 1} has an invalid destination folder."
} }
require(action != "move" || value in setOf("Inbox", "Archive", "Trash")) { require(action != "move" || value in setOf("Inbox", "Archive", "Trash") || AndroidMailService.isCustomFolder(value)) {
"Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash." "Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders."
} }
result.put(JSONObject() result.put(JSONObject()
.put("id", rule.optString("id").ifBlank { UUID.randomUUID().toString() }) .put("id", rule.optString("id").ifBlank { UUID.randomUUID().toString() })
@@ -2,9 +2,10 @@ package studio.daybreak.mail;
import android.Manifest; import android.Manifest;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.getcapacitor.BridgeActivity; import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity { public class MainActivity extends BridgeActivity {
@@ -13,7 +14,15 @@ public class MainActivity extends BridgeActivity {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
registerPlugin(EpMailPlugin.class); registerPlugin(EpMailPlugin.class);
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701); ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 1);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, handle push notifications.
} }
} }
} }
@@ -0,0 +1,20 @@
package studio.daybreak.mail
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Handle FCM messages here.
// Example: Show a notification or update the UI.
}
override fun onNewToken(token: String) {
super.onNewToken(token)
// Send the new token to your server or save it locally.
}
}
+4 -9
View File
@@ -1,23 +1,18 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules. // Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript { buildscript {
ext.kotlin_version = '1.5.31'
repositories { repositories {
google() google()
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:8.13.0' classpath "com.android.tools.build:gradle:4.2.2"
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.4.4' classpath "com.google.gms:google-services:4.3.10" // Add this line
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
} }
} }
apply from: "variables.gradle"
allprojects { allprojects {
repositories { repositories {
google() google()
+22 -3
View File
@@ -294,8 +294,8 @@ function normalizeAccount(input) {
if ((action === 'move' || action === 'label') && !value) { if ((action === 'move' || action === 'label') && !value) {
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`); throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
} }
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value)) { if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value) && !value.startsWith(CUSTOM_FOLDER_PREFIX)) {
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash.`); throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders.`);
} }
return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value }; return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value };
}); });
@@ -1383,7 +1383,26 @@ ipcMain.handle('pgp:add-contact', async (event, input) => {
} }
return pgpKeys.addContact({ armoredKey, source: input?.source === 'message' ? 'message' : 'import' }); return pgpKeys.addContact({ armoredKey, source: input?.source === 'message' ? 'message' : 'import' });
}); });
ipcMain.handle('pgp:set-trust', (_event, fingerprint, trust) => pgpKeys.setTrust(pgpFingerprint(fingerprint), String(trust))); ipcMain.handle('pgp:set-trust', async (event, fingerprint, trust) => {
const id = pgpFingerprint(fingerprint);
const level = String(trust);
// Raising trust changes which key outgoing mail is encrypted to, so confirm it here, outside the renderer.
if (level !== 'unknown') {
const contact = (await pgpKeys.listContacts()).find(item => item.fingerprint === id);
if (!contact) throw new Error('That contact key was not found.');
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
type: 'question',
buttons: ['Cancel', `Mark as ${level}`],
defaultId: 0,
cancelId: 0,
title: 'Confirm key trust',
message: `Mark this key as ${level}?`,
detail: `${contact.name || ''} ${(contact.emails || []).join(', ')}\nFingerprint:\n${id.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly continue if you checked this fingerprint with the owner.`
});
if (response !== 1) throw new Error('Trust change cancelled.');
}
return pgpKeys.setTrust(id, level);
});
ipcMain.handle('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint))); ipcMain.handle('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint)));
ipcMain.handle('pgp:export-contact', async (event, fingerprint) => { ipcMain.handle('pgp:export-contact', async (event, fingerprint) => {
const id = pgpFingerprint(fingerprint); const id = pgpFingerprint(fingerprint);
+2 -2
View File
@@ -24,6 +24,7 @@
<aside class="sidebar"> <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="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> <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>
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders"> <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 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="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
@@ -32,10 +33,9 @@
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</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="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> <button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
<div id="custom-folders"></div>
</nav> </nav>
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button> <button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<div id="custom-folders" class="folder-nav"></div>
<div class="sidebar-divider"></div> <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> <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="Design"><i class="label-dot dot-amber"></i>Design</button>
+80 -7
View File
@@ -140,9 +140,38 @@ async function loadCustomFolders() {
} catch {} } catch {}
} }
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
function ruleFolderSelect(selected = 'Inbox') {
const options = [['Inbox', 'Inbox'], ['Archive', 'Archive'], ['Trash', 'Trash'], ...customFolders.map(folder => [folder.id, folder.name])];
if (!options.some(([value]) => value === selected)) {
options.push([selected, String(selected).replace(/^[^:]*:/, '') || selected]);
}
return '<select class="mail-rule-value" aria-label="Destination folder">' +
options.map(([value, name]) => '<option value="' + esc(value) + '"' + (value === selected ? ' selected' : '') + '>' + esc(name) + '</option>').join('') + '</select>';
}
// window.prompt() is not available in Electron, so ask for text in an in-app dialog.
function askText(title, label, placeholder = '') {
return new Promise(resolve => {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay pgp-prompt';
overlay.innerHTML = '<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><label class="compose-line"><span></span><input type="text" maxlength="200"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">OK</button></div></form>';
overlay.querySelector('.modal-head span').textContent = title;
overlay.querySelector('.compose-line span').textContent = label;
const input = overlay.querySelector('input');
input.placeholder = placeholder;
const finish = value => { overlay.remove(); resolve(value); };
overlay.querySelector('form').onsubmit = event => { event.preventDefault(); finish(input.value.trim() || null); };
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
document.body.append(overlay);
input.focus();
});
}
async function createMailFolder() { async function createMailFolder() {
if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; } if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
const name = prompt('New mail folder name:')?.trim(); const name = await askText('New mail folder', 'Name');
if (!name) return; if (!name) return;
try { try {
const result = await window.daybreakMail.createFolder(name); const result = await window.daybreakMail.createFolder(name);
@@ -187,7 +216,7 @@ function openMailAccount(existingAccount = null) {
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')} ${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')}
</select> </select>
${rule.action==='move' ${rule.action==='move'
? `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${rule.value==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${rule.value==='Archive'?' selected':''}>Archive</option><option value="Trash"${rule.value==='Trash'?' selected':''}>Trash</option></select>` ? `${ruleFolderSelect(rule.value)}`
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`} : `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button> <button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
</div>`).join(''); </div>`).join('');
@@ -212,8 +241,8 @@ function openMailAccount(existingAccount = null) {
const row = event.target.closest('.mail-rule-row'); const row = event.target.closest('.mail-rule-row');
const value = row.querySelector('.mail-rule-value'); const value = row.querySelector('.mail-rule-value');
if (event.target.value === 'move') { if (event.target.value === 'move') {
const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? value.value : 'Inbox'; const selected = value.value || 'Inbox';
value.outerHTML = `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${selected==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${selected==='Archive'?' selected':''}>Archive</option><option value="Trash"${selected==='Trash'?' selected':''}>Trash</option></select>`; value.outerHTML = ruleFolderSelect(selected);
} else if (value.tagName === 'SELECT') { } else if (value.tagName === 'SELECT') {
value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`; value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`;
} }
@@ -288,7 +317,37 @@ function mailSearchFilters() {
}; };
} }
const selectedDraftIds = new Set();
async function deleteSelectedDrafts() {
const ids = messages.map(message => String(message.id)).filter(id => selectedDraftIds.has(id));
if (!ids.length) { toast('Select one or more drafts first'); return; }
if (!confirm(`Delete ${ids.length} selected draft${ids.length === 1 ? '' : 's'}?`)) return;
try {
for (const id of ids) await window.daybreakMail.deleteDraft(id);
selectedDraftIds.clear();
toast(`${ids.length} draft${ids.length === 1 ? '' : 's'} deleted`);
await syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete the drafts'); }
}
// In the Drafts folder the shared toolbar acts on drafts, which use string ids.
document.addEventListener('click', event => {
if (activeFolder !== 'Drafts') return;
const button = event.target.closest('#select-all, #delete-selected, #archive-selected, #mark-unread');
if (!button) return;
event.stopImmediatePropagation();
if (button.id === 'select-all') {
const ids = messages.map(message => String(message.id));
const all = ids.length && ids.every(id => selectedDraftIds.has(id));
ids.forEach(id => all ? selectedDraftIds.delete(id) : selectedDraftIds.add(id));
renderDrafts(messages.map(message => message.draft));
} else if (button.id === 'delete-selected') void deleteSelectedDrafts();
}, true);
function renderDrafts(drafts) { function renderDrafts(drafts) {
const present = new Set(drafts.map(draft => String(draft.id)));
[...selectedDraftIds].forEach(id => { if (!present.has(id)) selectedDraftIds.delete(id); });
messages.splice(0, messages.length, ...drafts.map(draft => ({ messages.splice(0, messages.length, ...drafts.map(draft => ({
id: draft.id, id: draft.id,
sender: 'Draft', sender: 'Draft',
@@ -302,14 +361,28 @@ function renderDrafts(drafts) {
draft draft
}))); })));
$('#message-list').innerHTML = messages.length ? messages.map(message => ` $('#message-list').innerHTML = messages.length ? messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><div class="contact-avatar" style="background:${message.color}">${message.initials}</div> <div class="message" data-id="${esc(message.id)}"><input class="row-check" type="checkbox" aria-label="Select draft"${selectedDraftIds.has(String(message.id)) ? ' checked' : ''}><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div> <div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span></div></div>`).join('') : <div class="message-meta"><span class="time">${esc(message.date)}</span><button type="button" class="icon-button draft-delete" title="Delete draft" aria-label="Delete draft">⌫</button></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>'; '<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft'); const start = $('#start-draft');
if (start) start.onclick = () => showCompose(); if (start) start.onclick = () => showCompose();
$$('.message').forEach(row => row.onclick = () => { $$('.message').forEach(row => row.onclick = event => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft; const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (event.target.closest('.row-check')) {
event.stopPropagation();
const id = row.dataset.id;
selectedDraftIds.has(id) ? selectedDraftIds.delete(id) : selectedDraftIds.add(id);
return;
}
if (event.target.closest('.draft-delete')) {
event.stopPropagation();
if (!draft || !confirm('Delete this draft?')) return;
window.daybreakMail.deleteDraft(draft.id)
.then(() => { toast('Draft deleted'); return syncMailbox(false); })
.catch(error => toast(error.message || 'Could not delete the draft'));
return;
}
if (draft) showCompose(null, false, draft); if (draft) showCompose(null, false, draft);
}); });
$('#reader-pane').innerHTML = emptyReader(); $('#reader-pane').innerHTML = emptyReader();
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.3.1", "version": "0.3.6",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.3.1", "version": "0.3.6",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+3 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.3.1", "version": "0.3.6",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"author": "Eternity Project", "author": "Eternity Project",
@@ -20,7 +20,8 @@
"build:android-web": "node scripts/prepare-android-web.cjs", "build:android-web": "node scripts/prepare-android-web.cjs",
"android:sync": "npm run build:android-web && cap sync android", "android:sync": "npm run build:android-web && cap sync android",
"android:open": "npm run android:sync && cap open android", "android:open": "npm run android:sync && cap open android",
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs" "android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
}, },
"devDependencies": { "devDependencies": {
"@capacitor/cli": "^8.5.2", "@capacitor/cli": "^8.5.2",
+10 -2
View File
@@ -140,7 +140,8 @@ if (typeof showCompose === 'function') {
const encrypt = $('#pgp-encrypt'); const encrypt = $('#pgp-encrypt');
const sign = $('#pgp-sign'); const sign = $('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
encrypt.addEventListener('change', () => { touched = true; }); if (touched) encrypt.dataset.touched = '1';
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
let timer = null; let timer = null;
const refresh = async () => { const refresh = async () => {
const to = $('#compose-to')?.value || ''; const to = $('#compose-to')?.value || '';
@@ -170,8 +171,15 @@ window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
if (!pgpApi()) return null; if (!pgpApi()) return null;
let encrypt = Boolean($('#pgp-encrypt')?.checked); let encrypt = Boolean($('#pgp-encrypt')?.checked);
const sign = Boolean($('#pgp-sign')?.checked); const sign = Boolean($('#pgp-sign')?.checked);
if (!encrypt && !sign) return null; if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null;
const status = await pgpApi().checkSend({ to, cc, sign }); const status = await pgpApi().checkSend({ to, cc, sign });
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
if (!encrypt && !status.missing.length && status.recipients.length && $('#pgp-encrypt')?.dataset.touched !== '1') {
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
if (!sign) return null;
} else return false;
}
if (!encrypt && !sign) return null;
if (encrypt && status.missing.length) { if (encrypt && status.missing.length) {
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`); const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
if (!sendPlain) return false; if (!sendPlain) return false;
+19
View File
@@ -0,0 +1,19 @@
# Builds the Android APK and the Windows portable exe into .\release
$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot\..
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
if (-not $env:JAVA_HOME) { $env:JAVA_HOME = 'C:\Program Files\Android\Android Studio\jbr' }
if (-not $env:ANDROID_HOME) { $env:ANDROID_HOME = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
New-Item -ItemType Directory -Force release | Out-Null
Write-Host "== Building APK $version =="
npm run android:apk
if ($LASTEXITCODE) { throw 'APK build failed' }
Copy-Item android\app\build\outputs\apk\debug\app-debug.apk "release\ep-mail $version.apk" -Force
Write-Host "== Building portable exe $version =="
npm run dist:win:portable
if ($LASTEXITCODE) { throw 'Portable build failed' }
Write-Host "`nDone:"
Get-ChildItem release | Where-Object { $_.Name -like "ep-mail $version.*" } | ForEach-Object { " $($_.FullName)" }
+4
View File
@@ -136,3 +136,7 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px} .pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px}
.pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8} .pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8}
.pgp-trust{margin-left:8px} .pgp-trust{margin-left:8px}
.draft-delete{margin-top:4px;font-size:15px;opacity:.55}.draft-delete:hover{opacity:1;color:#b3261e}.pgp-prompt-box{width:min(380px,92vw)}
.sidebar{overflow-y:auto}#mail-nav{overflow-y:auto;min-height:150px;flex:0 1 auto;scrollbar-width:thin;align-content:start}#custom-folders{display:contents}.folders-head{flex:none}.sidebar>:not(#mail-nav){flex-shrink:0}.folders-head+.folder-nav{margin-top:0}
+2 -2
View File
@@ -24,6 +24,7 @@
<aside class="sidebar"> <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="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> <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>
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders"> <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 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="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
@@ -32,10 +33,9 @@
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</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="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> <button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
<div id="custom-folders"></div>
</nav> </nav>
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button> <button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<div id="custom-folders" class="folder-nav"></div>
<div class="sidebar-divider"></div> <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> <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="Design"><i class="label-dot dot-amber"></i>Design</button>
+80 -7
View File
@@ -140,9 +140,38 @@ async function loadCustomFolders() {
} catch {} } catch {}
} }
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
function ruleFolderSelect(selected = 'Inbox') {
const options = [['Inbox', 'Inbox'], ['Archive', 'Archive'], ['Trash', 'Trash'], ...customFolders.map(folder => [folder.id, folder.name])];
if (!options.some(([value]) => value === selected)) {
options.push([selected, String(selected).replace(/^[^:]*:/, '') || selected]);
}
return '<select class="mail-rule-value" aria-label="Destination folder">' +
options.map(([value, name]) => '<option value="' + esc(value) + '"' + (value === selected ? ' selected' : '') + '>' + esc(name) + '</option>').join('') + '</select>';
}
// window.prompt() is not available in Electron, so ask for text in an in-app dialog.
function askText(title, label, placeholder = '') {
return new Promise(resolve => {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay pgp-prompt';
overlay.innerHTML = '<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><label class="compose-line"><span></span><input type="text" maxlength="200"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">OK</button></div></form>';
overlay.querySelector('.modal-head span').textContent = title;
overlay.querySelector('.compose-line span').textContent = label;
const input = overlay.querySelector('input');
input.placeholder = placeholder;
const finish = value => { overlay.remove(); resolve(value); };
overlay.querySelector('form').onsubmit = event => { event.preventDefault(); finish(input.value.trim() || null); };
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
document.body.append(overlay);
input.focus();
});
}
async function createMailFolder() { async function createMailFolder() {
if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; } if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
const name = prompt('New mail folder name:')?.trim(); const name = await askText('New mail folder', 'Name');
if (!name) return; if (!name) return;
try { try {
const result = await window.daybreakMail.createFolder(name); const result = await window.daybreakMail.createFolder(name);
@@ -187,7 +216,7 @@ function openMailAccount(existingAccount = null) {
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')} ${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')}
</select> </select>
${rule.action==='move' ${rule.action==='move'
? `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${rule.value==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${rule.value==='Archive'?' selected':''}>Archive</option><option value="Trash"${rule.value==='Trash'?' selected':''}>Trash</option></select>` ? `${ruleFolderSelect(rule.value)}`
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`} : `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button> <button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
</div>`).join(''); </div>`).join('');
@@ -212,8 +241,8 @@ function openMailAccount(existingAccount = null) {
const row = event.target.closest('.mail-rule-row'); const row = event.target.closest('.mail-rule-row');
const value = row.querySelector('.mail-rule-value'); const value = row.querySelector('.mail-rule-value');
if (event.target.value === 'move') { if (event.target.value === 'move') {
const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? value.value : 'Inbox'; const selected = value.value || 'Inbox';
value.outerHTML = `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${selected==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${selected==='Archive'?' selected':''}>Archive</option><option value="Trash"${selected==='Trash'?' selected':''}>Trash</option></select>`; value.outerHTML = ruleFolderSelect(selected);
} else if (value.tagName === 'SELECT') { } else if (value.tagName === 'SELECT') {
value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`; value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`;
} }
@@ -288,7 +317,37 @@ function mailSearchFilters() {
}; };
} }
const selectedDraftIds = new Set();
async function deleteSelectedDrafts() {
const ids = messages.map(message => String(message.id)).filter(id => selectedDraftIds.has(id));
if (!ids.length) { toast('Select one or more drafts first'); return; }
if (!confirm(`Delete ${ids.length} selected draft${ids.length === 1 ? '' : 's'}?`)) return;
try {
for (const id of ids) await window.daybreakMail.deleteDraft(id);
selectedDraftIds.clear();
toast(`${ids.length} draft${ids.length === 1 ? '' : 's'} deleted`);
await syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete the drafts'); }
}
// In the Drafts folder the shared toolbar acts on drafts, which use string ids.
document.addEventListener('click', event => {
if (activeFolder !== 'Drafts') return;
const button = event.target.closest('#select-all, #delete-selected, #archive-selected, #mark-unread');
if (!button) return;
event.stopImmediatePropagation();
if (button.id === 'select-all') {
const ids = messages.map(message => String(message.id));
const all = ids.length && ids.every(id => selectedDraftIds.has(id));
ids.forEach(id => all ? selectedDraftIds.delete(id) : selectedDraftIds.add(id));
renderDrafts(messages.map(message => message.draft));
} else if (button.id === 'delete-selected') void deleteSelectedDrafts();
}, true);
function renderDrafts(drafts) { function renderDrafts(drafts) {
const present = new Set(drafts.map(draft => String(draft.id)));
[...selectedDraftIds].forEach(id => { if (!present.has(id)) selectedDraftIds.delete(id); });
messages.splice(0, messages.length, ...drafts.map(draft => ({ messages.splice(0, messages.length, ...drafts.map(draft => ({
id: draft.id, id: draft.id,
sender: 'Draft', sender: 'Draft',
@@ -302,14 +361,28 @@ function renderDrafts(drafts) {
draft draft
}))); })));
$('#message-list').innerHTML = messages.length ? messages.map(message => ` $('#message-list').innerHTML = messages.length ? messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><div class="contact-avatar" style="background:${message.color}">${message.initials}</div> <div class="message" data-id="${esc(message.id)}"><input class="row-check" type="checkbox" aria-label="Select draft"${selectedDraftIds.has(String(message.id)) ? ' checked' : ''}><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div> <div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span></div></div>`).join('') : <div class="message-meta"><span class="time">${esc(message.date)}</span><button type="button" class="icon-button draft-delete" title="Delete draft" aria-label="Delete draft">⌫</button></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>'; '<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft'); const start = $('#start-draft');
if (start) start.onclick = () => showCompose(); if (start) start.onclick = () => showCompose();
$$('.message').forEach(row => row.onclick = () => { $$('.message').forEach(row => row.onclick = event => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft; const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (event.target.closest('.row-check')) {
event.stopPropagation();
const id = row.dataset.id;
selectedDraftIds.has(id) ? selectedDraftIds.delete(id) : selectedDraftIds.add(id);
return;
}
if (event.target.closest('.draft-delete')) {
event.stopPropagation();
if (!draft || !confirm('Delete this draft?')) return;
window.daybreakMail.deleteDraft(draft.id)
.then(() => { toast('Draft deleted'); return syncMailbox(false); })
.catch(error => toast(error.message || 'Could not delete the draft'));
return;
}
if (draft) showCompose(null, false, draft); if (draft) showCompose(null, false, draft);
}); });
$('#reader-pane').innerHTML = emptyReader(); $('#reader-pane').innerHTML = emptyReader();
+10 -2
View File
@@ -140,7 +140,8 @@ if (typeof showCompose === 'function') {
const encrypt = $('#pgp-encrypt'); const encrypt = $('#pgp-encrypt');
const sign = $('#pgp-sign'); const sign = $('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
encrypt.addEventListener('change', () => { touched = true; }); if (touched) encrypt.dataset.touched = '1';
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
let timer = null; let timer = null;
const refresh = async () => { const refresh = async () => {
const to = $('#compose-to')?.value || ''; const to = $('#compose-to')?.value || '';
@@ -170,8 +171,15 @@ window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
if (!pgpApi()) return null; if (!pgpApi()) return null;
let encrypt = Boolean($('#pgp-encrypt')?.checked); let encrypt = Boolean($('#pgp-encrypt')?.checked);
const sign = Boolean($('#pgp-sign')?.checked); const sign = Boolean($('#pgp-sign')?.checked);
if (!encrypt && !sign) return null; if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null;
const status = await pgpApi().checkSend({ to, cc, sign }); const status = await pgpApi().checkSend({ to, cc, sign });
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
if (!encrypt && !status.missing.length && status.recipients.length && $('#pgp-encrypt')?.dataset.touched !== '1') {
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
if (!sign) return null;
} else return false;
}
if (!encrypt && !sign) return null;
if (encrypt && status.missing.length) { if (encrypt && status.missing.length) {
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`); const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
if (!sendPlain) return false; if (!sendPlain) return false;
+4
View File
@@ -136,3 +136,7 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px} .pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px}
.pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8} .pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8}
.pgp-trust{margin-left:8px} .pgp-trust{margin-left:8px}
.draft-delete{margin-top:4px;font-size:15px;opacity:.55}.draft-delete:hover{opacity:1;color:#b3261e}.pgp-prompt-box{width:min(380px,92vw)}
.sidebar{overflow-y:auto}#mail-nav{overflow-y:auto;min-height:150px;flex:0 1 auto;scrollbar-width:thin;align-content:start}#custom-folders{display:contents}.folders-head{flex:none}.sidebar>:not(#mail-nav){flex-shrink:0}.folders-head+.folder-nav{margin-top:0}