Compare commits

..
7 Commits
Author SHA1 Message Date
thuttuandCopilot d0e2ce26bc Enable OpenPGP key servers on Android, add keys.eternityproject.fi, allow removing built-in servers
- Android: key-server lookup, publish, add/remove/enable via native HTTP
- Built-in servers can be removed; keys.eternityproject.fi (VKS) added as a default
- Fix Settings additions (Encryption keys, shortcuts) missing on Android due to async preferences
- Fix compose footer so Send is visible on small screens
- Bump version to 0.5.22

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-17 20:53:54 +02:00
thuttu 4ec578b072 FIX send message button in compose message window 2026-11-17 20:22:14 +02:00
thuttuandCopilot 8a798fec6b Upgrade Android build tooling for 0.5.20
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-09 22:17:55 +02:00
thuttuandCopilot 5b8aafe22c Improve Android mailbox navigation and pagination
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-09 22:07:20 +02:00
thuttu 89c45fcf63 FIX feature to scroll down in imap folder to load more mails 2026-11-09 21:11:00 +02:00
thuttu d7b6e31518 Add feature to scroll down in imap folder to load more mails, and speedup of imap folder change 2026-11-09 20:42:31 +02:00
thuttu b14209a5ae IMAP Folder speedup tuning 2026-11-09 20:11:31 +02:00
43 changed files with 12723 additions and 10332 deletions
+3
View File
@@ -0,0 +1,3 @@
{
"java.configuration.updateBuildConfiguration": "interactive"
}
+9 -1
View File
@@ -27,7 +27,15 @@ npm run android:apk
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management. The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
On Android, previously cached inbox messages appear while the mailbox refreshes. The app stays in the message list until you select a message; returning to the list does not automatically reopen the newest message. Android builds use the Gradle wrapper and Android Gradle Plugin 9.4.0. Capacitor's generated modules are aligned to that plugin version during the build; the legacy Android DSL and external Kotlin plugin remain enabled for compatibility and must be migrated before upgrading to AGP 10.
On Android, previously cached folder messages appear while the mailbox refreshes; a folder without cached messages still needs to load from the server. Folder discovery and message actions run separately from cached-folder loading. The app stays in the message list until you select a message; returning to the list does not automatically reopen the newest message.
While reading a message on Android, swipe in from the screen edge using the system Back gesture, or use the Back button in the reader, to return to the same position in the message list.
In connected IMAP folders, scrolling to the end of the message list loads the next page automatically. The **Load more** button remains available as a manual fallback. On Android, background refreshes wait while you browse down the list so they do not replace older messages; return to the top or press Refresh to apply pending updates.
After upgrading from an older Android build, close and reopen ep-mail once if it still shows the previous interface. This lets the updated offline app shell take control without clearing account data.
## Run on Windows or Linux ## Run on Windows or Linux
+1 -1
View File
@@ -56,7 +56,7 @@ android {
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'
if (hasCompleteReleaseSigning) signingConfig signingConfigs.release if (hasCompleteReleaseSigning) signingConfig signingConfigs.release
} }
} }
@@ -339,7 +339,7 @@ internal object AndroidAccountVault {
} }
@Synchronized @Synchronized
fun cacheMessages(id: String, folder: String, messages: JSONArray) { fun cacheMessages(id: String, folder: String, messages: JSONArray, replace: Boolean = false) {
val store = read() val store = read()
val accounts = store.optJSONArray("accounts") ?: return val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) { for (index in 0 until accounts.length()) {
@@ -348,16 +348,18 @@ internal object AndroidAccountVault {
val cache = account.optJSONObject("mailCache") ?: JSONObject() val cache = account.optJSONObject("mailCache") ?: JSONObject()
val previous = cache.optJSONArray(folder) ?: JSONArray() val previous = cache.optJSONArray(folder) ?: JSONArray()
val merged = LinkedHashMap<String, JSONObject>() val merged = LinkedHashMap<String, JSONObject>()
if (!replace) {
for (itemIndex in 0 until previous.length()) { for (itemIndex in 0 until previous.length()) {
val item = previous.optJSONObject(itemIndex) ?: continue val item = previous.optJSONObject(itemIndex) ?: continue
merged[item.optString("uid", item.optString("id"))] = item merged[item.optString("uid", item.optString("id"))] = item
} }
}
for (itemIndex in 0 until messages.length()) { for (itemIndex in 0 until messages.length()) {
val item = messages.optJSONObject(itemIndex) ?: continue val item = messages.optJSONObject(itemIndex) ?: continue
merged[item.optString("uid", item.optString("id"))] = item merged[item.optString("uid", item.optString("id"))] = item
} }
cache.put(folder, JSONArray().apply { cache.put(folder, JSONArray().apply {
merged.values.toList().takeLast(30).forEach { put(it) } merged.values.sortedByDescending { it.optLong("timestamp") }.take(30).forEach { put(it) }
}) })
account.put("mailCache", cache) account.put("mailCache", cache)
write(store) write(store)
@@ -182,7 +182,7 @@ internal object AndroidMailService {
result.put(value) result.put(value)
cached.put(value) cached.put(value)
} }
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached) AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached, replace = offset <= 0)
JSONObject().put("messages", result).put("total", total) JSONObject().put("messages", result).put("total", total)
.put("start", first).put("end", end).put("folder", requestedFolder) .put("start", first).put("end", end).put("folder", requestedFolder)
} finally { } finally {
@@ -464,6 +464,7 @@ internal object AndroidMailService {
return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT)) return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT))
} }
@Synchronized
fun flushOutbox(account: JSONObject) { fun flushOutbox(account: JSONObject) {
val accountId = account.optString("id") val accountId = account.optString("id")
val queued = AndroidAccountVault.pendingMailOperations(accountId) val queued = AndroidAccountVault.pendingMailOperations(accountId)
@@ -15,6 +15,7 @@ import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin import com.getcapacitor.annotation.CapacitorPlugin
import java.util.Locale import java.util.Locale
import java.util.UUID import java.util.UUID
import java.util.concurrent.Executors
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import javax.mail.internet.InternetAddress import javax.mail.internet.InternetAddress
@@ -24,6 +25,10 @@ import javax.crypto.Cipher
class EpMailPlugin : Plugin() { class EpMailPlugin : Plugin() {
private var syncReceiver: BroadcastReceiver? = null private var syncReceiver: BroadcastReceiver? = null
private var wipeDialogShowing = false private var wipeDialogShowing = false
private val mailboxExecutor = Executors.newFixedThreadPool(3)
private val folderListExecutor = Executors.newFixedThreadPool(2)
private val mailActionExecutor = Executors.newSingleThreadExecutor()
private val outboxExecutor = Executors.newSingleThreadExecutor()
override fun load() { override fun load() {
AndroidAccountVault.initialize(context) AndroidAccountVault.initialize(context)
@@ -58,6 +63,10 @@ class EpMailPlugin : Plugin() {
} }
override fun handleOnDestroy() { override fun handleOnDestroy() {
mailboxExecutor.shutdown()
folderListExecutor.shutdown()
mailActionExecutor.shutdown()
outboxExecutor.shutdown()
syncReceiver?.let { syncReceiver?.let {
try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {} try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {}
} }
@@ -479,9 +488,15 @@ class EpMailPlugin : Plugin() {
try { try {
val account = AndroidAccountVault.account() val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before listing folders.") ?: throw IllegalStateException("Add a mail account before listing folders.")
folderListExecutor.execute {
try {
call.resolve(AndroidMailService.listFolders(account).toJSObject()) call.resolve(AndroidMailService.listFolders(account).toJSObject())
} catch (error: Exception) { } catch (error: Exception) {
call.resolve(JSObject().put("folders", org.json.JSONArray()).put("offline", true)) call.reject(error.message ?: "Could not list mail folders.")
}
}
} catch (error: Exception) {
call.reject(error.message ?: "Could not list mail folders.")
} }
} }
@@ -522,10 +537,31 @@ class EpMailPlugin : Plugin() {
val selected = filterFolder?.takeIf { it in setOf("Inbox", "Sent", "Archive", "Trash", "Starred") } ?: requested val selected = filterFolder?.takeIf { it in setOf("Inbox", "Sent", "Archive", "Trash", "Starred") } ?: requested
val folder = if (selected in setOf("Inbox", "Sent", "Archive", "Trash", "Starred", "Snoozed") || AndroidMailService.isCustomFolder(selected)) selected else "Inbox" val folder = if (selected in setOf("Inbox", "Sent", "Archive", "Trash", "Starred", "Snoozed") || AndroidMailService.isCustomFolder(selected)) selected else "Inbox"
val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0) val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0)
AndroidMailService.flushOutbox(account) mailboxExecutor.execute {
try {
call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject()) call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject())
} catch (error: Exception) { } catch (error: Exception) {
call.reject(error.message ?: "Could not sync the mailbox.") call.reject(error.message ?: "Could not sync the mailbox.")
return@execute
}
retryOutbox(account)
}
} catch (error: Exception) {
call.reject(error.message ?: "Could not sync the mailbox.")
}
}
private fun retryOutbox(account: JSONObject) {
try {
outboxExecutor.execute {
try {
AndroidMailService.flushOutbox(account)
} catch (error: Exception) {
android.util.Log.e("EpMailOutbox", "Could not retry queued mail operations", error)
}
}
} catch (error: java.util.concurrent.RejectedExecutionException) {
android.util.Log.w("EpMailOutbox", "Could not schedule queued mail retry", error)
} }
} }
@@ -534,18 +570,28 @@ class EpMailPlugin : Plugin() {
try { try {
val account = AndroidAccountVault.account() val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before changing messages.") ?: throw IllegalStateException("Add a mail account before changing messages.")
call.resolve(AndroidMailService.updateMessage(account, call.data).toJSObject()) val input = JSONObject(call.data.toString())
mailActionExecutor.execute {
try {
call.resolve(AndroidMailService.updateMessage(account, input).toJSObject())
} catch (error: Exception) { } catch (error: Exception) {
val account = AndroidAccountVault.account() if (isConnectivityFailure(error)) {
if (account != null && isConnectivityFailure(error)) { try {
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject() AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
.put("id", UUID.randomUUID().toString()) .put("id", UUID.randomUUID().toString())
.put("type", "action") .put("type", "action")
.put("data", JSONObject(call.data.toString()))) .put("data", input))
call.resolve(JSObject().put("ok", true).put("queued", true)) call.resolve(JSObject().put("ok", true).put("queued", true))
} catch (queueError: Exception) {
call.reject(queueError.message ?: "Could not queue the message action.")
}
} else call.reject(error.message ?: "Could not update the message.") } else call.reject(error.message ?: "Could not update the message.")
} }
} }
} catch (error: Exception) {
call.reject(error.message ?: "Could not update the message.")
}
}
@PluginMethod @PluginMethod
fun setSnooze(call: PluginCall) { fun setSnooze(call: PluginCall) {
@@ -26,6 +26,7 @@ import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.biometric.BiometricManager; import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt; import androidx.biometric.BiometricPrompt;
import androidx.activity.OnBackPressedCallback;
import com.getcapacitor.BridgeActivity; import com.getcapacitor.BridgeActivity;
import javax.crypto.Cipher; import javax.crypto.Cipher;
@@ -54,6 +55,33 @@ public class MainActivity extends BridgeActivity {
registerPlugin(EpMailPlugin.class); registerPlugin(EpMailPlugin.class);
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
hardenWebView(); hardenWebView();
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
if (appLocked || vaultRecoveryRequired || getBridge() == null || getBridge().getWebView() == null) {
dispatchDefaultBack();
return;
}
getBridge().getWebView().evaluateJavascript(
"(function(){if(document.body.classList.contains('reader-open') && " +
"!document.querySelector('#modal-root .modal-overlay')){" +
"const back=document.querySelector('#reader-back');if(back){back.click();return true;}}" +
"return false;})()",
result -> {
if (!"true".equals(result)) dispatchDefaultBack();
}
);
}
private void dispatchDefaultBack() {
setEnabled(false);
try {
getOnBackPressedDispatcher().onBackPressed();
} finally {
setEnabled(true);
}
}
});
AndroidAccountVault.INSTANCE.initialize(getApplicationContext()); AndroidAccountVault.INSTANCE.initialize(getApplicationContext());
try { try {
AndroidAccountVault.INSTANCE.read(); AndroidAccountVault.INSTANCE.read();
@@ -0,0 +1,3 @@
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/ep_splash_icon"
android:inset="22dp" />
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/> <background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/> <foreground android:drawable="@drawable/ep_launcher_foreground"/>
</adaptive-icon> </adaptive-icon>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/> <background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/> <foreground android:drawable="@drawable/ep_launcher_foreground"/>
</adaptive-icon> </adaptive-icon>
@@ -0,0 +1,9 @@
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/ic_launcher_background" />
<item
android:drawable="@drawable/ep_splash_icon"
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</layer-list>
@@ -0,0 +1,13 @@
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@color/ic_launcher_background" />
</shape>
</item>
<item
android:drawable="@drawable/ep_splash_icon"
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</layer-list>
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<color name="ic_launcher_background">#FFFFFF</color> <color name="ic_launcher_background">#0a0c0b</color>
</resources> </resources>
+7 -1
View File
@@ -7,7 +7,7 @@ buildscript {
mavenCentral() mavenCentral()
} }
dependencies { dependencies {
classpath 'com.android.tools.build:gradle:8.13.0' classpath 'com.android.tools.build:gradle:9.4.0'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21' classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
classpath 'com.google.gms:google-services:4.4.4' classpath 'com.google.gms:google-services:4.4.4'
@@ -19,6 +19,12 @@ buildscript {
apply from: "variables.gradle" apply from: "variables.gradle"
allprojects { allprojects {
// Capacitor-generated modules declare their own AGP version.
buildscript {
configurations.classpath {
resolutionStrategy.force 'com.android.tools.build:gradle:9.4.0'
}
}
repositories { repositories {
google() google()
mavenCentral() mavenCentral()
+3
View File
@@ -20,3 +20,6 @@ org.gradle.jvmargs=-Xmx1536m
# Android operating system, and which are packaged with your app's APK # Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn # https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true android.useAndroidX=true
# Capacitor's generated modules and the current Kotlin plugin still use the legacy AGP APIs.
android.builtInKotlin=false
android.newDsl=false
+2 -1
View File
@@ -1,6 +1,7 @@
#Mon Nov 09 22:05:03 EET 2026
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
+19 -1
View File
@@ -4,11 +4,26 @@ const state = window.epMailState;
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))} function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity; const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
let readerListPosition = null;
function rememberReaderListPosition() {
if (window.daybreakMail?.platform !== 'android' || document.body.classList.contains('reader-open')) return;
const list = $('#message-list');
readerListPosition = { folder: state.activeFolder, scrollTop: list.scrollTop };
}
function returnToMessageList() {
state.activeMessage = null;
document.body.classList.remove('reader-open');
$('#reader-pane').innerHTML = emptyReader();
renderList();
if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop;
readerListPosition = null;
}
function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}} function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}}
function openMessage(id){ function openMessage(id){
state.activeMessage=id; state.activeMessage=id;
const m=state.messages.find(x=>x.id===id); const m=state.messages.find(x=>x.id===id);
if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;} if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
rememberReaderListPosition();
document.body.classList.add('reader-open'); document.body.classList.add('reader-open');
m.unread=false; m.unread=false;
renderList(); renderList();
@@ -18,7 +33,7 @@ function openMessage(id){
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:''; const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join(''); const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><button class="reader-back" id="reader-back" type="button" aria-label="Back to messages">Back</button><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`; $('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><button class="reader-back" id="reader-back" type="button" aria-label="Back to messages">Back</button><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;
$('#reader-back').onclick=()=>{state.activeMessage=null;document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader();renderList()}; $('#reader-back').onclick=returnToMessageList;
$('#load-remote-images')?.addEventListener('click',()=>{ $('#load-remote-images')?.addEventListener('click',()=>{
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{ $('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src')); const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
@@ -51,6 +66,9 @@ window.epMailShell = Object.freeze({
get renderList() { return renderList; }, get renderList() { return renderList; },
get openMessage() { return openMessage; }, get openMessage() { return openMessage; },
get showCompose() { return showCompose; }, get showCompose() { return showCompose; },
getReaderListPosition() {
return readerListPosition?.folder === state.activeFolder ? readerListPosition.scrollTop : 0;
},
emptyReader, emptyReader,
wrapRenderList(decorator) { renderList = decorator(renderList); }, wrapRenderList(decorator) { renderList = decorator(renderList); },
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); }, wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
+12 -7
View File
@@ -1,3 +1,5 @@
const { BUILTIN_SERVER_IDS } = require('../pgp-keyservers.cjs');
function pgpFailure(error) { function pgpFailure(error) {
return { return {
failed: true, failed: true,
@@ -207,12 +209,12 @@ function registerPgpIpcHandlers({
}); });
registerIpcHandler('pgp:key-servers', async () => { registerIpcHandler('pgp:key-servers', async () => {
const settings = await pgpKeys.getSettings(); const settings = await pgpKeys.getSettings();
return listServers(settings.customKeyServers, settings.enabledKeyServers); return listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
}); });
registerIpcHandler('pgp:set-key-server-enabled', async (_event, input) => { registerIpcHandler('pgp:set-key-server-enabled', async (_event, input) => {
if (typeof input?.enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.'); if (typeof input?.enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.');
const settings = await pgpKeys.getSettings(); const settings = await pgpKeys.getSettings();
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers); const servers = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
const serverId = String(input?.serverId || ''); const serverId = String(input?.serverId || '');
if (!servers.some(server => server.id === serverId)) throw new Error('That key server was not found.'); if (!servers.some(server => server.id === serverId)) throw new Error('That key server was not found.');
const enabled = new Set(settings.enabledKeyServers); const enabled = new Set(settings.enabledKeyServers);
@@ -221,7 +223,8 @@ function registerPgpIpcHandlers({
await pgpKeys.setSettings({ await pgpKeys.setSettings({
cacheMinutes: settings.cacheMinutes, cacheMinutes: settings.cacheMinutes,
customKeyServers: settings.customKeyServers, customKeyServers: settings.customKeyServers,
enabledKeyServers: [...enabled] enabledKeyServers: [...enabled],
removedBuiltinKeyServers: settings.removedBuiltinKeyServers
}); });
return { serverId, enabled: input.enabled }; return { serverId, enabled: input.enabled };
}); });
@@ -256,23 +259,25 @@ function registerPgpIpcHandlers({
const id = String(serverId || ''); const id = String(serverId || '');
const settings = await pgpKeys.getSettings(); const settings = await pgpKeys.getSettings();
const customServers = settings.customKeyServers.filter(server => server.id !== id); const customServers = settings.customKeyServers.filter(server => server.id !== id);
if (customServers.length === settings.customKeyServers.length) throw new Error('That custom key server was not found.'); const removesBuiltin = BUILTIN_SERVER_IDS.includes(id) && !settings.removedBuiltinKeyServers.includes(id);
if (customServers.length === settings.customKeyServers.length && !removesBuiltin) throw new Error('That key server was not found.');
await pgpKeys.setSettings({ await pgpKeys.setSettings({
cacheMinutes: settings.cacheMinutes, cacheMinutes: settings.cacheMinutes,
customKeyServers, customKeyServers: customServers,
removedBuiltinKeyServers: removesBuiltin ? [...settings.removedBuiltinKeyServers, id] : settings.removedBuiltinKeyServers,
enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id) enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id)
}); });
return { removed: true }; return { removed: true };
}); });
registerIpcHandler('pgp:find-key', async (_event, input) => { registerIpcHandler('pgp:find-key', async (_event, input) => {
const settings = await pgpKeys.getSettings(); const settings = await pgpKeys.getSettings();
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers); const servers = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
return pgpKeyServers.lookupEnabled(servers, input?.email); return pgpKeyServers.lookupEnabled(servers, input?.email);
}); });
registerIpcHandler('pgp:publish-key', async (event, input) => { registerIpcHandler('pgp:publish-key', async (event, input) => {
const fingerprint = pgpFingerprint(input?.fingerprint); const fingerprint = pgpFingerprint(input?.fingerprint);
const settings = await pgpKeys.getSettings(); const settings = await pgpKeys.getSettings();
const server = listServers(settings.customKeyServers, settings.enabledKeyServers).find(item => item.id === String(input?.serverId || '')); const server = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers).find(item => item.id === String(input?.serverId || ''));
if (!server) throw new Error('Choose a configured key server.'); if (!server) throw new Error('Choose a configured key server.');
if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.'); if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.');
const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint); const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint);
+12 -5
View File
@@ -7,8 +7,10 @@ const MAX_CUSTOM_SERVERS = 10;
const BUILTIN_SERVERS = [ const BUILTIN_SERVERS = [
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true }, { id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true } { id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true },
{ id: 'eternity-vks', name: 'keys.eternityproject.fi', url: 'https://keys.eternityproject.fi', protocol: 'vks', builtin: true }
]; ];
const BUILTIN_SERVER_IDS = BUILTIN_SERVERS.map(server => server.id);
function normalizeBaseUrl(value) { function normalizeBaseUrl(value) {
const raw = String(value || '').trim(); const raw = String(value || '').trim();
@@ -40,10 +42,11 @@ function normalizeCustomServer(input) {
}; };
} }
function listServers(customServers = [], enabledServerIds = []) { function listServers(customServers = [], enabledServerIds = [], removedBuiltinIds = []) {
const enabled = new Set(enabledServerIds); const enabled = new Set(enabledServerIds);
const removed = new Set(removedBuiltinIds);
return [ return [
...BUILTIN_SERVERS.map(server => ({ ...server, enabled: enabled.has(server.id) })), ...BUILTIN_SERVERS.filter(server => !removed.has(server.id)).map(server => ({ ...server, enabled: enabled.has(server.id) })),
...customServers.map(server => { ...customServers.map(server => {
const normalized = normalizeCustomServer(server); const normalized = normalizeCustomServer(server);
return { ...normalized, enabled: enabled.has(normalized.id) }; return { ...normalized, enabled: enabled.has(normalized.id) };
@@ -72,14 +75,17 @@ async function readResponseText(response) {
const chunks = []; const chunks = [];
let length = 0; let length = 0;
for await (const chunk of response.body) { for await (const chunk of response.body) {
const bytes = Buffer.from(chunk); const bytes = typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk;
length += bytes.length; length += bytes.length;
if (length > MAX_RESPONSE_BYTES) { if (length > MAX_RESPONSE_BYTES) {
throw new Error('The key server response is too large.'); throw new Error('The key server response is too large.');
} }
chunks.push(bytes); chunks.push(bytes);
} }
return Buffer.concat(chunks, length).toString('utf8'); const joined = new Uint8Array(length);
let offset = 0;
for (const bytes of chunks) { joined.set(bytes, offset); offset += bytes.length; }
return new TextDecoder().decode(joined);
} }
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) { function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
@@ -269,6 +275,7 @@ function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
module.exports = { module.exports = {
BUILTIN_SERVERS, BUILTIN_SERVERS,
BUILTIN_SERVER_IDS,
MAX_CUSTOM_SERVERS, MAX_CUSTOM_SERVERS,
createKeyServerService, createKeyServerService,
listServers, listServers,
+12 -2
View File
@@ -198,11 +198,14 @@ function createKeyStore(storage) {
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [], customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
enabledKeyServers: Array.isArray(settings.enabledKeyServers) enabledKeyServers: Array.isArray(settings.enabledKeyServers)
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))] ? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
: [],
removedBuiltinKeyServers: Array.isArray(settings.removedBuiltinKeyServers)
? [...new Set(settings.removedBuiltinKeyServers.filter(id => typeof id === 'string'))]
: [] : []
}; };
}, },
async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers }) { async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers, removedBuiltinKeyServers }) {
const minutes = Number(cacheMinutes); const minutes = Number(cacheMinutes);
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.'); if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
const data = await read(); const data = await read();
@@ -224,11 +227,18 @@ function createKeyStore(storage) {
} }
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)]; data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
} }
if (removedBuiltinKeyServers !== undefined) {
if (!Array.isArray(removedBuiltinKeyServers) || removedBuiltinKeyServers.length > 12 || removedBuiltinKeyServers.some(id => typeof id !== 'string' || !id.trim())) {
throw new Error('Choose no more than 12 valid built-in key servers to remove.');
}
data.settings.removedBuiltinKeyServers = [...new Set(removedBuiltinKeyServers)];
}
await storage.save(data); await storage.save(data);
return { return {
cacheMinutes: data.settings.cacheMinutes, cacheMinutes: data.settings.cacheMinutes,
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [], customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : [] enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : [],
removedBuiltinKeyServers: Array.isArray(data.settings.removedBuiltinKeyServers) ? [...data.settings.removedBuiltinKeyServers] : []
}; };
}, },
+179 -15
View File
@@ -8,12 +8,20 @@ const toastMailUi = appShell.toast;
const mailFeatureState = { const mailFeatureState = {
connectedAccount: null, connectedAccount: null,
pageOffset: 0, pageOffset: 0,
nextOffset: 0,
total: 0, total: 0,
autoLoadBlocked: false,
syncPromise: null, syncPromise: null,
syncQueued: false, syncQueued: false,
syncMailboxKey: null,
displayedMailboxKey: null,
refreshPending: false, refreshPending: false,
browseRefreshPending: false,
browseRefreshFromStart: false,
folderBeforeSearch: null, folderBeforeSearch: null,
customFolders: [], customFolders: [],
folderLoad: null,
foldersAccountId: null,
selectedDraftIds: new Set() selectedDraftIds: new Set()
}; };
@@ -142,10 +150,23 @@ function renderCustomFolders() {
async function loadCustomFolders() { async function loadCustomFolders() {
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return; if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
const accountId = mailFeatureState.connectedAccount.id;
if (mailFeatureState.folderLoad?.accountId === accountId) return mailFeatureState.folderLoad.promise;
const request = { accountId };
mailFeatureState.folderLoad = request;
request.promise = (async () => {
try { try {
mailFeatureState.customFolders = (await window.daybreakMail.listFolders()).folders || []; const result = await window.daybreakMail.listFolders();
if (mailFeatureState.folderLoad !== request || mailFeatureState.connectedAccount?.id !== accountId) return;
mailFeatureState.customFolders = result.folders || [];
renderCustomFolders(); renderCustomFolders();
} catch {} } catch (error) {
if (mailFeatureState.folderLoad === request) console.error('Could not load mail folders:', error);
} finally {
if (mailFeatureState.folderLoad === request) mailFeatureState.folderLoad = null;
}
})();
return request.promise;
} }
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders. // Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
@@ -183,6 +204,7 @@ async function createMailFolder() {
if (!name) return; if (!name) return;
try { try {
const result = await window.daybreakMail.createFolder(name); const result = await window.daybreakMail.createFolder(name);
mailFeatureState.folderLoad = null;
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders; mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
renderCustomFolders(); renderCustomFolders();
toastMailUi(`Folder “${result.folder?.name || name}” created`); toastMailUi(`Folder “${result.folder?.name || name}” created`);
@@ -192,6 +214,13 @@ async function createMailFolder() {
} }
function updateAccountCard(account) { function updateAccountCard(account) {
const accountId = mailFeatureState.connectedAccount?.id || null;
if (mailFeatureState.foldersAccountId !== accountId) {
mailFeatureState.foldersAccountId = accountId;
mailFeatureState.folderLoad = null;
mailFeatureState.customFolders = [];
renderCustomFolders();
}
const card = selectMailUi('#account-settings'); const card = selectMailUi('#account-settings');
if (!card) return; if (!card) return;
const email = account.email || ''; const email = account.email || '';
@@ -648,42 +677,86 @@ function setupDraftComposer() {
} }
async function syncMailbox(showToast, options = {}) { async function syncMailbox(showToast, options = {}) {
const isAndroid = window.daybreakMail?.platform === 'android';
const mailboxKey = JSON.stringify([mailFeatureState.connectedAccount?.id, rendererState.activeFolder]);
if (mailFeatureState.syncPromise) { if (mailFeatureState.syncPromise) {
if (!isAndroid || mailFeatureState.syncMailboxKey === mailboxKey) {
mailFeatureState.syncQueued = true; mailFeatureState.syncQueued = true;
return mailFeatureState.syncPromise; return mailFeatureState.syncPromise;
} }
mailFeatureState.syncQueued = false;
}
if (!mailFeatureState.connectedAccount || !window.daybreakMail) { if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
openMailAccount(); openMailAccount();
return; return;
} }
const refresh = selectMailUi('#refresh'); const refresh = selectMailUi('#refresh');
if (refresh) refresh.disabled = true; if (refresh) refresh.disabled = true;
const loadMoreButton = selectMailUi('#load-more');
if (loadMoreButton) loadMoreButton.disabled = true;
if (!options.append) {
mailFeatureState.browseRefreshPending = false;
mailFeatureState.browseRefreshFromStart = false;
} else {
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Loading more messages…';
}
const request = {};
mailFeatureState.syncRequest = request;
mailFeatureState.syncMailboxKey = mailboxKey;
let syncSucceeded = false;
const sync = (async () => { const sync = (async () => {
let showingCachedMessages = false; let showingCachedMessages = false;
try { try {
if (isAndroid && mailFeatureState.displayedMailboxKey !== mailboxKey) {
mailFeatureState.displayedMailboxKey = mailboxKey;
mailFeatureState.nextOffset = 0;
mailFeatureState.total = 0;
mailFeatureState.autoLoadBlocked = false;
rendererState.messages.splice(0, rendererState.messages.length);
rendererState.activeMessage = null;
rendererState.selectedIds.clear();
document.body.classList.remove('reader-open');
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
appShell.renderList();
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Loading folder…';
}
if (rendererState.activeFolder === 'Drafts') { if (rendererState.activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts(); const result = await window.daybreakMail.listDrafts();
if (isAndroid && mailFeatureState.syncRequest !== request) return;
renderDrafts(result.drafts || []); renderDrafts(result.drafts || []);
mailFeatureState.autoLoadBlocked = true;
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`); if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
return; return;
} }
const folder = rendererState.activeFolder; const folder = rendererState.activeFolder;
const accountId = mailFeatureState.connectedAccount.id; const accountId = mailFeatureState.connectedAccount.id;
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset); const offset = options.offset ?? (options.append ? mailFeatureState.nextOffset : mailFeatureState.pageOffset);
const filters = mailSearchFilters(); const filters = mailSearchFilters();
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId; const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId &&
(!isAndroid || mailFeatureState.syncRequest === request);
if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) { if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) {
try { try {
const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters); const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters);
if (cached && isCurrentMailbox()) { if (cached && isCurrentMailbox()) {
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages); rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
rendererState.activeMessage = null; rendererState.activeMessage = null;
mailFeatureState.pageOffset = offset;
mailFeatureState.nextOffset = offset + cached.messages.length;
mailFeatureState.total = cached.total;
mailFeatureState.autoLoadBlocked = true;
const pagination = selectMailUi('#pagination');
if (pagination) pagination.textContent = cached.total ? `${cached.start}–${cached.end} of ${cached.total} saved messages` : '0 saved messages';
const loadMore = selectMailUi('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', cached.messages.length >= cached.total);
appShell.renderList(); appShell.renderList();
showingCachedMessages = true; showingCachedMessages = true;
const status = selectMailUi('#mail-status'); const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Showing saved messages — syncing'; if (status) status.textContent = 'Showing saved messages — syncing';
} }
} catch (error) { } catch (error) {
if (isAndroid && mailFeatureState.syncRequest !== request) return;
console.error('Could not load cached messages:', error); console.error('Could not load cached messages:', error);
} }
} }
@@ -691,8 +764,16 @@ async function syncMailbox(showToast, options = {}) {
const result = await window.daybreakMail.syncFolder(folder, offset, filters); const result = await window.daybreakMail.syncFolder(folder, offset, filters);
if (!isCurrentMailbox()) return; if (!isCurrentMailbox()) return;
const previouslyActiveMessage = rendererState.activeMessage; const previouslyActiveMessage = rendererState.activeMessage;
if (options.append) rendererState.messages.push(...result.messages); if (options.append) {
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages); const existing = new Set(rendererState.messages.map(message => JSON.stringify([message.sourceFolder || folder, message.uid || message.id])));
for (const message of result.messages) {
const key = JSON.stringify([message.sourceFolder || folder, message.uid || message.id]);
if (!existing.has(key)) {
rendererState.messages.push(message);
existing.add(key);
}
}
} else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
rendererState.messages.forEach(message => { rendererState.messages.forEach(message => {
try { try {
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]'); const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
@@ -701,6 +782,14 @@ async function syncMailbox(showToast, options = {}) {
}); });
if (!options.append) mailFeatureState.pageOffset = offset; if (!options.append) mailFeatureState.pageOffset = offset;
mailFeatureState.total = result.total; mailFeatureState.total = result.total;
const hasSearch = Boolean(filters.query || filters.sender || filters.subject || filters.after || filters.before || filters.hasAttachments);
const isSequencePage = !result.offline && folder !== 'Snoozed' && !hasSearch;
const consumed = isSequencePage && result.start > 0 && result.end >= result.start
? result.end - result.start + 1
: result.messages.length;
mailFeatureState.nextOffset = offset + consumed;
mailFeatureState.autoLoadBlocked = consumed === 0 || (options.append && result.messages.length === 0);
syncSucceeded = true;
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage) rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage ? previouslyActiveMessage
: window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id; : window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id;
@@ -709,11 +798,14 @@ async function syncMailbox(showToast, options = {}) {
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count'); const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
if (inboxCount) inboxCount.textContent = String(unread); if (inboxCount) inboxCount.textContent = String(unread);
const pagination = selectMailUi('#pagination'); const pagination = selectMailUi('#pagination');
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages'; if (pagination) pagination.textContent = result.total ? `${options.append ? mailFeatureState.pageOffset + 1 : result.start}–${options.append ? Math.min(mailFeatureState.nextOffset, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = selectMailUi('#load-more'); const loadMore = selectMailUi('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.pageOffset + rendererState.messages.length >= result.total); if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.nextOffset >= result.total || consumed === 0);
rendererState.query = ''; rendererState.query = '';
const messageList = selectMailUi('#message-list');
const scrollTop = options.append ? messageList.scrollTop : 0;
appShell.renderList(); appShell.renderList();
if (options.append) messageList.scrollTop = scrollTop;
if (rendererState.activeMessage) { if (rendererState.activeMessage) {
appShell.openMessage(rendererState.activeMessage); appShell.openMessage(rendererState.activeMessage);
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage); const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
@@ -725,16 +817,26 @@ async function syncMailbox(showToast, options = {}) {
} }
updateAccountCard(mailFeatureState.connectedAccount); updateAccountCard(mailFeatureState.connectedAccount);
const status = selectMailUi('#mail-status'); const status = selectMailUi('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail'; if (status) status.textContent = mailFeatureState.browseRefreshPending
? 'Updates paused while browsing — return to the top or refresh'
: result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`); if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
} catch (error) { } catch (error) {
if (isAndroid && mailFeatureState.syncRequest !== request) return;
if (options.append) mailFeatureState.autoLoadBlocked = true;
if (showingCachedMessages) { if (showingCachedMessages) {
const status = selectMailUi('#mail-status'); const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Could not sync — showing saved messages'; if (status) status.textContent = 'Could not sync — showing saved messages';
} else if (options.append) {
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Could not load more messages — use Load more to retry';
} }
toastMailUi(error.message || 'Could not sync the inbox'); toastMailUi(error.message || 'Could not sync the inbox');
} finally { } finally {
if (!isAndroid || mailFeatureState.syncRequest === request) {
if (refresh) refresh.disabled = false; if (refresh) refresh.disabled = false;
if (loadMoreButton) loadMoreButton.disabled = false;
}
} }
})(); })();
@@ -742,14 +844,68 @@ async function syncMailbox(showToast, options = {}) {
try { try {
await sync; await sync;
} finally { } finally {
if (mailFeatureState.syncPromise !== sync) return;
mailFeatureState.syncPromise = null; mailFeatureState.syncPromise = null;
mailFeatureState.syncMailboxKey = null;
if (mailFeatureState.syncQueued) { if (mailFeatureState.syncQueued) {
mailFeatureState.syncQueued = false; mailFeatureState.syncQueued = false;
void syncMailbox(false); void syncMailbox(false);
} else if (runDeferredMailboxRefresh()) {
return;
} else if (syncSucceeded) {
maybeLoadMoreMessages();
} }
} }
} }
function shouldDeferMailboxRefresh() {
if (window.daybreakMail?.platform !== 'android') return false;
const list = selectMailUi('#message-list');
return Boolean(list && (list.scrollTop > 120 ||
(document.body.classList.contains('reader-open') &&
(appShell.getReaderListPosition() > 120 ||
mailFeatureState.nextOffset > mailFeatureState.pageOffset + 20))));
}
function requestBackgroundMailboxRefresh(options = {}) {
if (shouldDeferMailboxRefresh()) {
mailFeatureState.browseRefreshPending = true;
if (options.offset === 0) mailFeatureState.browseRefreshFromStart = true;
const status = selectMailUi('#mail-status');
if (status && !mailFeatureState.syncPromise) {
status.textContent = 'Updates paused while browsing — return to the top or refresh';
}
return;
}
void syncMailbox(false, options);
}
function runDeferredMailboxRefresh() {
if (!mailFeatureState.browseRefreshPending || mailFeatureState.syncPromise ||
document.visibilityState !== 'visible' || rendererState.activeView !== 'mail' ||
shouldDeferMailboxRefresh()) return false;
const options = mailFeatureState.browseRefreshFromStart ? { offset: 0 } : {};
mailFeatureState.browseRefreshPending = false;
mailFeatureState.browseRefreshFromStart = false;
void syncMailbox(false, options);
return true;
}
function handleMessageListScroll() {
if (!runDeferredMailboxRefresh()) maybeLoadMoreMessages();
}
function maybeLoadMoreMessages() {
const list = selectMailUi('#message-list');
if (!list || !mailFeatureState.connectedAccount || mailFeatureState.syncPromise ||
mailFeatureState.autoLoadBlocked || rendererState.activeFolder === 'Drafts' ||
mailFeatureState.nextOffset >= mailFeatureState.total || !list.clientHeight ||
document.body.classList.contains('reader-open') ||
rendererState.activeView !== 'mail') return;
if (list.scrollHeight - list.scrollTop - list.clientHeight > 120) return;
void syncMailbox(false, { append: true });
}
if (window.daybreakMail) { if (window.daybreakMail) {
setupDraftComposer(); setupDraftComposer();
let searchTimer; let searchTimer;
@@ -806,7 +962,7 @@ if (window.daybreakMail) {
} }
if (update.newCount || (update.foldersChanged || []).length) { if (update.newCount || (update.foldersChanged || []).length) {
if (document.visibilityState === 'visible') { if (document.visibilityState === 'visible') {
syncMailbox(false, update.newCount ? { offset: 0 } : {}); requestBackgroundMailboxRefresh(update.newCount ? { offset: 0 } : {});
} }
else mailFeatureState.refreshPending = true; else mailFeatureState.refreshPending = true;
} }
@@ -814,18 +970,20 @@ if (window.daybreakMail) {
document.addEventListener('visibilitychange', () => { document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) { if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) {
mailFeatureState.refreshPending = false; mailFeatureState.refreshPending = false;
syncMailbox(false, { offset: 0 }); requestBackgroundMailboxRefresh({ offset: 0 });
} else if (document.visibilityState === 'visible') {
runDeferredMailboxRefresh();
} }
}); });
window.addEventListener('focus', () => { window.addEventListener('focus', () => {
if (mailFeatureState.connectedAccount) syncMailbox(false); if (mailFeatureState.connectedAccount) requestBackgroundMailboxRefresh();
}); });
window.addEventListener('online', () => { window.addEventListener('online', () => {
if (mailFeatureState.connectedAccount) syncMailbox(false, { offset: 0 }); if (mailFeatureState.connectedAccount) requestBackgroundMailboxRefresh({ offset: 0 });
}); });
setInterval(() => { setInterval(() => {
if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') { if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') {
syncMailbox(false); requestBackgroundMailboxRefresh();
} }
}, 60 * 1000); }, 60 * 1000);
selectMailUi('#account-settings').addEventListener('click', openMailAccount); selectMailUi('#account-settings').addEventListener('click', openMailAccount);
@@ -854,7 +1012,13 @@ if (window.daybreakMail) {
mailFeatureState.pageOffset += 20; mailFeatureState.pageOffset += 20;
syncMailbox(false, { offset: mailFeatureState.pageOffset }); syncMailbox(false, { offset: mailFeatureState.pageOffset });
}; };
selectMailUi('#load-more').onclick = () => syncMailbox(false, { append: true }); selectMailUi('#load-more').onclick = () => {
if (!mailFeatureState.syncPromise) void syncMailbox(false, { append: true });
};
selectMailUi('#message-list').addEventListener('scroll', handleMessageListScroll, { passive: true });
document.addEventListener('click', event => {
if (event.target.closest('#reader-back')) runDeferredMailboxRefresh();
});
document.addEventListener('click', async event => { document.addEventListener('click', async event => {
const sendButton = event.target.closest('#send'); const sendButton = event.target.closest('#send');
if (!sendButton || !mailFeatureState.connectedAccount) return; if (!sendButton || !mailFeatureState.connectedAccount) return;
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.15", "version": "0.5.22",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.15", "version": "0.5.22",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.15", "version": "0.5.22",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
+5 -9
View File
@@ -19,9 +19,7 @@ function openEncryptionKeys() {
const root = selectPgpKeyUi('#modal-root'); const root = selectPgpKeyUi('#modal-root');
const account = window.epMailFeatures.mail.connectedAccount || {}; const account = window.epMailFeatures.mail.connectedAccount || {};
const androidPgp = window.daybreakMail?.pgp?.platform === 'android'; const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
const serverSettings = androidPgp const serverSettings = `<h3 class="pgp-heading">Public key servers</h3>
? '<h3 class="pgp-heading">Public key servers</h3><p class="account-note">Key-server lookup and publication are disabled in Android testing. Import a public key directly and compare its fingerprint with the owner.</p><div hidden><div id="pgp-server-list"></div><input id="pgp-search-email"><button id="pgp-find-key"></button><div id="pgp-found-keys"></div><select id="pgp-publish-server"></select><input id="pgp-server-name"><input id="pgp-server-url"><select id="pgp-server-protocol"></select><button id="pgp-add-server"></button></div>'
: `<h3 class="pgp-heading">Public key servers</h3>
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p> <p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div> <div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label> <label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
@@ -359,7 +357,6 @@ function openEncryptionKeys() {
}; };
enabledLabel.append(enabledText, enabled); enabledLabel.append(enabledText, enabled);
row.append(info, enabledLabel); row.append(info, enabledLabel);
if (!server.builtin) {
const remove = document.createElement('button'); const remove = document.createElement('button');
remove.className = 'discard'; remove.className = 'discard';
remove.textContent = 'Remove'; remove.textContent = 'Remove';
@@ -367,11 +364,10 @@ function openEncryptionKeys() {
try { try {
await window.daybreakMail.pgp.removeKeyServer(server.id); await window.daybreakMail.pgp.removeKeyServer(server.id);
await renderKeyServers(); await renderKeyServers();
status('Custom key server removed.'); status(`${server.name} removed.`);
} catch (error) { status(error.message || 'Could not remove the key server.'); } } catch (error) { status(error.message || 'Could not remove the key server.'); }
}; };
row.append(remove); row.append(remove);
}
list.append(row); list.append(row);
}); });
} }
@@ -451,13 +447,13 @@ function openEncryptionKeys() {
catch (error) { status(error.message || 'Could not save the setting.'); } catch (error) { status(error.message || 'Could not save the setting.'); }
}; };
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); }; selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
if (!androidPgp) void renderKeyServers(); void renderKeyServers();
void renderContacts(); void renderContacts();
void render(); void render();
} }
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () { window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => async function () {
baseOpenPreferences(); await baseOpenPreferences();
const fields = selectPgpKeyUi('#modal-root .compose-fields'); const fields = selectPgpKeyUi('#modal-root .compose-fields');
if (!fields || !pgpAvailable()) return; if (!fields || !pgpAvailable()) return;
const button = document.createElement('button'); const button = document.createElement('button');
+5564 -4942
View File
File diff suppressed because one or more lines are too long
+17 -2
View File
@@ -1,8 +1,23 @@
import { Capacitor, registerPlugin } from '@capacitor/core'; import { Capacitor, CapacitorHttp, registerPlugin } from '@capacitor/core';
import { createAndroidPgp } from './android-pgp.js'; import { createAndroidPgp } from './android-pgp.js';
const EpMail = registerPlugin('EpMail'); const EpMail = registerPlugin('EpMail');
// Native HTTP avoids WebView CORS limits; redirects are refused like on desktop.
async function nativeFetch(url, options = {}) {
const headers = options.headers || {};
const contentType = String(headers['content-type'] || '');
let data = options.body;
if (typeof data === 'string' && contentType.includes('json')) data = JSON.parse(data);
else if (typeof data === 'string' && contentType.includes('x-www-form-urlencoded')) data = Object.fromEntries(new URLSearchParams(data));
const response = await CapacitorHttp.request({ url: String(url), method: options.method || 'GET', headers, data,
responseType: 'text', disableRedirects: true, connectTimeout: 15000, readTimeout: 15000 });
const text = typeof response.data === 'string' ? response.data : JSON.stringify(response.data ?? '');
const lowered = Object.fromEntries(Object.entries(response.headers || {}).map(([name, value]) => [name.toLowerCase(), value]));
return { status: response.status, ok: response.status >= 200 && response.status < 300,
headers: { get: name => lowered[String(name).toLowerCase()] ?? null }, body: [new TextEncoder().encode(text)] };
}
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
const daybreakMail = { const daybreakMail = {
platform: 'android', platform: 'android',
@@ -63,6 +78,6 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
davSaveContact: contact => EpMail.davSaveContact(contact), davSaveContact: contact => EpMail.davSaveContact(contact),
davDeleteContact: remote => EpMail.davDeleteContact(remote) davDeleteContact: remote => EpMail.davDeleteContact(remote)
}; };
daybreakMail.pgp = createAndroidPgp({ EpMail, getAccount: () => EpMail.getAccount() }); daybreakMail.pgp = createAndroidPgp({ EpMail, getAccount: () => EpMail.getAccount(), fetchImpl: nativeFetch });
window.daybreakMail = daybreakMail; window.daybreakMail = daybreakMail;
} }
+70 -8
View File
@@ -1,4 +1,7 @@
import * as openpgp from 'openpgp'; import * as openpgp from 'openpgp';
import keyServers from '../desktop/pgp-keyservers.cjs';
const { BUILTIN_SERVER_IDS, MAX_CUSTOM_SERVERS, createKeyServerService, listServers, normalizeCustomServer } = keyServers;
const MAX_KEY_LENGTH = 200000; const MAX_KEY_LENGTH = 200000;
const MAX_MESSAGE_BYTES = 25 * 1024 * 1024; const MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
@@ -255,8 +258,19 @@ async function signatureStatuses(signatures, verification, sender) {
return results; return results;
} }
export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.confirm }) { export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.confirm, fetchImpl }) {
const keyServerService = createKeyServerService({ fetchImpl });
let storePromise; let storePromise;
function serverSettings(data) {
const settings = data.settings || {};
const ids = value => Array.isArray(value) ? [...new Set(value.filter(id => typeof id === 'string'))] : [];
return { ...settings, customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
enabledKeyServers: ids(settings.enabledKeyServers), removedBuiltinKeyServers: ids(settings.removedBuiltinKeyServers) };
}
function currentServers(data) {
const settings = serverSettings(data);
return listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
}
const passphrases = new Map(); const passphrases = new Map();
let cacheMinutes = 10; let cacheMinutes = 10;
@@ -310,7 +324,7 @@ export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.conf
} }
const user = await key.getPrimaryUser(); const user = await key.getPrimaryUser();
data.contacts.push({ fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', data.contacts.push({ fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown',
source: ['import', 'message', 'paste'].includes(source) ? source : 'import', addedAt: Date.now(), publicKey: key.armor() }); source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import', addedAt: Date.now(), publicKey: key.armor() });
await persist(data); await persist(data);
return { contact: { fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', source, addedAt: Date.now() }, keyChangedFrom }; return { contact: { fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', source, addedAt: Date.now() }, keyChangedFrom };
} }
@@ -607,12 +621,60 @@ export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.conf
return { cacheMinutes }; return { cacheMinutes };
}, },
async forgetPassphrases() { clear(); return { cleared: true }; }, async forgetPassphrases() { clear(); return { cleared: true }; },
async keyServers() { return []; }, async keyServers() { return currentServers(await store()); },
async findKey() { throw new Error('Key-server lookup is not included in Android testing. Import a public key directly.'); }, async findKey({ email } = {}) { return keyServerService.lookupEnabled(currentServers(await store()), email); },
async addKeyServer() { throw new Error('Key-server support is not included in Android testing.'); }, async addKeyServer(input) {
async removeKeyServer() { throw new Error('Key-server support is not included in Android testing.'); }, const candidate = normalizeCustomServer(input);
async setKeyServerEnabled() { throw new Error('Key-server support is not included in Android testing.'); }, const data = await store();
async publishKey() { throw new Error('Key-server support is not included in Android testing.'); }, const settings = serverSettings(data);
const custom = settings.customKeyServers.map(normalizeCustomServer);
if (custom.length >= MAX_CUSTOM_SERVERS) throw new Error(`You can configure up to ${MAX_CUSTOM_SERVERS} custom key servers.`);
if (currentServers(data).some(server => server.url === candidate.url && server.protocol === candidate.protocol)) throw new Error('That key server is already configured.');
const host = new URL(candidate.url).host;
if (!confirm(`Allow ep-mail to contact ${host} for OpenPGP keys?\n\nProtocol: ${candidate.protocol.toUpperCase()}\nThe server may learn which email addresses you search for. Only add a server you trust.`)) return { canceled: true };
candidate.id = crypto.randomUUID();
data.settings = { ...serverSettings(data), customKeyServers: [...custom, candidate] };
await persist(data);
return { server: candidate };
},
async removeKeyServer(serverId) {
const id = String(serverId || '');
const data = await store();
const settings = serverSettings(data);
const custom = settings.customKeyServers.filter(server => server.id !== id);
const removesBuiltin = BUILTIN_SERVER_IDS.includes(id) && !settings.removedBuiltinKeyServers.includes(id);
if (custom.length === settings.customKeyServers.length && !removesBuiltin) throw new Error('That key server was not found.');
data.settings = { ...settings, customKeyServers: custom,
enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id),
removedBuiltinKeyServers: removesBuiltin ? [...settings.removedBuiltinKeyServers, id] : settings.removedBuiltinKeyServers };
await persist(data);
return { removed: true };
},
async setKeyServerEnabled(serverId, enabled) {
if (typeof enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.');
const id = String(serverId || '');
const data = await store();
if (!currentServers(data).some(server => server.id === id)) throw new Error('That key server was not found.');
const settings = serverSettings(data);
const next = new Set(settings.enabledKeyServers);
if (enabled) next.add(id); else next.delete(id);
data.settings = { ...settings, enabledKeyServers: [...next] };
await persist(data);
return { serverId: id, enabled };
},
async publishKey({ fingerprint, serverId } = {}) {
const data = await store();
const server = currentServers(data).find(item => item.id === String(serverId || ''));
if (!server) throw new Error('Choose a configured key server.');
if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.');
const entry = data.keys.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
if (!entry.email) throw new Error('This key has no email address to publish.');
const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey });
if (!emailsOf(publicKey).includes(String(entry.email).toLowerCase())) throw new Error('The selected key no longer matches its stored email address.');
if (!confirm(`Publish the public key for ${entry.email} to ${server.name}?\n\nFingerprint:\n${fingerprint.match(/.{1,4}/g).join(' ')}\n\nOnly the public key will be sent. This exposes the email address in the key to the server, which may retain it. The server may send a verification email before the key becomes searchable.`)) return { canceled: true };
return keyServerService.publish(server, entry.email, entry.publicKey, fingerprint);
},
clearPassphrases: clear, clearPassphrases: clear,
buildOutgoing buildOutgoing
}; };
+25 -2
View File
@@ -1,5 +1,28 @@
const CACHE='ep-mail-v19'; const CACHE='ep-mail-v22';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting()))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim()))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); self.addEventListener('fetch', event => {
const request = event.request;
if (request.method !== 'GET' || new URL(request.url).origin !== location.origin) return;
event.respondWith((async () => {
let response;
try {
response = await fetch(request, { cache: 'no-cache' });
} catch (error) {
const cached = await caches.match(request) ||
(request.mode === 'navigate' ? await caches.match('./index.html') : null);
if (cached) return cached;
throw error;
}
if (response.ok) {
try {
const cache = await caches.open(CACHE);
await cache.put(request, response.clone());
} catch (error) {
console.error('Could not update offline app cache:', error);
}
}
return response;
})());
});
+2 -2
View File
@@ -65,8 +65,8 @@ document.addEventListener('keydown', event => {
action.run(); action.run();
}); });
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () { shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => async function () {
baseOpenPreferences(); await baseOpenPreferences();
const fields = selectShortcutUi('#modal-root .compose-fields'); const fields = selectShortcutUi('#modal-root .compose-fields');
const save = selectShortcutUi('#save-appearance'); const save = selectShortcutUi('#save-appearance');
if (!fields || !save) return; if (!fields || !save) return;
+5 -3
View File
@@ -114,7 +114,7 @@ body.ep-daylight .compose-line input::placeholder,body.ep-daylight .compose-body
body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b} body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b}
body.ep-daylight .toast{background:#11212b;color:#f1f1e9} body.ep-daylight .toast{background:#11212b;color:#f1f1e9}
body.ep-daylight .row-check:checked{accent-color:#526a2c} body.ep-daylight .row-check:checked{accent-color:#526a2c}
.compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-fields{min-height:0;flex:1 1 auto;overflow-y:auto} .compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-modal>.modal-head,.compose-modal>.compose-footer{flex:none}.compose-fields{min-height:0;flex:0 1 auto;overflow-y:auto}.compose-modal>.compose-body{flex:1 1 120px;min-height:90px;height:auto}
.snooze-options .outline-button{width:100%;text-align:left} .snooze-options .outline-button{width:100%;text-align:left}
.mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap} .mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap}
@media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}} @media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}}
@@ -199,8 +199,10 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.compose-line input[type=checkbox]{flex:0 0 auto;width:20px;height:20px} .compose-line input[type=checkbox]{flex:0 0 auto;width:20px;height:20px}
.compose-line span{flex:0 1 54%;line-height:1.25} .compose-line span{flex:0 1 54%;line-height:1.25}
.compose-line input:not([type=checkbox]){flex:1;max-width:100%;min-width:0} .compose-line input:not([type=checkbox]){flex:1;max-width:100%;min-width:0}
.compose-footer{gap:8px;padding:10px 12px} .compose-footer{gap:8px;padding:10px 12px;flex-wrap:wrap;justify-content:flex-end}
.compose-body{height:30vh;padding:12px} .compose-footer .pgp-compose{flex:1 0 100%;flex-wrap:wrap;margin-right:0;gap:4px 12px}
.compose-footer .send-button{order:99;padding:10px 18px;font-size:12px}
.compose-body{padding:12px}
.account-note,.account-status{font-size:12px} .account-note,.account-status{font-size:12px}
.mail-rule-row{grid-template-columns:1fr;gap:6px} .mail-rule-row{grid-template-columns:1fr;gap:6px}
.mail-rule-row>*{grid-column:1} .mail-rule-row>*{grid-column:1}
+343 -3
View File
@@ -16,8 +16,8 @@ function deferred() {
function harness({ platform = 'android', cached, sync }) { function harness({ platform = 'android', cached, sync }) {
const messages = []; const messages = [];
const state = { messages, activeMessage: null, activeFolder: 'Inbox', selectedIds: new Set(), query: '' }; const state = { messages, activeMessage: null, activeFolder: 'Inbox', activeView: 'mail', selectedIds: new Set(), query: '' };
const feature = { connectedAccount: { id: 'account' }, pageOffset: 0, syncPromise: null, syncQueued: false }; const feature = { connectedAccount: { id: 'account' }, pageOffset: 0, syncPromise: null, syncQueued: false, displayedMailboxKey: JSON.stringify(['account', 'Inbox']) };
const elements = new Map(); const elements = new Map();
const opened = []; const opened = [];
const renders = []; const renders = [];
@@ -31,7 +31,7 @@ function harness({ platform = 'android', cached, sync }) {
if (cached) bridge.getCachedFolder = cached; if (cached) bridge.getCachedFolder = cached;
const context = { const context = {
window: { daybreakMail: bridge }, window: { daybreakMail: bridge },
document: { body: { classList: { remove: value => classes.delete(value) } } }, document: { visibilityState: 'visible', body: { classList: { remove: value => classes.delete(value), contains: value => classes.has(value) } } },
rendererState: state, rendererState: state,
mailFeatureState: feature, mailFeatureState: feature,
selectMailUi: selector => { selectMailUi: selector => {
@@ -41,6 +41,7 @@ function harness({ platform = 'android', cached, sync }) {
appShell: { appShell: {
renderList: () => renders.push(messages.map(message => message.id)), renderList: () => renders.push(messages.map(message => message.id)),
openMessage: id => opened.push(id), openMessage: id => opened.push(id),
getReaderListPosition: () => 0,
emptyReader: () => 'empty' emptyReader: () => 'empty'
}, },
mailSearchFilters: () => ({}), mailSearchFilters: () => ({}),
@@ -130,6 +131,333 @@ test('a sync result for a previous folder does not replace the current mailbox',
assert.deepEqual(ui.opened, []); assert.deepEqual(ui.opened, []);
}); });
test('switching folders shows that folder’s cached messages before the network response', async () => {
const network = deferred();
const ui = harness({
cached: async folder => folder === 'Sent' ? result([42]) : null,
sync: () => network.promise
});
ui.state.messages.push({ id: 1, uid: 1, tags: [] });
ui.state.activeFolder = 'Sent';
const pending = ui.context.syncMailbox(false, { offset: 0 });
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(ui.state.messages.map(message => message.id), [42]);
assert.deepEqual(ui.renders.at(-1), [42]);
network.resolve(result([43]));
await pending;
});
test('a different folder can load from cache while the previous folder is still syncing', async () => {
const inbox = deferred();
const sent = deferred();
const ui = harness({
cached: async folder => folder === 'Sent' ? result([42]) : null,
sync: folder => folder === 'Inbox' ? inbox.promise : sent.promise
});
const first = ui.context.syncMailbox(false);
await new Promise(resolve => setImmediate(resolve));
ui.state.activeFolder = 'Sent';
const second = ui.context.syncMailbox(false, { offset: 0 });
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(ui.state.messages.map(message => message.id), [42]);
sent.resolve(result([43]));
await second;
inbox.resolve(result([1]));
await first;
assert.deepEqual(ui.state.messages.map(message => message.id), [43]);
});
test('returning to a folder ignores an older request for the same folder', async () => {
const firstInbox = deferred();
const sent = deferred();
const secondInbox = deferred();
let calls = 0;
const ui = harness({
sync: () => [firstInbox, sent, secondInbox][calls++].promise
});
const first = ui.context.syncMailbox(false);
ui.state.activeFolder = 'Sent';
const middle = ui.context.syncMailbox(false);
ui.state.activeFolder = 'Inbox';
const last = ui.context.syncMailbox(false);
secondInbox.resolve(result([3]));
await last;
firstInbox.resolve(result([1]));
sent.resolve(result([2]));
await Promise.all([first, middle]);
assert.deepEqual(ui.state.messages.map(message => message.id), [3]);
assert.equal(ui.elements.get('#refresh').disabled, false);
});
test('switching accounts never displays the previous account’s messages', async () => {
const network = deferred();
const ui = harness({ cached: async () => null, sync: () => network.promise });
ui.state.messages.push({ id: 1, uid: 1, tags: [] });
ui.feature.connectedAccount = { id: 'other' };
const pending = ui.context.syncMailbox(false);
assert.equal(ui.state.messages.length, 0);
network.resolve(result([2]));
await pending;
assert.deepEqual(ui.state.messages.map(message => message.id), [2]);
});
test('scrolling to the end appends one page and retains the scroll position', async () => {
const next = deferred();
const offsets = [];
const ui = harness({ sync: (_folder, offset) => {
offsets.push(offset);
return next.promise;
} });
ui.state.messages.push(...result([1, 2]).messages);
ui.feature.total = 5;
ui.feature.nextOffset = 2;
const list = ui.context.selectMailUi('#message-list');
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 700 });
ui.context.appShell.renderList = () => { list.scrollTop = 0; };
ui.context.maybeLoadMoreMessages();
ui.context.maybeLoadMoreMessages();
assert.deepEqual(offsets, [2]);
list.scrollHeight = 1400;
next.resolve({ messages: result([3, 4]).messages, total: 5, start: 2, end: 3 });
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3, 4]);
assert.equal(list.scrollTop, 700);
assert.deepEqual(offsets, [2]);
});
test('Android background refresh waits while browsing and runs at the top', async () => {
const offsets = [];
const ui = harness({ sync: async (_folder, offset) => {
offsets.push(offset);
return { messages: result([1, 2]).messages, total: 40, start: 21, end: 22 };
} });
ui.state.messages.push(...result([1, 2, 3]).messages);
ui.feature.total = 40;
ui.feature.nextOffset = 40;
const list = ui.context.selectMailUi('#message-list');
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 700 });
ui.context.requestBackgroundMailboxRefresh();
ui.context.requestBackgroundMailboxRefresh({ offset: 0 });
assert.deepEqual(offsets, []);
assert.equal(ui.feature.browseRefreshPending, true);
assert.match(ui.elements.get('#mail-status').textContent, /Updates paused/);
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3]);
list.scrollTop = 0;
ui.context.handleMessageListScroll();
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(offsets, [0]);
assert.equal(ui.feature.browseRefreshPending, false);
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2]);
});
test('automatic refresh is deferred during an Android page fetch and manual refresh remains available', async () => {
const page = deferred();
const offsets = [];
const ui = harness({ sync: (_folder, offset) => {
offsets.push(offset);
return offsets.length === 1 ? page.promise : Promise.resolve(result([1]));
} });
ui.state.messages.push(...result([1, 2]).messages);
ui.feature.total = 40;
ui.feature.nextOffset = 20;
const list = ui.context.selectMailUi('#message-list');
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 700 });
const pending = ui.context.syncMailbox(false, { append: true });
assert.match(ui.elements.get('#mail-status').textContent, /Loading more/);
ui.context.requestBackgroundMailboxRefresh({ offset: 0 });
list.scrollHeight = 1400;
page.resolve({ messages: result([3, 4]).messages, total: 40, start: 1, end: 2 });
await pending;
assert.deepEqual(offsets, [20]);
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3, 4]);
assert.match(ui.elements.get('#mail-status').textContent, /Updates paused/);
await ui.context.syncMailbox(true, { offset: 0 });
assert.deepEqual(offsets, [20, 0]);
assert.equal(ui.feature.browseRefreshPending, false);
});
test('desktop background refresh remains immediate while scrolled down', async () => {
const offsets = [];
const ui = harness({ platform: 'desktop', sync: async (_folder, offset) => {
offsets.push(offset);
return result([1]);
} });
Object.assign(ui.context.selectMailUi('#message-list'), { scrollTop: 700, scrollHeight: 1000, clientHeight: 300 });
ui.context.requestBackgroundMailboxRefresh({ offset: 0 });
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(offsets, [0]);
});
test('Android defers background refresh when the hidden reader list was scrolled', () => {
let calls = 0;
const ui = harness({ sync: async () => { calls++; return result([1]); } });
ui.context.appShell.getReaderListPosition = () => 500;
ui.classes.add('reader-open');
Object.assign(ui.context.selectMailUi('#message-list'), { scrollTop: 0 });
ui.feature.nextOffset = 20;
ui.context.requestBackgroundMailboxRefresh();
assert.equal(calls, 0);
assert.equal(ui.feature.browseRefreshPending, true);
});
test('short lists continue loading until the viewport is filled', async () => {
let calls = 0;
const ui = harness({ sync: async () => {
calls++;
return calls === 1
? { messages: result([1]).messages, total: 3, start: 3, end: 3 }
: { messages: result([2, 3]).messages, total: 3, start: 1, end: 2 };
} });
const list = ui.context.selectMailUi('#message-list');
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
await ui.context.syncMailbox(false, { offset: 0 });
await new Promise(resolve => setImmediate(resolve));
assert.equal(calls, 2);
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3]);
});
test('an appended page does not duplicate messages returned by a shifting mailbox', async () => {
const ui = harness({ sync: async () => ({ messages: result([2, 3, 3]).messages, total: 4, start: 1, end: 3 }) });
ui.state.messages.push(...result([1, 2]).messages);
ui.feature.total = 4;
ui.feature.nextOffset = 2;
await ui.context.syncMailbox(false, { append: true });
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3]);
});
test('automatic loading waits for the list bottom and stops at the last page', () => {
let calls = 0;
const ui = harness({ sync: async () => { calls++; return result([]); } });
ui.feature.total = 40;
ui.feature.nextOffset = 20;
const list = ui.context.selectMailUi('#message-list');
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 100 });
ui.context.maybeLoadMoreMessages();
assert.equal(calls, 0);
list.scrollTop = 700;
ui.feature.nextOffset = 40;
ui.context.maybeLoadMoreMessages();
assert.equal(calls, 0);
ui.feature.nextOffset = 20;
ui.state.activeFolder = 'Drafts';
ui.context.maybeLoadMoreMessages();
assert.equal(calls, 0);
});
test('pagination advances over snoozed messages and stops automatic loading on empty pages', async () => {
const offsets = [];
const ui = harness({ sync: async (_folder, offset) => {
offsets.push(offset);
if (offset === 0) return { messages: result([1]).messages, total: 45, start: 26, end: 45 };
return { messages: [], total: 45, start: 6, end: 25 };
} });
await ui.context.syncMailbox(false, { offset: 0 });
assert.equal(ui.feature.nextOffset, 20);
await ui.context.syncMailbox(false, { append: true });
assert.deepEqual(offsets, [0, 20]);
assert.equal(ui.feature.nextOffset, 40);
assert.equal(ui.feature.autoLoadBlocked, true);
});
test('automatic pagination stops after a failed or empty fetch', async () => {
let calls = 0;
const ui = harness({ sync: async () => { calls++; throw new Error('Offline'); } });
ui.feature.total = 40;
ui.feature.nextOffset = 20;
const list = ui.context.selectMailUi('#message-list');
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
ui.context.maybeLoadMoreMessages();
await new Promise(resolve => setImmediate(resolve));
ui.context.maybeLoadMoreMessages();
assert.equal(calls, 1);
assert.equal(ui.feature.autoLoadBlocked, true);
assert.deepEqual(ui.toasts, ['Offline']);
});
test('offline cached pages can load automatically and stop at the cached total', async () => {
let calls = 0;
const ui = harness({ sync: async (_folder, offset) => {
calls++;
return offset === 0
? { messages: result([1]).messages, total: 2, start: 1, end: 1, offline: true }
: { messages: result([2]).messages, total: 2, start: 2, end: 2, offline: true };
} });
const list = ui.context.selectMailUi('#message-list');
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
await ui.context.syncMailbox(false);
await new Promise(resolve => setImmediate(resolve));
assert.equal(calls, 2);
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2]);
});
test('Android cache keeps newest messages when loading older pages', () => {
const vault = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidAccountVault.kt'), 'utf8');
const service = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8');
assert.match(vault, /sortedByDescending \{ it\.optLong\("timestamp"\) \}\.take\(30\)/);
assert.match(service, /cacheMessages\(account\.optString\("id"\), requestedFolder, cached, replace = offset <= 0\)/);
});
test('folder discovery deduplicates concurrent requests and ignores the previous account', async () => {
const first = deferred();
const second = deferred();
let calls = 0;
const feature = { connectedAccount: { id: 'one' }, customFolders: [] };
const renders = [];
const context = {
mailFeatureState: feature,
window: { daybreakMail: { listFolders: () => [first, second][calls++].promise } },
renderCustomFolders: () => renders.push(feature.customFolders.map(folder => folder.id)),
console
};
const start = source.indexOf('async function loadCustomFolders()');
const end = source.indexOf('\n// Destination options', start);
vm.runInNewContext(`${source.slice(start, end)}\nthis.loadCustomFolders = loadCustomFolders`, context);
const pending = context.loadCustomFolders();
const duplicate = context.loadCustomFolders();
assert.equal(calls, 1);
feature.connectedAccount = { id: 'two' };
const current = context.loadCustomFolders();
assert.equal(calls, 2);
second.resolve({ folders: [{ id: 'new' }] });
await current;
first.resolve({ folders: [{ id: 'old' }] });
await Promise.all([pending, duplicate]);
assert.deepEqual(feature.customFolders.map(folder => folder.id), ['new']);
assert.deepEqual(renders, [['new']]);
});
test('folder discovery reports errors and allows retry', async () => {
let calls = 0;
const errors = [];
const feature = { connectedAccount: { id: 'one' }, customFolders: [] };
const context = {
mailFeatureState: feature,
window: { daybreakMail: { listFolders: async () => {
if (++calls === 1) throw new Error('Unavailable');
return { folders: [{ id: 'retried' }] };
} } },
renderCustomFolders() {},
console: { error: (...args) => errors.push(args) }
};
const start = source.indexOf('async function loadCustomFolders()');
const end = source.indexOf('\n// Destination options', start);
vm.runInNewContext(`${source.slice(start, end)}\nthis.loadCustomFolders = loadCustomFolders`, context);
await context.loadCustomFolders();
await context.loadCustomFolders();
assert.equal(errors.length, 1);
assert.equal(feature.customFolders[0].id, 'retried');
assert.equal(calls, 2);
});
test('Android folder discovery and message actions do not run on the Capacitor plugin thread', () => {
const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8');
const list = plugin.slice(plugin.indexOf('fun listFolders('), plugin.indexOf('fun createFolder('));
const action = plugin.slice(plugin.indexOf('fun updateMessage('), plugin.indexOf('fun setSnooze('));
assert.ok(list.indexOf('folderListExecutor.execute') < list.indexOf('AndroidMailService.listFolders(account)'));
assert.ok(action.indexOf('mailActionExecutor.execute') < action.indexOf('AndroidMailService.updateMessage(account, input)'));
assert.match(action, /enqueueMailOperation/);
});
test('Android startup theme uses the EP vector on supported splash screens', () => { test('Android startup theme uses the EP vector on supported splash screens', () => {
const styles = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'values', 'styles.xml'), 'utf8'); const styles = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'values', 'styles.xml'), 'utf8');
const icon = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'drawable', 'ep_splash_icon.xml'), 'utf8'); const icon = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'drawable', 'ep_splash_icon.xml'), 'utf8');
@@ -137,3 +465,15 @@ test('Android startup theme uses the EP vector on supported splash screens', ()
assert.match(styles, /name="postSplashScreenTheme">@style\/AppTheme.NoActionBar/); assert.match(styles, /name="postSplashScreenTheme">@style\/AppTheme.NoActionBar/);
assert.match(icon, /android:strokeColor="#eee9de"/); assert.match(icon, /android:strokeColor="#eee9de"/);
}); });
test('Android launcher icons use the EP logo on adaptive and legacy launchers', () => {
const res = path.join(root, 'android', 'app', 'src', 'main', 'res');
const read = (...parts) => fs.readFileSync(path.join(res, ...parts), 'utf8');
for (const name of ['ic_launcher.xml', 'ic_launcher_round.xml']) {
assert.match(read('mipmap-anydpi-v26', name), /@drawable\/ep_launcher_foreground/);
assert.match(read('mipmap-anydpi', name), /@drawable\/ep_splash_icon/);
}
assert.match(read('drawable', 'ep_launcher_foreground.xml'), /@drawable\/ep_splash_icon/);
assert.match(read('drawable', 'ep_launcher_foreground.xml'), /android:inset="22dp"/);
assert.match(read('values', 'ic_launcher_background.xml'), /#0a0c0b/);
});
+78
View File
@@ -0,0 +1,78 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const root = path.resolve(__dirname, '..');
const source = fs.readFileSync(path.join(root, 'app.js'), 'utf8');
const helpers = source.slice(source.indexOf('let readerListPosition = null;'), source.indexOf('function renderList()'));
function harness(platform = 'android') {
const classes = new Set();
const list = { scrollTop: 0 };
const reader = { innerHTML: '' };
const state = { activeFolder: 'Inbox', activeMessage: 1 };
const context = {
window: { daybreakMail: { platform } },
document: { body: { classList: {
contains: value => classes.has(value),
remove: value => classes.delete(value)
} } },
state,
$: selector => selector === '#message-list' ? list : reader,
emptyReader: () => 'empty',
renderList: () => { list.scrollTop = 0; }
};
vm.runInNewContext(helpers, context);
return { context, classes, list, reader, state };
}
test('opening and returning to a message restores the Android list position', () => {
const ui = harness();
ui.list.scrollTop = 675;
ui.context.rememberReaderListPosition();
ui.classes.add('reader-open');
ui.list.scrollTop = 0;
ui.context.returnToMessageList();
assert.equal(ui.list.scrollTop, 675);
assert.equal(ui.state.activeMessage, null);
assert.equal(ui.classes.has('reader-open'), false);
assert.equal(ui.reader.innerHTML, 'empty');
});
test('reader rerenders do not overwrite the saved position', () => {
const ui = harness();
ui.list.scrollTop = 600;
ui.context.rememberReaderListPosition();
ui.classes.add('reader-open');
ui.list.scrollTop = 0;
ui.context.rememberReaderListPosition();
ui.context.returnToMessageList();
assert.equal(ui.list.scrollTop, 600);
});
test('changing folders or using desktop does not restore an unrelated position', () => {
const changed = harness();
changed.list.scrollTop = 600;
changed.context.rememberReaderListPosition();
changed.state.activeFolder = 'Sent';
changed.context.returnToMessageList();
assert.equal(changed.list.scrollTop, 0);
const desktop = harness('desktop');
desktop.list.scrollTop = 600;
desktop.context.rememberReaderListPosition();
desktop.context.returnToMessageList();
assert.equal(desktop.list.scrollTop, 0);
});
test('Android system back uses the same reader button and falls back outside the reader', () => {
const activity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8');
assert.match(activity, /getOnBackPressedDispatcher\(\)\.addCallback/);
assert.match(activity, /appLocked \|\| vaultRecoveryRequired/);
assert.match(activity, /reader-open/);
assert.match(activity, /#modal-root \.modal-overlay/);
assert.match(activity, /back\.click\(\)/);
assert.match(activity, /if \(!"true"\.equals\(result\)\) dispatchDefaultBack/);
assert.match(source, /\$\('#reader-back'\)\.onclick=returnToMessageList/);
});
+15
View File
@@ -11,6 +11,9 @@ const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'u
const androidDebugScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-apk.cjs'), 'utf8'); const androidDebugScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-apk.cjs'), 'utf8');
const androidReleaseScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-release-apk.cjs'), 'utf8'); const androidReleaseScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-release-apk.cjs'), 'utf8');
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8'); const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
const androidRootBuild = fs.readFileSync(path.join(root, 'android', 'build.gradle'), 'utf8');
const androidProperties = fs.readFileSync(path.join(root, 'android', 'gradle.properties'), 'utf8');
const androidWrapper = fs.readFileSync(path.join(root, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties'), 'utf8');
test('package metadata and lockfile share one release version', () => { test('package metadata and lockfile share one release version', () => {
assert.equal(packageLock.version, packageJson.version); assert.equal(packageLock.version, packageJson.version);
@@ -45,3 +48,15 @@ test('Android debug APK is labeled as debug and release APK requires signing cre
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_PASSWORD/); assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_PASSWORD/);
assert.match(androidReleaseScript, /ep-mail \$\{version\}\.apk/); assert.match(androidReleaseScript, /ep-mail \$\{version\}\.apk/);
}); });
test('Android Gradle and generated Capacitor modules use a compatible plugin version', () => {
const plugin = androidRootBuild.match(/classpath 'com\.android\.tools\.build:gradle:([^']+)'/);
const forced = androidRootBuild.match(/resolutionStrategy\.force 'com\.android\.tools\.build:gradle:([^']+)'/);
assert.ok(plugin && forced);
assert.equal(plugin[1], forced[1]);
assert.equal(plugin[1], '9.4.0');
assert.match(androidWrapper, /gradle-9\.7\.1-bin\.zip/);
assert.match(androidProperties, /^android\.builtInKotlin=false$/m);
assert.match(androidProperties, /^android\.newDsl=false$/m);
assert.match(androidBuild, /getDefaultProguardFile\('proguard-android-optimize\.txt'\)/);
});
+4 -1
View File
@@ -52,8 +52,11 @@ test('all built-in and custom key servers start disabled', () => {
url: 'https://keys.example.org', url: 'https://keys.example.org',
protocol: 'hkp' protocol: 'hkp'
}]); }]);
assert.equal(servers.length, 3); assert.equal(servers.length, 4);
assert.ok(servers.some(server => server.id === 'eternity-vks' && server.url === 'https://keys.eternityproject.fi' && server.protocol === 'vks'));
assert.ok(servers.every(server => server.enabled === false)); assert.ok(servers.every(server => server.enabled === false));
const trimmed = listServers([], [], ['openpgp-vks', 'mailvelope-hkp']);
assert.deepEqual(trimmed.map(server => server.id), ['eternity-vks']);
const enabled = listServers([], ['openpgp-vks']); const enabled = listServers([], ['openpgp-vks']);
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true); assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false); assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
+1 -1
View File
@@ -195,7 +195,7 @@ test('keyring: contacts, trust levels, expired passphrase cache and settings', a
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/); await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/);
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/); await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/); await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [] }); assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [], removedBuiltinKeyServers: [] });
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' }; const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] }); await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] });
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0); assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
+83
View File
@@ -0,0 +1,83 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '..', 'service-worker.js'), 'utf8');
function harness({ network, cached }) {
const handlers = {};
const writes = [];
const context = {
URL,
location: { origin: 'https://localhost' },
self: { addEventListener: (type, handler) => { handlers[type] = handler; } },
caches: {
match: async request => cached.get(typeof request === 'string' ? request : request.url),
open: async () => ({ put: async (request, response) => writes.push([request.url, response]) })
},
fetch: network
};
vm.runInNewContext(source, context);
return {
writes,
async request(request) {
let response;
const pending = [];
handlers.fetch({
request,
respondWith(value) { response = value; },
waitUntil(value) { pending.push(value); }
});
if (!response) return { intercepted: false };
const result = await response;
await Promise.all(pending);
return result;
}
};
}
test('new Android app assets replace old cached scripts', async () => {
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
const fresh = { ok: true, clone() { return this; } };
const old = { old: true };
const ui = harness({ network: async () => fresh, cached: new Map([[request.url, old]]) });
assert.equal(await ui.request(request), fresh);
assert.deepEqual(ui.writes, [[request.url, fresh]]);
assert.notEqual(source.match(/const CACHE\s*=\s*['"]([^'"]+)/)[1], 'ep-mail-v19');
});
test('offline requests use cached assets and missing assets fail explicitly', async () => {
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
const old = { old: true };
const offline = async () => { throw new Error('offline'); };
const ui = harness({ network: offline, cached: new Map([[request.url, old]]) });
assert.equal(await ui.request(request), old);
const missing = harness({ network: offline, cached: new Map() });
await assert.rejects(missing.request(request), /offline/);
});
test('network failures for navigation use the cached app shell', async () => {
const request = { method: 'GET', url: 'https://localhost/', mode: 'navigate' };
const shell = { shell: true };
const ui = harness({
network: async () => { throw new Error('offline'); },
cached: new Map([['./index.html', shell]])
});
assert.equal(await ui.request(request), shell);
});
test('HTTP error responses are not stored or replaced with cached content', async () => {
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
const failed = { ok: false, status: 404 };
const ui = harness({ network: async () => failed, cached: new Map([[request.url, { old: true }]]) });
assert.equal(await ui.request(request), failed);
assert.deepEqual(ui.writes, []);
});
test('cross-origin and non-GET requests are not intercepted', async () => {
const ui = harness({ network: async () => { throw new Error('unexpected fetch'); }, cached: new Map() });
assert.deepEqual(await ui.request({ method: 'GET', url: 'https://other.example/image.png' }), { intercepted: false });
assert.deepEqual(await ui.request({ method: 'POST', url: 'https://localhost/mail-ui.js' }), { intercepted: false });
});
+19 -1
View File
@@ -4,11 +4,26 @@ const state = window.epMailState;
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))} function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity; const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
let readerListPosition = null;
function rememberReaderListPosition() {
if (window.daybreakMail?.platform !== 'android' || document.body.classList.contains('reader-open')) return;
const list = $('#message-list');
readerListPosition = { folder: state.activeFolder, scrollTop: list.scrollTop };
}
function returnToMessageList() {
state.activeMessage = null;
document.body.classList.remove('reader-open');
$('#reader-pane').innerHTML = emptyReader();
renderList();
if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop;
readerListPosition = null;
}
function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}} function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}}
function openMessage(id){ function openMessage(id){
state.activeMessage=id; state.activeMessage=id;
const m=state.messages.find(x=>x.id===id); const m=state.messages.find(x=>x.id===id);
if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;} if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
rememberReaderListPosition();
document.body.classList.add('reader-open'); document.body.classList.add('reader-open');
m.unread=false; m.unread=false;
renderList(); renderList();
@@ -18,7 +33,7 @@ function openMessage(id){
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:''; const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join(''); const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><button class="reader-back" id="reader-back" type="button" aria-label="Back to messages">Back</button><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`; $('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><button class="reader-back" id="reader-back" type="button" aria-label="Back to messages">Back</button><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;
$('#reader-back').onclick=()=>{state.activeMessage=null;document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader();renderList()}; $('#reader-back').onclick=returnToMessageList;
$('#load-remote-images')?.addEventListener('click',()=>{ $('#load-remote-images')?.addEventListener('click',()=>{
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{ $('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src')); const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
@@ -51,6 +66,9 @@ window.epMailShell = Object.freeze({
get renderList() { return renderList; }, get renderList() { return renderList; },
get openMessage() { return openMessage; }, get openMessage() { return openMessage; },
get showCompose() { return showCompose; }, get showCompose() { return showCompose; },
getReaderListPosition() {
return readerListPosition?.folder === state.activeFolder ? readerListPosition.scrollTop : 0;
},
emptyReader, emptyReader,
wrapRenderList(decorator) { renderList = decorator(renderList); }, wrapRenderList(decorator) { renderList = decorator(renderList); },
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); }, wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
+179 -15
View File
@@ -8,12 +8,20 @@ const toastMailUi = appShell.toast;
const mailFeatureState = { const mailFeatureState = {
connectedAccount: null, connectedAccount: null,
pageOffset: 0, pageOffset: 0,
nextOffset: 0,
total: 0, total: 0,
autoLoadBlocked: false,
syncPromise: null, syncPromise: null,
syncQueued: false, syncQueued: false,
syncMailboxKey: null,
displayedMailboxKey: null,
refreshPending: false, refreshPending: false,
browseRefreshPending: false,
browseRefreshFromStart: false,
folderBeforeSearch: null, folderBeforeSearch: null,
customFolders: [], customFolders: [],
folderLoad: null,
foldersAccountId: null,
selectedDraftIds: new Set() selectedDraftIds: new Set()
}; };
@@ -142,10 +150,23 @@ function renderCustomFolders() {
async function loadCustomFolders() { async function loadCustomFolders() {
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return; if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
const accountId = mailFeatureState.connectedAccount.id;
if (mailFeatureState.folderLoad?.accountId === accountId) return mailFeatureState.folderLoad.promise;
const request = { accountId };
mailFeatureState.folderLoad = request;
request.promise = (async () => {
try { try {
mailFeatureState.customFolders = (await window.daybreakMail.listFolders()).folders || []; const result = await window.daybreakMail.listFolders();
if (mailFeatureState.folderLoad !== request || mailFeatureState.connectedAccount?.id !== accountId) return;
mailFeatureState.customFolders = result.folders || [];
renderCustomFolders(); renderCustomFolders();
} catch {} } catch (error) {
if (mailFeatureState.folderLoad === request) console.error('Could not load mail folders:', error);
} finally {
if (mailFeatureState.folderLoad === request) mailFeatureState.folderLoad = null;
}
})();
return request.promise;
} }
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders. // Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
@@ -183,6 +204,7 @@ async function createMailFolder() {
if (!name) return; if (!name) return;
try { try {
const result = await window.daybreakMail.createFolder(name); const result = await window.daybreakMail.createFolder(name);
mailFeatureState.folderLoad = null;
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders; mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
renderCustomFolders(); renderCustomFolders();
toastMailUi(`Folder “${result.folder?.name || name}” created`); toastMailUi(`Folder “${result.folder?.name || name}” created`);
@@ -192,6 +214,13 @@ async function createMailFolder() {
} }
function updateAccountCard(account) { function updateAccountCard(account) {
const accountId = mailFeatureState.connectedAccount?.id || null;
if (mailFeatureState.foldersAccountId !== accountId) {
mailFeatureState.foldersAccountId = accountId;
mailFeatureState.folderLoad = null;
mailFeatureState.customFolders = [];
renderCustomFolders();
}
const card = selectMailUi('#account-settings'); const card = selectMailUi('#account-settings');
if (!card) return; if (!card) return;
const email = account.email || ''; const email = account.email || '';
@@ -648,42 +677,86 @@ function setupDraftComposer() {
} }
async function syncMailbox(showToast, options = {}) { async function syncMailbox(showToast, options = {}) {
const isAndroid = window.daybreakMail?.platform === 'android';
const mailboxKey = JSON.stringify([mailFeatureState.connectedAccount?.id, rendererState.activeFolder]);
if (mailFeatureState.syncPromise) { if (mailFeatureState.syncPromise) {
if (!isAndroid || mailFeatureState.syncMailboxKey === mailboxKey) {
mailFeatureState.syncQueued = true; mailFeatureState.syncQueued = true;
return mailFeatureState.syncPromise; return mailFeatureState.syncPromise;
} }
mailFeatureState.syncQueued = false;
}
if (!mailFeatureState.connectedAccount || !window.daybreakMail) { if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
openMailAccount(); openMailAccount();
return; return;
} }
const refresh = selectMailUi('#refresh'); const refresh = selectMailUi('#refresh');
if (refresh) refresh.disabled = true; if (refresh) refresh.disabled = true;
const loadMoreButton = selectMailUi('#load-more');
if (loadMoreButton) loadMoreButton.disabled = true;
if (!options.append) {
mailFeatureState.browseRefreshPending = false;
mailFeatureState.browseRefreshFromStart = false;
} else {
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Loading more messages…';
}
const request = {};
mailFeatureState.syncRequest = request;
mailFeatureState.syncMailboxKey = mailboxKey;
let syncSucceeded = false;
const sync = (async () => { const sync = (async () => {
let showingCachedMessages = false; let showingCachedMessages = false;
try { try {
if (isAndroid && mailFeatureState.displayedMailboxKey !== mailboxKey) {
mailFeatureState.displayedMailboxKey = mailboxKey;
mailFeatureState.nextOffset = 0;
mailFeatureState.total = 0;
mailFeatureState.autoLoadBlocked = false;
rendererState.messages.splice(0, rendererState.messages.length);
rendererState.activeMessage = null;
rendererState.selectedIds.clear();
document.body.classList.remove('reader-open');
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
appShell.renderList();
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Loading folder…';
}
if (rendererState.activeFolder === 'Drafts') { if (rendererState.activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts(); const result = await window.daybreakMail.listDrafts();
if (isAndroid && mailFeatureState.syncRequest !== request) return;
renderDrafts(result.drafts || []); renderDrafts(result.drafts || []);
mailFeatureState.autoLoadBlocked = true;
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`); if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
return; return;
} }
const folder = rendererState.activeFolder; const folder = rendererState.activeFolder;
const accountId = mailFeatureState.connectedAccount.id; const accountId = mailFeatureState.connectedAccount.id;
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset); const offset = options.offset ?? (options.append ? mailFeatureState.nextOffset : mailFeatureState.pageOffset);
const filters = mailSearchFilters(); const filters = mailSearchFilters();
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId; const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId &&
(!isAndroid || mailFeatureState.syncRequest === request);
if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) { if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) {
try { try {
const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters); const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters);
if (cached && isCurrentMailbox()) { if (cached && isCurrentMailbox()) {
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages); rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
rendererState.activeMessage = null; rendererState.activeMessage = null;
mailFeatureState.pageOffset = offset;
mailFeatureState.nextOffset = offset + cached.messages.length;
mailFeatureState.total = cached.total;
mailFeatureState.autoLoadBlocked = true;
const pagination = selectMailUi('#pagination');
if (pagination) pagination.textContent = cached.total ? `${cached.start}–${cached.end} of ${cached.total} saved messages` : '0 saved messages';
const loadMore = selectMailUi('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', cached.messages.length >= cached.total);
appShell.renderList(); appShell.renderList();
showingCachedMessages = true; showingCachedMessages = true;
const status = selectMailUi('#mail-status'); const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Showing saved messages — syncing'; if (status) status.textContent = 'Showing saved messages — syncing';
} }
} catch (error) { } catch (error) {
if (isAndroid && mailFeatureState.syncRequest !== request) return;
console.error('Could not load cached messages:', error); console.error('Could not load cached messages:', error);
} }
} }
@@ -691,8 +764,16 @@ async function syncMailbox(showToast, options = {}) {
const result = await window.daybreakMail.syncFolder(folder, offset, filters); const result = await window.daybreakMail.syncFolder(folder, offset, filters);
if (!isCurrentMailbox()) return; if (!isCurrentMailbox()) return;
const previouslyActiveMessage = rendererState.activeMessage; const previouslyActiveMessage = rendererState.activeMessage;
if (options.append) rendererState.messages.push(...result.messages); if (options.append) {
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages); const existing = new Set(rendererState.messages.map(message => JSON.stringify([message.sourceFolder || folder, message.uid || message.id])));
for (const message of result.messages) {
const key = JSON.stringify([message.sourceFolder || folder, message.uid || message.id]);
if (!existing.has(key)) {
rendererState.messages.push(message);
existing.add(key);
}
}
} else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
rendererState.messages.forEach(message => { rendererState.messages.forEach(message => {
try { try {
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]'); const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
@@ -701,6 +782,14 @@ async function syncMailbox(showToast, options = {}) {
}); });
if (!options.append) mailFeatureState.pageOffset = offset; if (!options.append) mailFeatureState.pageOffset = offset;
mailFeatureState.total = result.total; mailFeatureState.total = result.total;
const hasSearch = Boolean(filters.query || filters.sender || filters.subject || filters.after || filters.before || filters.hasAttachments);
const isSequencePage = !result.offline && folder !== 'Snoozed' && !hasSearch;
const consumed = isSequencePage && result.start > 0 && result.end >= result.start
? result.end - result.start + 1
: result.messages.length;
mailFeatureState.nextOffset = offset + consumed;
mailFeatureState.autoLoadBlocked = consumed === 0 || (options.append && result.messages.length === 0);
syncSucceeded = true;
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage) rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage ? previouslyActiveMessage
: window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id; : window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id;
@@ -709,11 +798,14 @@ async function syncMailbox(showToast, options = {}) {
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count'); const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
if (inboxCount) inboxCount.textContent = String(unread); if (inboxCount) inboxCount.textContent = String(unread);
const pagination = selectMailUi('#pagination'); const pagination = selectMailUi('#pagination');
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages'; if (pagination) pagination.textContent = result.total ? `${options.append ? mailFeatureState.pageOffset + 1 : result.start}–${options.append ? Math.min(mailFeatureState.nextOffset, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = selectMailUi('#load-more'); const loadMore = selectMailUi('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.pageOffset + rendererState.messages.length >= result.total); if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.nextOffset >= result.total || consumed === 0);
rendererState.query = ''; rendererState.query = '';
const messageList = selectMailUi('#message-list');
const scrollTop = options.append ? messageList.scrollTop : 0;
appShell.renderList(); appShell.renderList();
if (options.append) messageList.scrollTop = scrollTop;
if (rendererState.activeMessage) { if (rendererState.activeMessage) {
appShell.openMessage(rendererState.activeMessage); appShell.openMessage(rendererState.activeMessage);
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage); const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
@@ -725,16 +817,26 @@ async function syncMailbox(showToast, options = {}) {
} }
updateAccountCard(mailFeatureState.connectedAccount); updateAccountCard(mailFeatureState.connectedAccount);
const status = selectMailUi('#mail-status'); const status = selectMailUi('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail'; if (status) status.textContent = mailFeatureState.browseRefreshPending
? 'Updates paused while browsing — return to the top or refresh'
: result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`); if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
} catch (error) { } catch (error) {
if (isAndroid && mailFeatureState.syncRequest !== request) return;
if (options.append) mailFeatureState.autoLoadBlocked = true;
if (showingCachedMessages) { if (showingCachedMessages) {
const status = selectMailUi('#mail-status'); const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Could not sync — showing saved messages'; if (status) status.textContent = 'Could not sync — showing saved messages';
} else if (options.append) {
const status = selectMailUi('#mail-status');
if (status) status.textContent = 'Could not load more messages — use Load more to retry';
} }
toastMailUi(error.message || 'Could not sync the inbox'); toastMailUi(error.message || 'Could not sync the inbox');
} finally { } finally {
if (!isAndroid || mailFeatureState.syncRequest === request) {
if (refresh) refresh.disabled = false; if (refresh) refresh.disabled = false;
if (loadMoreButton) loadMoreButton.disabled = false;
}
} }
})(); })();
@@ -742,14 +844,68 @@ async function syncMailbox(showToast, options = {}) {
try { try {
await sync; await sync;
} finally { } finally {
if (mailFeatureState.syncPromise !== sync) return;
mailFeatureState.syncPromise = null; mailFeatureState.syncPromise = null;
mailFeatureState.syncMailboxKey = null;
if (mailFeatureState.syncQueued) { if (mailFeatureState.syncQueued) {
mailFeatureState.syncQueued = false; mailFeatureState.syncQueued = false;
void syncMailbox(false); void syncMailbox(false);
} else if (runDeferredMailboxRefresh()) {
return;
} else if (syncSucceeded) {
maybeLoadMoreMessages();
} }
} }
} }
function shouldDeferMailboxRefresh() {
if (window.daybreakMail?.platform !== 'android') return false;
const list = selectMailUi('#message-list');
return Boolean(list && (list.scrollTop > 120 ||
(document.body.classList.contains('reader-open') &&
(appShell.getReaderListPosition() > 120 ||
mailFeatureState.nextOffset > mailFeatureState.pageOffset + 20))));
}
function requestBackgroundMailboxRefresh(options = {}) {
if (shouldDeferMailboxRefresh()) {
mailFeatureState.browseRefreshPending = true;
if (options.offset === 0) mailFeatureState.browseRefreshFromStart = true;
const status = selectMailUi('#mail-status');
if (status && !mailFeatureState.syncPromise) {
status.textContent = 'Updates paused while browsing — return to the top or refresh';
}
return;
}
void syncMailbox(false, options);
}
function runDeferredMailboxRefresh() {
if (!mailFeatureState.browseRefreshPending || mailFeatureState.syncPromise ||
document.visibilityState !== 'visible' || rendererState.activeView !== 'mail' ||
shouldDeferMailboxRefresh()) return false;
const options = mailFeatureState.browseRefreshFromStart ? { offset: 0 } : {};
mailFeatureState.browseRefreshPending = false;
mailFeatureState.browseRefreshFromStart = false;
void syncMailbox(false, options);
return true;
}
function handleMessageListScroll() {
if (!runDeferredMailboxRefresh()) maybeLoadMoreMessages();
}
function maybeLoadMoreMessages() {
const list = selectMailUi('#message-list');
if (!list || !mailFeatureState.connectedAccount || mailFeatureState.syncPromise ||
mailFeatureState.autoLoadBlocked || rendererState.activeFolder === 'Drafts' ||
mailFeatureState.nextOffset >= mailFeatureState.total || !list.clientHeight ||
document.body.classList.contains('reader-open') ||
rendererState.activeView !== 'mail') return;
if (list.scrollHeight - list.scrollTop - list.clientHeight > 120) return;
void syncMailbox(false, { append: true });
}
if (window.daybreakMail) { if (window.daybreakMail) {
setupDraftComposer(); setupDraftComposer();
let searchTimer; let searchTimer;
@@ -806,7 +962,7 @@ if (window.daybreakMail) {
} }
if (update.newCount || (update.foldersChanged || []).length) { if (update.newCount || (update.foldersChanged || []).length) {
if (document.visibilityState === 'visible') { if (document.visibilityState === 'visible') {
syncMailbox(false, update.newCount ? { offset: 0 } : {}); requestBackgroundMailboxRefresh(update.newCount ? { offset: 0 } : {});
} }
else mailFeatureState.refreshPending = true; else mailFeatureState.refreshPending = true;
} }
@@ -814,18 +970,20 @@ if (window.daybreakMail) {
document.addEventListener('visibilitychange', () => { document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) { if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) {
mailFeatureState.refreshPending = false; mailFeatureState.refreshPending = false;
syncMailbox(false, { offset: 0 }); requestBackgroundMailboxRefresh({ offset: 0 });
} else if (document.visibilityState === 'visible') {
runDeferredMailboxRefresh();
} }
}); });
window.addEventListener('focus', () => { window.addEventListener('focus', () => {
if (mailFeatureState.connectedAccount) syncMailbox(false); if (mailFeatureState.connectedAccount) requestBackgroundMailboxRefresh();
}); });
window.addEventListener('online', () => { window.addEventListener('online', () => {
if (mailFeatureState.connectedAccount) syncMailbox(false, { offset: 0 }); if (mailFeatureState.connectedAccount) requestBackgroundMailboxRefresh({ offset: 0 });
}); });
setInterval(() => { setInterval(() => {
if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') { if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') {
syncMailbox(false); requestBackgroundMailboxRefresh();
} }
}, 60 * 1000); }, 60 * 1000);
selectMailUi('#account-settings').addEventListener('click', openMailAccount); selectMailUi('#account-settings').addEventListener('click', openMailAccount);
@@ -854,7 +1012,13 @@ if (window.daybreakMail) {
mailFeatureState.pageOffset += 20; mailFeatureState.pageOffset += 20;
syncMailbox(false, { offset: mailFeatureState.pageOffset }); syncMailbox(false, { offset: mailFeatureState.pageOffset });
}; };
selectMailUi('#load-more').onclick = () => syncMailbox(false, { append: true }); selectMailUi('#load-more').onclick = () => {
if (!mailFeatureState.syncPromise) void syncMailbox(false, { append: true });
};
selectMailUi('#message-list').addEventListener('scroll', handleMessageListScroll, { passive: true });
document.addEventListener('click', event => {
if (event.target.closest('#reader-back')) runDeferredMailboxRefresh();
});
document.addEventListener('click', async event => { document.addEventListener('click', async event => {
const sendButton = event.target.closest('#send'); const sendButton = event.target.closest('#send');
if (!sendButton || !mailFeatureState.connectedAccount) return; if (!sendButton || !mailFeatureState.connectedAccount) return;
+5 -9
View File
@@ -19,9 +19,7 @@ function openEncryptionKeys() {
const root = selectPgpKeyUi('#modal-root'); const root = selectPgpKeyUi('#modal-root');
const account = window.epMailFeatures.mail.connectedAccount || {}; const account = window.epMailFeatures.mail.connectedAccount || {};
const androidPgp = window.daybreakMail?.pgp?.platform === 'android'; const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
const serverSettings = androidPgp const serverSettings = `<h3 class="pgp-heading">Public key servers</h3>
? '<h3 class="pgp-heading">Public key servers</h3><p class="account-note">Key-server lookup and publication are disabled in Android testing. Import a public key directly and compare its fingerprint with the owner.</p><div hidden><div id="pgp-server-list"></div><input id="pgp-search-email"><button id="pgp-find-key"></button><div id="pgp-found-keys"></div><select id="pgp-publish-server"></select><input id="pgp-server-name"><input id="pgp-server-url"><select id="pgp-server-protocol"></select><button id="pgp-add-server"></button></div>'
: `<h3 class="pgp-heading">Public key servers</h3>
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p> <p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div> <div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label> <label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
@@ -359,7 +357,6 @@ function openEncryptionKeys() {
}; };
enabledLabel.append(enabledText, enabled); enabledLabel.append(enabledText, enabled);
row.append(info, enabledLabel); row.append(info, enabledLabel);
if (!server.builtin) {
const remove = document.createElement('button'); const remove = document.createElement('button');
remove.className = 'discard'; remove.className = 'discard';
remove.textContent = 'Remove'; remove.textContent = 'Remove';
@@ -367,11 +364,10 @@ function openEncryptionKeys() {
try { try {
await window.daybreakMail.pgp.removeKeyServer(server.id); await window.daybreakMail.pgp.removeKeyServer(server.id);
await renderKeyServers(); await renderKeyServers();
status('Custom key server removed.'); status(`${server.name} removed.`);
} catch (error) { status(error.message || 'Could not remove the key server.'); } } catch (error) { status(error.message || 'Could not remove the key server.'); }
}; };
row.append(remove); row.append(remove);
}
list.append(row); list.append(row);
}); });
} }
@@ -451,13 +447,13 @@ function openEncryptionKeys() {
catch (error) { status(error.message || 'Could not save the setting.'); } catch (error) { status(error.message || 'Could not save the setting.'); }
}; };
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); }; selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
if (!androidPgp) void renderKeyServers(); void renderKeyServers();
void renderContacts(); void renderContacts();
void render(); void render();
} }
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () { window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => async function () {
baseOpenPreferences(); await baseOpenPreferences();
const fields = selectPgpKeyUi('#modal-root .compose-fields'); const fields = selectPgpKeyUi('#modal-root .compose-fields');
if (!fields || !pgpAvailable()) return; if (!fields || !pgpAvailable()) return;
const button = document.createElement('button'); const button = document.createElement('button');
+5564 -4942
View File
File diff suppressed because one or more lines are too long
+25 -2
View File
@@ -1,5 +1,28 @@
const CACHE='ep-mail-v19'; const CACHE='ep-mail-v22';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting()))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim()))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); self.addEventListener('fetch', event => {
const request = event.request;
if (request.method !== 'GET' || new URL(request.url).origin !== location.origin) return;
event.respondWith((async () => {
let response;
try {
response = await fetch(request, { cache: 'no-cache' });
} catch (error) {
const cached = await caches.match(request) ||
(request.mode === 'navigate' ? await caches.match('./index.html') : null);
if (cached) return cached;
throw error;
}
if (response.ok) {
try {
const cache = await caches.open(CACHE);
await cache.put(request, response.clone());
} catch (error) {
console.error('Could not update offline app cache:', error);
}
}
return response;
})());
});
+2 -2
View File
@@ -65,8 +65,8 @@ document.addEventListener('keydown', event => {
action.run(); action.run();
}); });
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () { shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => async function () {
baseOpenPreferences(); await baseOpenPreferences();
const fields = selectShortcutUi('#modal-root .compose-fields'); const fields = selectShortcutUi('#modal-root .compose-fields');
const save = selectShortcutUi('#save-appearance'); const save = selectShortcutUi('#save-appearance');
if (!fields || !save) return; if (!fields || !save) return;
+5 -3
View File
@@ -114,7 +114,7 @@ body.ep-daylight .compose-line input::placeholder,body.ep-daylight .compose-body
body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b} body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b}
body.ep-daylight .toast{background:#11212b;color:#f1f1e9} body.ep-daylight .toast{background:#11212b;color:#f1f1e9}
body.ep-daylight .row-check:checked{accent-color:#526a2c} body.ep-daylight .row-check:checked{accent-color:#526a2c}
.compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-fields{min-height:0;flex:1 1 auto;overflow-y:auto} .compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-modal>.modal-head,.compose-modal>.compose-footer{flex:none}.compose-fields{min-height:0;flex:0 1 auto;overflow-y:auto}.compose-modal>.compose-body{flex:1 1 120px;min-height:90px;height:auto}
.snooze-options .outline-button{width:100%;text-align:left} .snooze-options .outline-button{width:100%;text-align:left}
.mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap} .mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap}
@media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}} @media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}}
@@ -199,8 +199,10 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.compose-line input[type=checkbox]{flex:0 0 auto;width:20px;height:20px} .compose-line input[type=checkbox]{flex:0 0 auto;width:20px;height:20px}
.compose-line span{flex:0 1 54%;line-height:1.25} .compose-line span{flex:0 1 54%;line-height:1.25}
.compose-line input:not([type=checkbox]){flex:1;max-width:100%;min-width:0} .compose-line input:not([type=checkbox]){flex:1;max-width:100%;min-width:0}
.compose-footer{gap:8px;padding:10px 12px} .compose-footer{gap:8px;padding:10px 12px;flex-wrap:wrap;justify-content:flex-end}
.compose-body{height:30vh;padding:12px} .compose-footer .pgp-compose{flex:1 0 100%;flex-wrap:wrap;margin-right:0;gap:4px 12px}
.compose-footer .send-button{order:99;padding:10px 18px;font-size:12px}
.compose-body{padding:12px}
.account-note,.account-status{font-size:12px} .account-note,.account-status{font-size:12px}
.mail-rule-row{grid-template-columns:1fr;gap:6px} .mail-rule-row{grid-template-columns:1fr;gap:6px}
.mail-rule-row>*{grid-column:1} .mail-rule-row>*{grid-column:1}