Compare commits

..
12 Commits
Author SHA1 Message Date
thuttuandCopilot 63ee146719 Add configurable keyboard shortcuts
Bump version to 0.2.1

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 10:06:19 +03:00
thuttuandCopilot 43be32b162 Add creating IMAP folders from the app
Bump version to 0.2.0

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 10:03:15 +03:00
thuttuandCopilot 47ec7bdb80 Warn about suspicious mail senders and links
Bump version to 0.1.21

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 01:53:01 +03:00
thuttuandCopilot cae6825f2c Add advanced search and offline mail support
Bump version to 0.1.20

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 01:41:07 +03:00
thuttuandCopilot 9b3a890b1d Add per-account mail rules and settings
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 01:24:01 +03:00
thuttu a1b8bca066 Add Snooze messages until a chosen time and show a follow-up reminder when they return. Bump version V0.1.17 2026-10-07 00:55:14 +03:00
thuttu 520056d27c Ver V0.1.16 Add Android version to project 2026-10-07 00:26:54 +03:00
thuttuandCopilot 7135cbb629 Add persistent IMAP IDLE watchers
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 00:00:30 +03:00
thuttuandCopilot e999497e5f Move DAV server setup into Account Settings
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-06 23:58:59 +03:00
thuttu 51f5113aff Ver V0.1.15 Remove initials icon from bottom left corner FIX Diplay name is supported per account 2026-10-06 23:49:52 +03:00
thuttu 2becdcccd7 Ver V0.1.14 Add automatic ui refresh 2026-10-06 23:40:11 +03:00
thuttu e50073ab4c Ver V0.1.13 Add Automatic mailbox sync 2026-10-06 23:29:18 +03:00
95 changed files with 9146 additions and 148 deletions
+15 -4
View File
@@ -1,12 +1,23 @@
# ep-mail # ep-mail
An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, archive and trash actions, compose/reply/forward, contacts, and a month calendar. An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, snooze reminders, archive and trash actions, compose/reply/forward, contacts, and a month calendar.
## Desktop app ## Desktop app
The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. The app uses required STARTTLS for IMAP port 143 and SMTP port 587 and stores the password encrypted through the operating system credential store. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`. The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser; the app never renders remote message HTML. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
## Android app
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
```sh
npm install
npm run android:apk
```
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk`. Install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`, or open the project in Android Studio with `npm run android:open`. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
## Run on Windows or Linux ## Run on Windows or Linux
@@ -20,4 +31,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
## Current scope ## Current scope
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**.
+31 -3
View File
@@ -4,6 +4,24 @@
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation. - [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants. - [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
- [x] Add Android support for the mail app.
- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
- [x] Show the app version after **ep-mail** in the window title.
## Mail workflow
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
- [ ] Add Undo Send and scheduled sending.
- [x] Improve mail search with sender, subject, date, folder, and attachment filters.
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
- [ ] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
- [x] Add per-account signatures, notification preferences, and sync settings.
- [x] Add the ability to create IMAP folders from the app.
- [ ] Block remote images by default and let users load them per message.
## Mail security ## Mail security
@@ -11,14 +29,24 @@
## Appearance and settings ## Appearance and settings
- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears.
- [x] Make **EP Wasteland** the default theme for new users. - [x] Make **EP Wasteland** the default theme for new users.
- [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts. - [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts.
- [x] Keep the display name in Account Settings and make it available while adding a mailbox. - [x] Keep the display name in Account Settings and make it available while adding a mailbox.
## Account settings ## Account settings
- [ ] Fix the mailbox space indicator; it is not working.
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
- [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
- [ ] Add push mail support.
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
- [x] Add new mail notifications.
- [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup. - [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup.
- [ ] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views. - [x] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name. - [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
- [ ] Display name must be set per account. - [x] Display name must be set per account.
- [ ] Remove the display name initials from the bottom-left corner. - [x] Remove the display name initials from the bottom-left corner.
+4 -2
View File
@@ -3,8 +3,8 @@ async function openAccountManager(){
try{ try{
const data=await window.daybreakMail.listAccounts(); const data=await window.daybreakMail.listAccounts();
const accounts=data.accounts||[]; const accounts=data.accounts||[];
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.email)}</strong><small>${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join(''); const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.displayName||account.email)}</strong><small>${esc(account.email)} · ${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Mail accounts</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`; root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
const close=()=>root.innerHTML=''; const close=()=>root.innerHTML='';
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close); root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
@@ -12,6 +12,8 @@ async function openAccountManager(){
root.onclick=async event=>{ root.onclick=async event=>{
const switchButton=event.target.closest('[data-switch-account]'); const switchButton=event.target.closest('[data-switch-account]');
if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return} if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
const davButton=event.target.closest('[data-open-dav]');
if(davButton){close();openDavManager(davButton.dataset.openDav);return}
const editButton=event.target.closest('[data-edit-account]'); const editButton=event.target.closest('[data-edit-account]');
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)openMailAccount(account);return} if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)openMailAccount(account);return}
const removeButton=event.target.closest('[data-remove-account]'); const removeButton=event.target.closest('[data-remove-account]');
+101
View File
@@ -0,0 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+78
View File
@@ -0,0 +1,78 @@
apply plugin: 'com.android.application'
apply plugin: 'org.jetbrains.kotlin.android'
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
android {
namespace = "studio.daybreak.mail"
compileSdk = rootProject.ext.compileSdkVersion
buildFeatures {
buildConfig true
}
packaging {
resources {
pickFirsts += "META-INF/NOTICE.md"
pickFirsts += "META-INF/LICENSE.md"
}
}
defaultConfig {
applicationId "studio.daybreak.mail"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode appVersionParts[0] * 10000 + appVersionParts[1] * 100 + appVersionParts[2]
versionName appVersion
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
kotlinOptions {
jvmTarget = '21'
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
implementation 'com.sun.mail:android-mail:1.6.7'
implementation 'com.sun.mail:android-activation:1.6.7'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'androidx.work:work-runtime-ktx:2.10.1'
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
+19
View File
@@ -0,0 +1,19 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,26 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MailIdleService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application>
</manifest>
@@ -0,0 +1,540 @@
package studio.daybreak.mail
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import org.json.JSONArray
import org.json.JSONObject
import java.security.KeyStore
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
internal object AndroidAccountVault {
private const val KEY_ALIAS = "ep-mail-account-key"
private const val PREFS_NAME = "ep-mail-secure-store"
private const val ENCRYPTED_VALUE = "encrypted-data"
private const val GCM_TAG_BITS = 128
@Volatile private var appContext: Context? = null
fun initialize(context: Context) {
appContext = context.applicationContext
secretKey()
}
@Synchronized
fun read(): JSONObject {
val context = requireContext()
val encoded = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.getString(ENCRYPTED_VALUE, null) ?: return emptyStore()
val payload = Base64.decode(encoded, Base64.NO_WRAP)
require(payload.size > 12) { "Encrypted account data is invalid." }
val iv = payload.copyOfRange(0, 12)
val encrypted = payload.copyOfRange(12, payload.size)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
return JSONObject(String(cipher.doFinal(encrypted), Charsets.UTF_8))
}
@Synchronized
fun write(store: JSONObject) {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, secretKey())
val encrypted = cipher.doFinal(store.toString().toByteArray(Charsets.UTF_8))
val payload = cipher.iv + encrypted
val saved = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.edit()
.putString(ENCRYPTED_VALUE, Base64.encodeToString(payload, Base64.NO_WRAP))
.commit()
check(saved) { "Could not save encrypted account data." }
}
fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray()
fun account(id: String? = null): JSONObject? {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return null
val selectedId = id ?: store.optString("activeId")
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") == selectedId) return account
}
return null
}
@Synchronized
fun saveAccount(account: JSONObject): JSONObject {
val store = read()
val accounts = store.optJSONArray("accounts") ?: JSONArray()
val updated = JSONArray()
var saved: JSONObject? = null
for (index in 0 until accounts.length()) {
val previous = accounts.getJSONObject(index)
val same = previous.optString("email").equals(account.optString("email"), true) &&
previous.optString("imapHost").equals(account.optString("imapHost"), true)
if (same || previous.optString("id") == account.optString("id")) {
val merged = JSONObject(previous.toString())
val keys = account.keys()
while (keys.hasNext()) {
val key = keys.next()
merged.put(key, account.get(key))
}
saved = merged
updated.put(merged)
} else {
updated.put(previous)
}
}
if (saved == null) {
saved = JSONObject(account.toString())
updated.put(saved)
}
store.put("accounts", updated)
store.put("activeId", saved.optString("id"))
write(store)
return saved
}
@Synchronized
fun removeAccount(id: String?): JSONObject {
val store = read()
val accounts = store.optJSONArray("accounts") ?: JSONArray()
val kept = JSONArray()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) kept.put(account)
}
val activeId = if (store.optString("activeId") == id) {
kept.optJSONObject(0)?.optString("id") ?: ""
} else store.optString("activeId")
store.put("accounts", kept)
store.put("activeId", activeId)
write(store)
return JSONObject().put("accounts", publicAccounts(kept)).put("activeId", activeId)
}
@Synchronized
fun updateInboxCursor(id: String, uidValidity: Long, lastUid: Long) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") == id) {
account.put("androidInboxSyncState", JSONObject()
.put("uidValidity", uidValidity)
.put("lastUid", lastUid))
write(store)
return
}
}
}
@Synchronized
fun setSnooze(id: String, uid: Long, folder: String, dueAt: Long?, subject: String) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val previous = account.optJSONArray("snoozedMessages") ?: JSONArray()
val updated = JSONArray()
for (itemIndex in 0 until previous.length()) {
val item = previous.getJSONObject(itemIndex)
if (item.optLong("uid") != uid || item.optString("folder") != folder) updated.put(item)
}
if (dueAt != null) {
updated.put(JSONObject()
.put("uid", uid)
.put("folder", folder)
.put("dueAt", dueAt)
.put("subject", subject.take(200)))
}
account.put("snoozedMessages", updated)
write(store)
return
}
}
@Synchronized
fun takeDueSnoozes(id: String, now: Long): JSONArray {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return JSONArray()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val previous = account.optJSONArray("snoozedMessages") ?: JSONArray()
val remaining = JSONArray()
val due = JSONArray()
for (itemIndex in 0 until previous.length()) {
val item = previous.getJSONObject(itemIndex)
if (item.optLong("dueAt") <= now) {
due.put(JSONObject(item.toString())
.put("accountId", id)
.put("email", account.optString("email")))
} else {
remaining.put(item)
}
}
if (due.length() > 0) {
account.put("snoozedMessages", remaining)
write(store)
}
return due
}
return JSONArray()
}
@Synchronized
fun addRuleLabel(id: String, folder: String, uid: Long, label: String) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val labels = account.optJSONObject("ruleLabels") ?: JSONObject()
val key = "$folder:$uid"
val values = labels.optJSONArray(key) ?: JSONArray()
if ((0 until values.length()).none { values.optString(it) == label }) values.put(label)
labels.put(key, values)
account.put("ruleLabels", labels)
write(store)
return
}
}
@Synchronized
fun cacheMessages(id: String, folder: String, messages: JSONArray) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val cache = account.optJSONObject("mailCache") ?: JSONObject()
val previous = cache.optJSONArray(folder) ?: JSONArray()
val merged = LinkedHashMap<String, JSONObject>()
for (itemIndex in 0 until previous.length()) {
val item = previous.optJSONObject(itemIndex) ?: continue
merged[item.optString("uid", item.optString("id"))] = item
}
for (itemIndex in 0 until messages.length()) {
val item = messages.optJSONObject(itemIndex) ?: continue
merged[item.optString("uid", item.optString("id"))] = item
}
cache.put(folder, JSONArray().apply {
merged.values.toList().takeLast(30).forEach { put(it) }
})
account.put("mailCache", cache)
write(store)
return
}
}
fun cachedFolder(id: String, folder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject? {
val account = account(id) ?: return null
val cached = account.optJSONObject("mailCache")?.optJSONArray(folder) ?: return null
val matched = (0 until cached.length()).mapNotNull { cached.optJSONObject(it) }
.filter { matchesFilters(it, filters) }
.sortedByDescending { it.optLong("timestamp") }
val start = offset.coerceAtLeast(0)
val page = matched.drop(start).take(20)
if (page.isEmpty() && matched.isEmpty()) return null
return JSONObject()
.put("messages", JSONArray().apply { page.forEach(::put) })
.put("total", matched.size)
.put("start", if (matched.isEmpty()) 0 else start + 1)
.put("end", start + page.size)
.put("folder", folder)
.put("offline", true)
}
private fun matchesFilters(message: JSONObject, filters: JSONObject): Boolean {
val query = filters.optString("query").trim().lowercase(Locale.ROOT)
val senderFilter = filters.optString("sender").trim().lowercase(Locale.ROOT)
val subjectFilter = filters.optString("subject").trim().lowercase(Locale.ROOT)
val sender = "${message.optString("sender")} ${message.optString("email")}".lowercase(Locale.ROOT)
val subject = message.optString("subject").lowercase(Locale.ROOT)
val attachments = message.optJSONArray("attachments")
val haystack = "$sender $subject ${message.optString("snippet")} ${message.optJSONArray("body")?.toString().orEmpty()}".lowercase(Locale.ROOT)
val timestamp = message.optLong("timestamp")
val after = dateBoundary(filters.optString("after"), false)
val before = dateBoundary(filters.optString("before"), true)
return (query.isBlank() || query.split(Regex("\\s+")).all(haystack::contains)) &&
(senderFilter.isBlank() || sender.contains(senderFilter)) &&
(subjectFilter.isBlank() || subject.contains(subjectFilter)) &&
(after == null || timestamp >= after) && (before == null || timestamp <= before) &&
(!filters.optBoolean("hasAttachments") || (attachments?.length() ?: 0) > 0)
}
private fun dateBoundary(value: String, endOfDay: Boolean): Long? {
if (value.isBlank()) return null
val parsed = runCatching { SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(value) }.getOrNull() ?: return null
val calendar = Calendar.getInstance().apply { time = parsed }
if (endOfDay) {
calendar.add(Calendar.DAY_OF_MONTH, 1)
return calendar.timeInMillis - 1
}
return calendar.timeInMillis
}
@Synchronized
fun saveDraft(id: String, draft: JSONObject) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val drafts = account.optJSONArray("drafts") ?: JSONArray()
val updated = JSONArray().put(JSONObject(draft.toString()))
for (draftIndex in 0 until drafts.length()) {
val current = drafts.optJSONObject(draftIndex) ?: continue
if (current.optString("id") != draft.optString("id")) updated.put(current)
}
account.put("drafts", updated)
write(store)
return
}
}
@Synchronized
fun deleteDraft(id: String, draftId: String) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val drafts = account.optJSONArray("drafts") ?: JSONArray()
account.put("drafts", JSONArray().apply {
for (draftIndex in 0 until drafts.length()) {
val draft = drafts.optJSONObject(draftIndex) ?: continue
if (draft.optString("id") != draftId) put(draft)
}
})
write(store)
return
}
}
@Synchronized
fun enqueueMailOperation(id: String, operation: JSONObject) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val previous = account.optJSONArray("mailOutbox") ?: JSONArray()
val data = operation.optJSONObject("data")
val queue = JSONArray()
for (index in 0 until previous.length()) {
val existing = previous.optJSONObject(index) ?: continue
val existingData = existing.optJSONObject("data")
if (existingData == null) {
queue.put(existing)
continue
}
val duplicate = operation.optString("type") == "action" && existing.optString("type") == "action" &&
existingData.optLong("uid") == data?.optLong("uid") &&
existingData.optString("folder") == data?.optString("folder") &&
existingData.optString("action") == data?.optString("action")
if (!duplicate) queue.put(existing)
}
queue.put(JSONObject(operation.toString()))
account.put("mailOutbox", queue)
if (operation.optString("type") == "action" && data != null) applyQueuedActionToCache(account, data)
write(store)
return
}
}
private fun applyQueuedActionToCache(account: JSONObject, input: JSONObject) {
val cache = account.optJSONObject("mailCache") ?: return
val sourceName = input.optString("folder", "Inbox")
val source = cache.optJSONArray(sourceName) ?: return
val uid = input.optLong("uid")
val action = input.optString("action")
val updatedSource = JSONArray()
var moved: JSONObject? = null
for (index in 0 until source.length()) {
val message = source.optJSONObject(index) ?: continue
if (message.optLong("uid", message.optLong("id")) != uid) {
updatedSource.put(message)
continue
}
when (action) {
"star" -> {
message.put("star", input.optBoolean("enabled"))
updatedSource.put(message)
}
"unread" -> {
message.put("unread", input.optBoolean("enabled"))
updatedSource.put(message)
}
"archive", "delete", "inbox" -> moved = message
else -> updatedSource.put(message)
}
}
cache.put(sourceName, updatedSource)
val destinationName = when (action) {
"archive" -> "Archive"
"delete" -> "Trash"
"inbox" -> "Inbox"
else -> null
}
if (moved == null || destinationName == null) return
moved!!.put("sourceFolder", destinationName)
.put("archived", destinationName == "Archive")
.put("deleted", destinationName == "Trash")
val destination = cache.optJSONArray(destinationName) ?: JSONArray()
val merged = (0 until destination.length()).mapNotNull { destination.optJSONObject(it) }
.filter { it.optLong("uid", it.optLong("id")) != uid } + moved!!
cache.put(destinationName, JSONArray().apply { merged.takeLast(30).forEach { put(it) } })
}
@Synchronized
fun pendingMailOperations(id: String): JSONArray = account(id)?.optJSONArray("mailOutbox") ?: JSONArray()
@Synchronized
fun removeMailOperation(id: String, operationId: String) {
val store = read()
val accounts = store.optJSONArray("accounts") ?: return
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) continue
val queue = account.optJSONArray("mailOutbox") ?: JSONArray()
account.put("mailOutbox", JSONArray().apply {
for (queueIndex in 0 until queue.length()) {
val operation = queue.optJSONObject(queueIndex) ?: continue
if (operation.optString("id") != operationId) put(operation)
}
})
write(store)
return
}
}
fun publicAccounts(accounts: JSONArray = this.accounts()): JSONArray {
val result = JSONArray()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
result.put(publicAccount(account))
}
return result
}
fun publicAccount(account: JSONObject): JSONObject = JSONObject()
.put("id", account.optString("id"))
.put("email", account.optString("email"))
.put("displayName", account.optString("displayName"))
.put("imapHost", account.optString("imapHost"))
.put("smtpHost", account.optString("smtpHost"))
.put("signature", account.optString("signature"))
.put("notificationsEnabled", account.optBoolean("notificationsEnabled", true))
.put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2))
.put("rules", account.optJSONArray("rules") ?: JSONArray())
fun storeDav(type: String): JSONArray = read().optJSONArray(type) ?: JSONArray()
fun putDavAccount(type: String, account: JSONObject): JSONObject {
val store = read()
val accounts = store.optJSONArray(type) ?: JSONArray()
val updated = JSONArray()
var saved: JSONObject? = null
for (index in 0 until accounts.length()) {
val previous = accounts.getJSONObject(index)
if (previous.optString("serverUrl") == account.optString("serverUrl") &&
previous.optString("username").equals(account.optString("username"), true)) {
val merged = JSONObject(account.toString()).put("id", previous.optString("id"))
updated.put(merged)
saved = merged
} else {
updated.put(previous)
}
}
if (saved == null) {
saved = JSONObject(account.toString())
updated.put(saved)
}
store.put(type, updated)
store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", saved.optString("id"))
write(store)
return saved
}
fun activeDav(type: String, id: String? = null): JSONObject? {
val store = read()
val accounts = store.optJSONArray(type) ?: return null
val selectedId = id ?: store.optString(if (type == "caldav") "activeCaldavId" else "activeCarddavId")
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") == selectedId) return account
}
return null
}
fun publicDavAccounts(type: String): JSONArray {
val result = JSONArray()
val accounts = storeDav(type)
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
result.put(JSONObject()
.put("id", account.optString("id"))
.put("serverUrl", account.optString("serverUrl"))
.put("username", account.optString("username"))
.put("collections", account.optJSONArray("collections") ?: JSONArray()))
}
return result
}
fun removeDavAccount(type: String, id: String): JSONObject {
val store = read()
val accounts = store.optJSONArray(type) ?: JSONArray()
val remaining = JSONArray()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
if (account.optString("id") != id) remaining.put(account)
}
val activeKey = if (type == "caldav") "activeCaldavId" else "activeCarddavId"
val activeId = if (store.optString(activeKey) == id) {
remaining.optJSONObject(0)?.optString("id") ?: ""
} else store.optString(activeKey)
store.put(type, remaining)
store.put(activeKey, activeId)
write(store)
return JSONObject().put("accounts", publicDavAccounts(type)).put("activeId", activeId)
}
private fun emptyStore() = JSONObject()
.put("accounts", JSONArray())
.put("activeId", "")
.put("caldav", JSONArray())
.put("carddav", JSONArray())
.put("activeCaldavId", "")
.put("activeCarddavId", "")
private fun requireContext(): Context =
appContext ?: throw IllegalStateException("Encrypted account storage is not initialized.")
@Synchronized
private fun secretKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init(
KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.setRandomizedEncryptionRequired(true)
.build()
)
return generator.generateKey()
}
}
@@ -0,0 +1,443 @@
package studio.daybreak.mail
import android.util.Base64
import org.json.JSONArray
import org.json.JSONObject
import org.w3c.dom.Element
import java.io.ByteArrayInputStream
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.Locale
import java.util.UUID
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit
import javax.xml.parsers.DocumentBuilderFactory
internal object AndroidDavService {
private val httpClient = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
fun list(): JSONObject {
val store = AndroidAccountVault.read()
return JSONObject()
.put("caldav", AndroidAccountVault.publicDavAccounts("caldav"))
.put("carddav", AndroidAccountVault.publicDavAccounts("carddav"))
.put("activeCaldavId", store.optString("activeCaldavId"))
.put("activeCarddavId", store.optString("activeCarddavId"))
}
fun connect(input: JSONObject): JSONObject {
val type = type(input.optString("type"))
val serverUrl = input.optString("serverUrl").trim()
val username = input.optString("username").trim()
val password = input.optString("password")
val url = try { URL(serverUrl) } catch (_: Exception) {
throw IllegalArgumentException("Enter a valid CalDAV or CardDAV server URL.")
}
require(url.protocol == "https" || (url.protocol == "http" && url.host in setOf("localhost", "127.0.0.1", "::1"))) {
"DAV server URLs must use HTTPS."
}
require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." }
val collections = discoverCollections(url.toString(), username, password, type)
require(collections.length() > 0) {
"No ${if (type == "caldav") "calendars" else "address books"} were found on this server."
}
val account = JSONObject()
.put("id", UUID.randomUUID().toString())
.put("type", type)
.put("serverUrl", url.toString())
.put("username", username)
.put("password", password)
.put("collections", collections)
val saved = AndroidAccountVault.putDavAccount(type, account)
val publicConfig = publicDav(saved)
return JSONObject()
.put("config", publicConfig)
.put("collections", collections)
.put("accounts", list())
}
fun activate(typeInput: String, id: String): JSONObject {
val type = type(typeInput)
val config = AndroidAccountVault.activeDav(type, id)
?: throw IllegalStateException("That DAV account could not be found.")
val store = AndroidAccountVault.read()
store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", config.optString("id"))
AndroidAccountVault.write(store)
return JSONObject().put("id", config.optString("id"))
}
fun remove(typeInput: String, id: String): JSONObject =
AndroidAccountVault.removeDavAccount(type(typeInput), id)
fun sync(typeInput: String): JSONObject {
val type = type(typeInput)
val account = AndroidAccountVault.activeDav(type)
?: throw IllegalStateException("Connect a ${if (type == "caldav") "CalDAV" else "CardDAV"} server first.")
val collectionKey = if (type == "caldav") "calendar" else "addressbook"
val result = JSONArray()
val collections = account.optJSONArray("collections") ?: JSONArray()
for (index in 0 until collections.length()) {
val collection = collections.getJSONObject(index)
val objects = listObjects(account, collection, type)
for (obj in objects) {
val href = obj.optString("href")
val data = obj.optString("data")
if (data.isBlank()) continue
if (type == "caldav") parseCalendar(data, account, collection, obj).forEach(result::put)
else parseContacts(data, account, collection, obj).forEach(result::put)
}
}
return JSONObject().put("items", result).put("account", publicDav(account))
.put("collectionType", collectionKey)
}
fun saveEvent(input: JSONObject): JSONObject? {
val remote = input.optJSONObject("_dav") ?: JSONObject()
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId").ifBlank { null }) ?: return null
val collections = account.optJSONArray("collections") ?: JSONArray()
val collection = findCollection(collections, remote.optString("collectionUrl"))
?: throw IllegalStateException("No writable calendar was found.")
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
val filename = "$uid.ics"
val collectionUrl = collection.optString("url")
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
val data = calendarData(input, uid)
val response = request(account, target, "PUT", data, mapOf("Content-Type" to "text/calendar; charset=utf-8"))
require(response.code in 200..299) { "The calendar server rejected the event (${response.code})." }
return JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collectionUrl)
.put("objectUrl", target)
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
.put("uid", uid)
}
fun deleteEvent(remote: JSONObject) {
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId"))
?: throw IllegalStateException("That calendar account could not be found.")
val url = remote.optString("objectUrl")
if (url.isBlank()) return
val response = request(account, url, "DELETE", null)
require(response.code in 200..299 || response.code == 404) { "The calendar server rejected the deletion (${response.code})." }
}
fun saveContact(input: JSONObject): JSONObject? {
val remote = input.optJSONObject("_dav") ?: JSONObject()
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId").ifBlank { null }) ?: return null
val collections = account.optJSONArray("collections") ?: JSONArray()
val collection = findCollection(collections, remote.optString("collectionUrl"))
?: throw IllegalStateException("No writable address book was found.")
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
val filename = "$uid.vcf"
val collectionUrl = collection.optString("url")
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
val response = request(account, target, "PUT", vcardData(input, uid), mapOf("Content-Type" to "text/vcard; charset=utf-8"))
require(response.code in 200..299) { "The address book server rejected the contact (${response.code})." }
return JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collectionUrl)
.put("objectUrl", target)
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
.put("uid", uid)
}
fun deleteContact(remote: JSONObject) {
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId"))
?: throw IllegalStateException("That address book account could not be found.")
val url = remote.optString("objectUrl")
if (url.isBlank()) return
val response = request(account, url, "DELETE", null)
require(response.code in 200..299 || response.code == 404) { "The address book server rejected the deletion (${response.code})." }
}
private data class HttpResult(val code: Int, val body: ByteArray, val headers: Map<String, String>)
private fun request(
account: JSONObject,
address: String,
method: String,
body: String?,
headers: Map<String, String> = emptyMap()
): HttpResult {
val target = URL(address)
val base = URL(account.optString("serverUrl"))
val targetPort = if (target.port >= 0) target.port else target.defaultPort
val basePort = if (base.port >= 0) base.port else base.defaultPort
require(target.protocol == base.protocol && target.host.equals(base.host, true) && targetPort == basePort) {
"The DAV server returned a collection URL on an unexpected host."
}
val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull())
val builder = Request.Builder()
.url(address)
.header("Authorization", basicAuth(account))
.header("User-Agent", "ep-mail-Android")
for ((key, value) in headers) builder.header(key, value)
builder.method(method, requestBody)
httpClient.newCall(builder.build()).execute().use { response ->
val bytes = response.body?.bytes() ?: ByteArray(0)
val responseHeaders = response.headers.toMultimap().mapValues { (_, values) -> values.firstOrNull().orEmpty() }
return HttpResult(response.code, bytes, responseHeaders)
}
}
private fun discoverCollections(serverUrl: String, username: String, password: String, type: String): JSONArray {
val base = JSONObject().put("serverUrl", serverUrl).put("username", username).put("password", password)
val setName = if (type == "caldav") "calendar-home-set" else "addressbook-home-set"
val rootResponse = request(base, serverUrl, "PROPFIND", propfindBody(setName), mapOf(
"Depth" to "0",
"Content-Type" to "application/xml; charset=utf-8"
))
require(rootResponse.code in 200..299 || rootResponse.code == 207) {
"Could not access the DAV server (${rootResponse.code})."
}
val rootDocument = parseXml(rootResponse.body)
var homeUrl = findHref(rootDocument, setName)?.let { resolveUrl(serverUrl, it) }
if (homeUrl == null) {
val principal = findHref(rootDocument, "current-user-principal")
if (principal != null) {
val principalUrl = resolveUrl(serverUrl, principal)
val principalResponse = request(base, principalUrl, "PROPFIND", propfindBody(setName), mapOf(
"Depth" to "0",
"Content-Type" to "application/xml; charset=utf-8"
))
if (principalResponse.code in 200..299 || principalResponse.code == 207) {
homeUrl = findHref(parseXml(principalResponse.body), setName)?.let { resolveUrl(principalUrl, it) }
}
}
}
val collectionUrl = homeUrl ?: serverUrl
val response = request(base, collectionUrl, "PROPFIND", collectionBody(), mapOf(
"Depth" to "1",
"Content-Type" to "application/xml; charset=utf-8"
))
require(response.code in 200..299 || response.code == 207) {
"Could not discover DAV collections (${response.code})."
}
val document = parseXml(response.body)
val requiredType = if (type == "caldav") "calendar" else "addressbook"
val result = JSONArray()
val responses = document.getElementsByTagNameNS("*", "response")
for (index in 0 until responses.length) {
val responseElement = responses.item(index) as? Element ?: continue
val href = childText(responseElement, "href") ?: continue
if (responseElement.getElementsByTagNameNS("*", requiredType).length == 0) continue
val resolved = resolveUrl(collectionUrl, href)
val displayName = textContent(responseElement, "displayname").orEmpty().ifBlank { resolved }
result.put(JSONObject().put("url", resolved).put("name", displayName))
}
return result
}
private fun listObjects(account: JSONObject, collection: JSONObject, type: String): List<JSONObject> {
val collectionUrl = collection.optString("url")
val response = request(account, collectionUrl, "PROPFIND", collectionBody(), mapOf(
"Depth" to "1",
"Content-Type" to "application/xml; charset=utf-8"
))
require(response.code in 200..299 || response.code == 207) {
"Could not read DAV collection ${collection.optString("name")} (${response.code})."
}
val document = parseXml(response.body)
val responses = document.getElementsByTagNameNS("*", "response")
val result = ArrayList<JSONObject>()
for (index in 0 until responses.length) {
val element = responses.item(index) as? Element ?: continue
val href = childText(element, "href") ?: continue
val objectUrl = resolveUrl(collectionUrl, href)
if (objectUrl.trimEnd('/') == collectionUrl.trimEnd('/')) continue
val data = if (type == "caldav") textContent(element, "calendar-data") else textContent(element, "address-data")
val content = if (!data.isNullOrBlank()) data else {
val fetched = request(account, objectUrl, "GET", null)
if (fetched.code !in 200..299) continue
String(fetched.body, StandardCharsets.UTF_8)
}
result.add(JSONObject()
.put("href", objectUrl)
.put("etag", textContent(element, "getetag").orEmpty())
.put("data", content))
}
return result
}
private fun parseCalendar(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
val unfolded = unfold(data)
return Regex("BEGIN:VEVENT(.*?)END:VEVENT", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
.findAll(unfolded).mapNotNull { match ->
val block = match.groupValues[1]
val fields = parseProperties(block)
val uid = fields["UID"].orEmpty().ifBlank { UUID.randomUUID().toString() }
val (date, time) = parseDate(fields["DTSTART"].orEmpty()) ?: return@mapNotNull null
JSONObject()
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
.put("title", unescape(fields["SUMMARY"].orEmpty()).ifBlank { "(no title)" })
.put("date", date)
.put("time", time)
.put("with", Regex("(?im)^ATTENDEE[^:]*:(?:mailto:)?([^\\r\\n]+)").findAll(block)
.map { it.groupValues[1].trim() }.joinToString(", "))
.put("place", unescape(fields["LOCATION"].orEmpty()))
.put("notes", unescape(fields["DESCRIPTION"].orEmpty()))
.put("_dav", JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collection.optString("url"))
.put("objectUrl", resource.optString("href"))
.put("etag", resource.optString("etag"))
.put("uid", uid))
}.toList()
}
private fun parseContacts(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
val cards = Regex("BEGIN:VCARD(.*?)END:VCARD", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
return cards.findAll(unfold(data)).mapNotNull { match ->
val block = match.groupValues[1]
val fields = parseProperties(block)
val name = unescape(fields["FN"].orEmpty()).trim()
if (name.isBlank()) return@mapNotNull null
val uid = fields["UID"].orEmpty()
JSONObject()
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
.put("name", name)
.put("email", unescape(fields["EMAIL"].orEmpty()))
.put("note", unescape(fields["NOTE"].orEmpty()))
.put("initials", name.split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.toString() }
.joinToString("").take(2).uppercase(Locale.getDefault()))
.put("color", "#dce9dd")
.put("_dav", JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collection.optString("url"))
.put("objectUrl", resource.optString("href"))
.put("etag", resource.optString("etag"))
.put("uid", uid))
}.toList()
}
private fun calendarData(event: JSONObject, uid: String): String {
val date = event.optString("date").replace("-", "")
val time = event.optString("time")
val start = if (time.isBlank()) "DTSTART;VALUE=DATE:$date" else "DTSTART;TZID=UTC:${date}T${time.replace(":", "")}00"
val end = if (time.isBlank()) "" else {
val parts = time.split(":")
val mins = (parts.getOrNull(0)?.toIntOrNull() ?: 0) * 60 + (parts.getOrNull(1)?.toIntOrNull() ?: 0) + 60
val endTime = "%04d%02d00".format(Locale.ROOT, (mins / 60) % 24, mins % 60)
"DTEND;TZID=UTC:${date}T$endTime\r\n"
}
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${escape(uid)}\r\nDTSTAMP:${utcNow()}\r\n$start\r\n$end${property("SUMMARY", event.optString("title"))}${property("LOCATION", event.optString("place"))}${property("DESCRIPTION", event.optString("notes"))}END:VEVENT\r\nEND:VCALENDAR\r\n"
}
private fun vcardData(contact: JSONObject, uid: String): String {
val name = contact.optString("name").trim().split(Regex("\\s+"))
val first = name.firstOrNull().orEmpty()
val last = name.drop(1).joinToString(" ")
return "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${escape(uid)}\r\nFN:${escape(contact.optString("name"))}\r\nN:${escape(last)};${escape(first)};;;\r\nEMAIL:${escape(contact.optString("email"))}\r\n${if (contact.optString("note").isNotBlank()) "NOTE:${escape(contact.optString("note"))}\r\n" else ""}END:VCARD\r\n"
}
private fun propfindBody(homeSet: String) = """<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
<d:prop><d:current-user-principal/><d:displayname/><c:$homeSet/><a:$homeSet/></d:prop>
</d:propfind>""".trimIndent()
private fun collectionBody() = """<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
<d:prop><d:resourcetype/><d:displayname/><d:getetag/><c:calendar-data/><a:address-data/></d:prop>
</d:propfind>""".trimIndent()
private fun parseXml(bytes: ByteArray): org.w3c.dom.Document {
val factory = DocumentBuilderFactory.newInstance().apply {
isNamespaceAware = true
isXIncludeAware = false
isExpandEntityReferences = false
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
setFeature("http://xml.org/sax/features/external-general-entities", false)
setFeature("http://xml.org/sax/features/external-parameter-entities", false)
}
return factory.newDocumentBuilder().parse(ByteArrayInputStream(bytes))
}
private fun findHref(document: org.w3c.dom.Document, propertyName: String): String? {
val elements = document.getElementsByTagNameNS("*", propertyName)
for (index in 0 until elements.length) {
val href = (elements.item(index) as? Element)?.getElementsByTagNameNS("*", "href")?.item(0)?.textContent
if (!href.isNullOrBlank()) return href.trim()
}
return null
}
private fun textContent(element: Element, propertyName: String): String? {
val nodes = element.getElementsByTagNameNS("*", propertyName)
return if (nodes.length == 0) null else nodes.item(0)?.textContent?.trim()
}
private fun childText(element: Element, childName: String): String? {
val children = element.childNodes
for (index in 0 until children.length) {
val node = children.item(index)
if (node is Element && node.localName == childName) return node.textContent.trim()
}
return null
}
private fun resolveUrl(base: String, href: String): String = URL(URL(base), href).toString()
private fun basicAuth(account: JSONObject): String {
val raw = "${account.optString("username")}:${account.optString("password")}"
return "Basic " + Base64.encodeToString(raw.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
}
private fun publicDav(account: JSONObject) = JSONObject()
.put("id", account.optString("id"))
.put("serverUrl", account.optString("serverUrl"))
.put("username", account.optString("username"))
.put("collections", account.optJSONArray("collections") ?: JSONArray())
private fun type(value: String) = if (value == "carddav") "carddav" else "caldav"
private fun findCollection(collections: JSONArray, url: String): JSONObject? {
for (index in 0 until collections.length()) {
val collection = collections.getJSONObject(index)
if (url.isBlank() || collection.optString("url") == url) return collection
}
return null
}
private fun encode(value: String) = java.net.URLEncoder.encode(value, "UTF-8")
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")
private fun unescape(value: String) = value.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")
private fun property(name: String, value: String) = if (value.isBlank()) "" else "$name:${escape(value)}\r\n"
private fun utcNow() = java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ROOT)
.apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }.format(java.util.Date())
private fun unfold(data: String) = data.replace("\r\n ", "").replace("\n ", "").replace("\r\n\t", "").replace("\n\t", "")
private fun parseProperties(block: String): Map<String, String> {
val result = LinkedHashMap<String, String>()
for (line in block.lines()) {
val colon = line.indexOf(':')
if (colon <= 0) continue
val name = line.substring(0, colon).substringBefore(';').uppercase(Locale.ROOT)
result.putIfAbsent(name, line.substring(colon + 1).trim())
}
return result
}
private fun parseDate(raw: String): Pair<String, String>? {
if (raw.isBlank()) return null
val rawValue = raw.substringAfter(':', raw)
return try {
when {
rawValue.length == 8 -> "${rawValue.substring(0, 4)}-${rawValue.substring(4, 6)}-${rawValue.substring(6, 8)}" to ""
rawValue.length >= 15 -> {
val digits = rawValue.replace("T", "").replace("Z", "").take(14)
val date = "${digits.substring(0, 4)}-${digits.substring(4, 6)}-${digits.substring(6, 8)}"
val time = "${digits.substring(8, 10)}:${digits.substring(10, 12)}"
date to time
}
else -> null
}
} catch (_: Exception) { null }
}
}
@@ -0,0 +1,767 @@
package studio.daybreak.mail
import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.Html
import android.webkit.MimeTypeMap
import com.sun.mail.imap.IMAPFolder
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.Properties
import java.util.UUID
import javax.mail.Address
import javax.mail.Authenticator
import javax.mail.Flags
import javax.mail.Folder
import javax.mail.Message
import javax.mail.Multipart
import javax.mail.PasswordAuthentication
import javax.mail.Session
import javax.mail.Store
import javax.mail.Transport
import javax.mail.UIDFolder
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
import javax.mail.internet.MimeUtility
internal object AndroidMailService {
data class SyncResult(val payload: JSONObject, val newCount: Int)
fun connect(account: JSONObject): JSONObject = withStore(account) { session, store ->
val inbox = store.getFolder("INBOX")
check(inbox.exists()) { "The inbox could not be found." }
inbox.open(Folder.READ_ONLY)
val count = inbox.messageCount
inbox.close(false)
val smtpSession = Session.getInstance(smtpProperties(account), credentials(account))
val transport = smtpSession.getTransport("smtp")
try {
transport.connect(
account.optString("smtpHost"),
account.optInt("smtpPort", 587),
account.optString("email"),
account.optString("password")
)
} finally {
if (transport.isConnected) transport.close()
}
JSONObject().put("mailbox", "INBOX").put("messages", count)
}
fun sync(account: JSONObject, requestedFolder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject {
if (requestedFolder == "Snoozed") return syncSnoozed(account, offset)
return try {
withStore(account) { _, store ->
val folder = resolveFolder(store, requestedFolder)
if (folder == null) return@withStore JSONObject()
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
folder.open(Folder.READ_ONLY)
try {
val total = folder.messageCount
val hasSearchFilters = listOf("query", "sender", "subject", "after", "before")
.any { filters.optString(it).isNotBlank() } || filters.optBoolean("hasAttachments")
if (hasSearchFilters) {
val all = JSONArray()
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
if (total > 0) {
val start = (total - 4999).coerceAtLeast(1)
for (message in folder.getMessages(start, total)) {
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
if (snoozed.length() > 0 && (0 until snoozed.length()).any { index ->
val item = snoozed.optJSONObject(index) ?: return@any false
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
item.optLong("dueAt") > System.currentTimeMillis()
}) continue
all.put(messageJson(folder, message, requestedFolder, account))
}
}
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, all)
val matches = (0 until all.length()).mapNotNull { all.optJSONObject(it) }
.filter { matchesFilters(it, filters) }
.sortedByDescending { it.optLong("timestamp") }
val start = offset.coerceAtLeast(0)
val page = matches.drop(start).take(20)
return@withStore JSONObject()
.put("messages", JSONArray().apply { page.forEach(::put) })
.put("total", matches.size)
.put("start", if (matches.isEmpty()) 0 else start + 1)
.put("end", start + page.size)
.put("folder", requestedFolder)
}
val end = (total - offset.coerceAtLeast(0)).coerceAtLeast(0)
if (end == 0) {
return@withStore JSONObject().put("messages", JSONArray()).put("total", total)
.put("start", 0).put("end", 0).put("folder", requestedFolder)
}
val first = (end - 19).coerceAtLeast(1)
val result = JSONArray()
val batch = folder.getMessages(first, end).reversed()
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
val cached = JSONArray()
for (message in batch) {
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
val isSnoozed = (0 until snoozed.length()).any { index ->
val item = snoozed.getJSONObject(index)
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
item.optLong("dueAt") > System.currentTimeMillis()
}
if (isSnoozed) continue
val value = messageJson(folder, message, requestedFolder, account)
result.put(value)
cached.put(value)
}
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached)
JSONObject().put("messages", result).put("total", total)
.put("start", first).put("end", end).put("folder", requestedFolder)
} finally {
folder.close(false)
}
}
} catch (error: Exception) {
if (!isConnectivityFailure(error)) throw error
AndroidAccountVault.cachedFolder(account.optString("id"), requestedFolder, offset, filters)
?: throw error
}
}
private fun isConnectivityFailure(error: Throwable): Boolean {
var current: Throwable? = error
while (current != null) {
if (current is java.net.UnknownHostException ||
current is java.net.ConnectException ||
current is java.net.SocketTimeoutException ||
current is javax.net.ssl.SSLException) return true
val message = current.message.orEmpty().lowercase(Locale.ROOT)
if (listOf("network is unreachable", "connection timed out", "connection refused", "unable to resolve host", "socket closed").any(message::contains)) return true
current = current.cause
}
return false
}
private fun matchesFilters(message: JSONObject, filters: JSONObject): Boolean {
val query = filters.optString("query").trim().lowercase(Locale.ROOT)
val senderFilter = filters.optString("sender").trim().lowercase(Locale.ROOT)
val subjectFilter = filters.optString("subject").trim().lowercase(Locale.ROOT)
val sender = "${message.optString("sender")} ${message.optString("email")}".lowercase(Locale.ROOT)
val subject = message.optString("subject").lowercase(Locale.ROOT)
val haystack = "$sender $subject ${message.optString("snippet")} ${message.optJSONArray("body")?.toString().orEmpty()}".lowercase(Locale.ROOT)
val timestamp = message.optLong("timestamp")
val after = dateBoundary(filters.optString("after"), false)
val before = dateBoundary(filters.optString("before"), true)
val attachments = message.optJSONArray("attachments")
return (query.isBlank() || query.split(Regex("\\s+")).all(haystack::contains)) &&
(senderFilter.isBlank() || sender.contains(senderFilter)) &&
(subjectFilter.isBlank() || subject.contains(subjectFilter)) &&
(after == null || timestamp >= after) && (before == null || timestamp <= before) &&
(!filters.optBoolean("hasAttachments") || (attachments?.length() ?: 0) > 0)
}
private fun dateBoundary(value: String, endOfDay: Boolean): Long? {
if (value.isBlank()) return null
val parsed = runCatching { SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(value) }.getOrNull() ?: return null
val calendar = Calendar.getInstance().apply { time = parsed }
if (endOfDay) {
calendar.add(Calendar.DAY_OF_MONTH, 1)
return calendar.timeInMillis - 1
}
return calendar.timeInMillis
}
private fun syncSnoozed(account: JSONObject, offset: Int): JSONObject =
withStore(account) { _, store ->
val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray()
val pending = (0 until snoozes.length())
.map { snoozes.getJSONObject(it) }
.filter { it.optLong("dueAt") > System.currentTimeMillis() }
.sortedBy { it.optLong("dueAt") }
val page = pending.drop(offset.coerceAtLeast(0)).take(20)
val messages = JSONArray()
for (snooze in page) {
val sourceFolder = snooze.optString("folder", "Inbox")
val folder = resolveFolder(store, sourceFolder) ?: continue
folder.open(Folder.READ_ONLY)
try {
val message = (folder as? UIDFolder)?.getMessageByUID(snooze.optLong("uid")) ?: continue
messages.put(messageJson(folder, message, "Snoozed", account, sourceFolder)
.put("sourceFolder", sourceFolder)
.put("snoozedUntil", snooze.optLong("dueAt")))
} finally {
folder.close(false)
}
}
JSONObject()
.put("messages", messages)
.put("total", pending.size)
.put("start", if (page.isEmpty()) 0 else offset + 1)
.put("end", offset + messages.length())
.put("folder", "Snoozed")
}
fun updateMessage(account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store ->
val uid = input.optLong("uid")
require(uid > 0) { "That message could not be identified." }
val action = input.optString("action")
require(action in setOf("star", "unread", "archive", "delete", "inbox")) { "That mail action is not supported." }
val source = resolveFolder(store, input.optString("folder", "Inbox"))
?: throw IllegalStateException("That mail folder could not be found.")
var expungeDeleted = false
source.open(Folder.READ_WRITE)
try {
val message = (source as? UIDFolder)?.getMessageByUID(uid)
?: throw IllegalStateException("The message is no longer available.")
when (action) {
"star" -> message.setFlag(Flags.Flag.FLAGGED, input.optBoolean("enabled"))
"unread" -> message.setFlag(Flags.Flag.SEEN, !input.optBoolean("enabled"))
"archive", "delete", "inbox" -> {
val targetName = when (action) {
"archive" -> "Archive"
"delete" -> "Trash"
else -> "Inbox"
}
val target = resolveFolder(store, targetName) ?: store.getFolder(targetName)
if (!target.exists()) target.create(Folder.HOLDS_MESSAGES)
if (source.fullName == target.fullName) {
if (action == "delete") {
expungeDeleted = true
message.setFlag(Flags.Flag.DELETED, true)
}
} else {
expungeDeleted = true
source.copyMessages(arrayOf(message), target)
message.setFlag(Flags.Flag.DELETED, true)
}
}
}
} finally {
source.close(expungeDeleted)
}
if (action == "archive" || action == "delete" || action == "inbox") {
AndroidAccountVault.setSnooze(
account.optString("id"),
uid,
input.optString("folder", "Inbox"),
null,
""
)
}
JSONObject().put("ok", true)
}
fun send(account: JSONObject, input: JSONObject): JSONObject {
val recipient = input.optString("to").trim()
require(recipient.isNotEmpty()) { "Add at least one recipient." }
val properties = smtpProperties(account)
val session = Session.getInstance(properties, credentials(account))
val message = MimeMessage(session)
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
val cc = input.optString("cc").trim()
if (cc.isNotEmpty()) message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, true))
message.subject = input.optString("subject", "(no subject)")
val body = input.optString("text")
val signature = account.optString("signature").take(5000)
message.setText(
if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature",
"UTF-8"
)
message.sentDate = Date()
message.saveChanges()
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
val transport = session.getTransport("smtp")
try {
transport.connect(
account.optString("smtpHost"),
account.optInt("smtpPort", 587),
account.optString("email"),
account.optString("password")
)
transport.sendMessage(message, message.allRecipients)
} finally {
if (transport.isConnected) transport.close()
}
var savedToSent = false
try {
withStore(account) { _, store ->
val sent = resolveFolder(store, "Sent") ?: store.getFolder("Sent")
if (!sent.exists()) sent.create(Folder.HOLDS_MESSAGES)
sent.appendMessages(arrayOf(message))
savedToSent = true
}
} catch (_: Exception) {
savedToSent = false
}
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
}
fun flushOutbox(account: JSONObject) {
val accountId = account.optString("id")
val queued = AndroidAccountVault.pendingMailOperations(accountId)
for (index in 0 until queued.length()) {
val operation = queued.optJSONObject(index) ?: continue
try {
val data = operation.optJSONObject("data") ?: continue
when (operation.optString("type")) {
"send" -> send(account, data)
"action" -> updateMessage(account, data)
else -> throw IllegalStateException("Unsupported queued mail operation.")
}
AndroidAccountVault.removeMailOperation(accountId, operation.optString("id"))
} catch (error: Exception) {
android.util.Log.w("EpMailOutbox", "Mail operation remains queued for a later retry.", error)
break
}
}
}
fun saveAttachment(context: Context, account: JSONObject, input: JSONObject): JSONObject =
withStore(account) { _, store ->
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
?: throw IllegalStateException("That mail folder could not be found.")
folder.open(Folder.READ_ONLY)
try {
val uid = input.optLong("uid")
val message = (folder as? UIDFolder)?.getMessageByUID(uid)
?: throw IllegalStateException("The message is no longer available.")
val filename = input.optString("filename")
val part = findAttachment(message, filename)
?: throw IllegalStateException("No attachment was found in this message.")
saveAttachmentBytes(context, filename.ifBlank { "attachment" }, part.contentType, part.inputStream.readBytes())
} finally {
folder.close(false)
}
}
fun checkForNewMail(account: JSONObject): Int {
flushOutbox(account)
return withStore(account) { _, store ->
val folder = store.getFolder("INBOX")
folder.open(Folder.READ_ONLY)
try {
val uidFolder = folder as? UIDFolder
?: throw IllegalStateException("The mail server does not support stable message IDs.")
val validity = uidFolder.uidValidity
val latestUid = (uidFolder.uidNext - 1).coerceAtLeast(0)
val oldState = account.optJSONObject("androidInboxSyncState")
val lastUid = if (oldState == null || oldState.optLong("uidValidity") != validity) {
AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid)
return@withStore 0
} else oldState.optLong("lastUid")
if (latestUid <= lastUid) return@withStore 0
val added = uidFolder.getMessagesByUID(lastUid + 1, UIDFolder.LASTUID)
AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid)
applyRules(account, added.mapNotNull { try { uidFolder.getUID(it) } catch (_: Exception) { null } })
added.size
} finally {
folder.close(false)
}
}
}
fun applyRules(account: JSONObject, uids: List<Long>) {
val rules = account.optJSONArray("rules") ?: return
if (rules.length() == 0 || uids.isEmpty()) return
withStore(account) { _, store ->
val inbox = resolveFolder(store, "Inbox") ?: return@withStore
for (uid in uids.distinct()) {
try {
inbox.open(Folder.READ_WRITE)
try {
val message = (inbox as? UIDFolder)?.getMessageByUID(uid) ?: continue
val sender = message.from.orEmpty().joinToString(" ") { address ->
if (address is InternetAddress) "${address.personal.orEmpty()} ${address.address}" else address.toString()
}
val subject = message.subject.orEmpty()
val matched = (0 until rules.length()).asSequence()
.map { rules.getJSONObject(it) }
.firstOrNull { rule ->
val senderCondition = rule.optString("senderContains")
val subjectCondition = rule.optString("subjectContains")
(senderCondition.isBlank() || sender.contains(senderCondition, ignoreCase = true)) &&
(subjectCondition.isBlank() || subject.contains(subjectCondition, ignoreCase = true))
} ?: continue
when (matched.optString("action")) {
"flag" -> message.setFlag(Flags.Flag.FLAGGED, true)
"label" -> AndroidAccountVault.addRuleLabel(
account.optString("id"), "Inbox", uid, matched.optString("value")
)
"archive", "move" -> {
val destination = if (matched.optString("action") == "archive") {
resolveFolder(store, "Archive") ?: store.getFolder("Archive").also {
if (!it.exists()) it.create(Folder.HOLDS_MESSAGES)
}
} else resolveFolder(store, matched.optString("value"))
?: throw IllegalStateException("Rule destination mailbox \"${matched.optString("value")}\" was not found.")
if (destination.fullName != inbox.fullName) {
inbox.copyMessages(arrayOf(message), destination)
message.setFlag(Flags.Flag.DELETED, true)
}
}
}
} finally {
inbox.close(true)
}
} catch (error: Exception) {
android.util.Log.e("EpMailRules", "Could not apply a mail rule to message $uid", error)
}
}
}
}
fun watchInbox(
account: JSONObject,
onNewMail: (Int) -> Unit,
shouldStop: () -> Boolean,
onConnection: (Store?, Folder?) -> Unit
) {
val props = imapProperties(account).apply {
setProperty("mail.imap.timeout", "0")
setProperty("mail.imap.writetimeout", "60000")
}
val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2)
.coerceIn(2, 60) * 60_000L
val session = Session.getInstance(props, credentials(account))
val store = session.getStore("imap")
try {
store.connect(
account.optString("imapHost"),
account.optInt("imapPort", 143),
account.optString("email"),
account.optString("password")
)
val inbox = store.getFolder("INBOX")
inbox.open(Folder.READ_ONLY)
var previousCount = inbox.messageCount
val uidFolder = inbox as? UIDFolder
val uidValidity = uidFolder?.uidValidity ?: 0L
val initialUid = uidFolder?.let { (it.uidNext - 1).coerceAtLeast(0) } ?: 0L
if (uidValidity > 0) {
AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, initialUid)
}
onConnection(store, inbox)
inbox.addMessageCountListener(object : javax.mail.event.MessageCountListener {
override fun messagesAdded(event: javax.mail.event.MessageCountEvent) {
if (event.type == javax.mail.event.MessageCountEvent.ADDED) {
previousCount = maxOf(previousCount, inbox.messageCount)
val newestUid = event.messages.maxOfOrNull { message ->
try { uidFolder?.getUID(message) ?: 0L } catch (_: Exception) { 0L }
} ?: 0L
if (uidValidity > 0 && newestUid > 0) {
AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, newestUid)
}
val addedUids = event.messages.mapNotNull { message ->
try { uidFolder?.getUID(message) } catch (_: Exception) { null }
}
Thread({
applyRules(account, addedUids)
}, "ep-mail-rules-${account.optString("id")}").start()
onNewMail(event.messages.size)
}
}
override fun messagesRemoved(event: javax.mail.event.MessageCountEvent) = Unit
})
try {
var supportsIdle = inbox is IMAPFolder
while (!shouldStop()) {
try {
if (supportsIdle && inbox is IMAPFolder) {
inbox.idle()
} else {
Thread.sleep(pollingIntervalMs)
val currentCount = inbox.messageCount
if (currentCount > previousCount) {
val added = checkForNewMail(account)
if (added > 0) onNewMail(added)
}
previousCount = currentCount
}
} catch (error: Exception) {
if (shouldStop()) break
if (error !is javax.mail.MethodNotSupportedException &&
!error.javaClass.simpleName.contains("UnsupportedCommand")) throw error
supportsIdle = false
}
}
} finally {
onConnection(null, null)
if (inbox.isOpen) inbox.close(false)
}
} finally {
if (store.isConnected) store.close()
}
}
fun accountFingerprint(account: JSONObject): String = listOf(
account.optString("email"),
account.optString("imapHost"),
account.optString("password"),
account.optBoolean("notificationsEnabled", true),
account.optInt("syncIntervalMinutes", 2),
account.optString("signature"),
account.optJSONArray("rules")?.toString().orEmpty()
).joinToString("|").hashCode().toString()
private fun messageJson(
folder: Folder,
message: Message,
requestedFolder: String,
account: JSONObject? = null,
labelFolder: String = requestedFolder
): JSONObject {
val uid = (folder as? UIDFolder)?.getUID(message) ?: message.messageNumber.toLong()
val sender = (message.from?.firstOrNull() as? InternetAddress)
val senderName = decode(sender?.personal).ifBlank { sender?.address ?: "Unknown sender" }
val senderEmail = sender?.address ?: ""
val subject = decode(message.subject).ifBlank { "(no subject)" }
val body = ArrayList<String>()
val attachments = JSONArray()
val links = linkedSetOf<String>()
collectParts(message, body, attachments, links)
val bodyText = body.joinToString("\n\n").trim().take(8000)
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date()
val tags = JSONArray().put(requestedFolder)
val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid")
if (ruleLabels != null) {
for (index in 0 until ruleLabels.length()) {
val label = ruleLabels.optString(index)
if (label.isNotBlank()) tags.put(label)
}
}
val files = attachmentList(attachments)
val flags = message.flags
val id = uid.toDouble()
return JSONObject()
.put("id", id)
.put("uid", uid)
.put("initials", senderName.split(Regex("[\\s@]+")).filter(String::isNotBlank)
.mapNotNull { it.firstOrNull()?.toString() }.joinToString("").take(2).uppercase(Locale.getDefault()))
.put("color", "#dce6df")
.put("sender", senderName)
.put("email", senderEmail)
.put("subject", subject)
.put("snippet", snippet)
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
.put("timestamp", date.time)
.put("unread", !flags.contains(Flags.Flag.SEEN))
.put("star", flags.contains(Flags.Flag.FLAGGED))
.put("tags", tags)
.put("sent", requestedFolder == "Sent")
.put("archived", requestedFolder == "Archive")
.put("deleted", requestedFolder == "Trash")
.put("sourceFolder", labelFolder)
.put("body", JSONArray().apply {
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
})
.put("links", JSONArray().apply { links.take(30).forEach(::put) })
.put("attachments", attachments)
.put("attachment", files.firstOrNull()?.optString("filename") ?: JSONObject.NULL)
.put("size", files.firstOrNull()?.optString("size") ?: "")
}
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
(0 until attachments.length()).map { attachments.getJSONObject(it) }
private fun collectParts(part: javax.mail.Part, body: MutableList<String>, attachments: JSONArray, links: MutableSet<String>) {
val filename = decode(part.fileName)
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
val name = filename.ifBlank { "attachment" }
val size = part.size.coerceAtLeast(0)
attachments.put(JSONObject().put("filename", name).put("size", size))
return
}
val content = try { part.content } catch (_: Exception) { return }
when (content) {
is String -> if (part.isMimeType("text/plain")) {
body.add(content.replace("\r", "").trim())
} else if (part.isMimeType("text/html")) {
Regex("""<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE)
.findAll(content)
.mapNotNull { match -> (match.groups[1]?.value ?: match.groups[2]?.value ?: match.groups[3]?.value)?.replace("&amp;", "&") }
.take(30)
.forEach(links::add)
if (body.isEmpty()) body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim())
}
is Multipart -> for (index in 0 until content.count) {
collectParts(content.getBodyPart(index), body, attachments, links)
}
is javax.mail.BodyPart -> collectParts(content, body, attachments, links)
}
}
private fun findAttachment(part: javax.mail.Part, filename: String): MimeBodyPart? {
val name = decode(part.fileName)
if ((name == filename || (filename.isBlank() && name.isNotBlank())) && part is MimeBodyPart) return part
val content = try { part.content } catch (_: Exception) { return null }
if (content is Multipart) {
for (index in 0 until content.count) {
findAttachment(content.getBodyPart(index), filename)?.let { return it }
}
}
return null
}
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
val mimeType = contentType.substringBefore(';').ifBlank {
MimeTypeMap.getSingleton().getMimeTypeFromExtension(filename.substringAfterLast('.', "")) ?: "application/octet-stream"
}
if (Build.VERSION.SDK_INT >= 29) {
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, filename)
put(MediaStore.Downloads.MIME_TYPE, mimeType)
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
val uri = context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
?: throw IllegalStateException("Could not create the attachment in Downloads.")
context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
?: throw IllegalStateException("Could not write the attachment.")
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", filename)
}
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
?: throw IllegalStateException("Downloads storage is not available.")
val file = File(directory, filename.replace(Regex("[\\\\/:*?\"<>|]"), "_"))
file.writeBytes(bytes)
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", filename)
}
private const val CUSTOM_FOLDER_PREFIX = "Folder:"
private val reservedFolderNames = setOf(
"inbox", "sent", "drafts", "archive", "trash", "starred", "snoozed", "junk", "spam",
"sent items", "sent mail", "sent messages", "archives", "all mail", "deleted items", "deleted messages"
)
fun isCustomFolder(name: String) = name.startsWith(CUSTOM_FOLDER_PREFIX)
private fun customFolders(store: Store): JSONArray {
val systemAttributes = setOf("\\sent", "\\archive", "\\trash", "\\drafts", "\\junk", "\\all", "\\flagged")
val result = JSONArray()
val folders = try { store.defaultFolder.list("*") } catch (_: Exception) { emptyArray() }
folders.filter { folder ->
val attributes = (folder as? IMAPFolder)?.attributes?.map { it.lowercase(Locale.ROOT) } ?: emptyList()
folder.fullName.uppercase(Locale.ROOT) != "INBOX" &&
(folder.type and Folder.HOLDS_MESSAGES) != 0 &&
attributes.none { it in systemAttributes } &&
folder.fullName.lowercase(Locale.ROOT).split(Regex("[./]")).last() !in reservedFolderNames
}.sortedBy { it.fullName }.forEach { folder ->
result.put(JSONObject().put("name", folder.name).put("path", folder.fullName)
.put("id", CUSTOM_FOLDER_PREFIX + folder.fullName))
}
return result
}
fun listFolders(account: JSONObject): JSONObject =
withStore(account) { _, store -> JSONObject().put("folders", customFolders(store)) }
fun createFolder(account: JSONObject, rawName: String): JSONObject {
val name = rawName.trim()
require(name.isNotEmpty() && name.length <= 100) { "Enter a folder name of up to 100 characters." }
require(!Regex("[\\\\/.*%#&\\u0000-\\u001f]").containsMatchIn(name)) {
"Folder names cannot contain / \\ . * % # & or control characters."
}
require(name.lowercase(Locale.ROOT) !in reservedFolderNames) { "That folder name is reserved." }
return withStore(account) { _, store ->
val folder = store.getFolder(name)
check(!folder.exists()) { "A folder with that name already exists." }
check(folder.create(Folder.HOLDS_MESSAGES)) { "The mail server could not create that folder." }
try { folder.isSubscribed = true } catch (_: Exception) {}
JSONObject().put("ok", true)
.put("folder", JSONObject().put("name", name).put("path", folder.fullName)
.put("id", CUSTOM_FOLDER_PREFIX + folder.fullName))
.put("folders", customFolders(store))
}
}
private fun resolveFolder(store: Store, requested: String): Folder? {
if (requested.startsWith(CUSTOM_FOLDER_PREFIX)) {
return store.getFolder(requested.removePrefix(CUSTOM_FOLDER_PREFIX)).takeIf { it.exists() }
}
if (requested == "Inbox" || requested == "Starred" || requested == "Snoozed") {
return store.getFolder("INBOX")
}
val (specialUse, candidates) = when (requested) {
"Sent" -> "\\Sent" to setOf("sent", "sent items", "sent mail", "sent messages")
"Archive" -> "\\Archive" to setOf("archive", "archives", "all mail")
"Trash" -> "\\Trash" to setOf("trash", "deleted items", "deleted messages")
else -> return store.getFolder(requested).takeIf { it.exists() }
}
val folders = try { store.defaultFolder.list("*") } catch (_: Exception) { emptyArray() }
return folders.firstOrNull { folder ->
val imapFolder = folder as? IMAPFolder
imapFolder?.attributes?.any { it.equals(specialUse, true) } == true
} ?: folders.firstOrNull { folder ->
folder.fullName.lowercase(Locale.ROOT).split(Regex("[./]")).lastOrNull() in candidates
}
}
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
val session = Session.getInstance(imapProperties(account), credentials(account))
val store = session.getStore("imap")
try {
store.connect(
account.optString("imapHost"),
account.optInt("imapPort", 143),
account.optString("email"),
account.optString("password")
)
return block(session, store)
} finally {
if (store.isConnected) store.close()
}
}
private fun credentials(account: JSONObject) = object : Authenticator() {
override fun getPasswordAuthentication() = PasswordAuthentication(
account.optString("email"),
account.optString("password")
)
}
private fun imapProperties(account: JSONObject) = Properties().apply {
setProperty("mail.store.protocol", "imap")
setProperty("mail.imap.host", account.optString("imapHost"))
setProperty("mail.imap.port", account.optInt("imapPort", 143).toString())
setProperty("mail.imap.auth", "true")
setProperty("mail.imap.starttls.enable", "true")
setProperty("mail.imap.starttls.required", "true")
setProperty("mail.imap.ssl.checkserveridentity", "true")
setProperty("mail.imap.connectiontimeout", "20000")
setProperty("mail.imap.timeout", "30000")
setProperty("mail.imap.writetimeout", "30000")
}
private fun smtpProperties(account: JSONObject) = Properties().apply {
setProperty("mail.smtp.host", account.optString("smtpHost"))
setProperty("mail.smtp.port", account.optInt("smtpPort", 587).toString())
setProperty("mail.smtp.auth", "true")
setProperty("mail.smtp.starttls.enable", "true")
setProperty("mail.smtp.starttls.required", "true")
setProperty("mail.smtp.ssl.checkserveridentity", "true")
setProperty("mail.smtp.connectiontimeout", "20000")
setProperty("mail.smtp.timeout", "30000")
setProperty("mail.smtp.writetimeout", "30000")
}
private fun displayName(account: JSONObject) =
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
private fun decode(value: String?): String = try {
if (value.isNullOrBlank()) "" else MimeUtility.decodeText(value)
} catch (_: Exception) {
value.orEmpty()
}
}
@@ -0,0 +1,507 @@
package studio.daybreak.mail
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.app.AlertDialog
import com.getcapacitor.JSObject
import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin
import java.util.Locale
import java.util.UUID
import org.json.JSONArray
import org.json.JSONObject
@CapacitorPlugin(name = "EpMail")
class EpMailPlugin : Plugin() {
private var syncReceiver: BroadcastReceiver? = null
override fun load() {
AndroidAccountVault.initialize(context)
val filter = IntentFilter(MailIdleService.ACTION_MAIL_SYNC)
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val update = intent.getStringExtra(MailIdleService.EXTRA_SYNC_UPDATE) ?: return
notifyListeners("mailSyncUpdate", JSObject(update))
}
}
syncReceiver = receiver
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
MailIdleService.start(context)
}
override fun handleOnResume() {
MailIdleService.start(context)
}
override fun handleOnDestroy() {
syncReceiver?.let {
try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {}
}
syncReceiver = null
}
@PluginMethod
fun getAppVersion(call: PluginCall) {
call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME))
}
@PluginMethod
fun getAccount(call: PluginCall) {
val account = AndroidAccountVault.account()
if (account == null) call.resolve()
else call.resolve(AndroidAccountVault.publicAccount(account).toJSObject())
}
@PluginMethod
fun listAccounts(call: PluginCall) {
val store = AndroidAccountVault.read()
call.resolve(JSObject()
.put("accounts", AndroidAccountVault.publicAccounts())
.put("activeId", store.optString("activeId")))
}
@PluginMethod
fun selectAccount(call: PluginCall) {
try {
val id = call.getString("id") ?: throw IllegalArgumentException("Choose a mail account.")
val account = AndroidAccountVault.account(id)
?: throw IllegalStateException("That mail account is no longer available.")
val store = AndroidAccountVault.read().put("activeId", id)
AndroidAccountVault.write(store)
MailIdleService.start(context)
call.resolve(AndroidAccountVault.publicAccount(account).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not select the mail account.")
}
}
@PluginMethod
fun removeAccount(call: PluginCall) {
try {
val id = call.getString("id") ?: throw IllegalArgumentException("Choose a mail account.")
val result = AndroidAccountVault.removeAccount(id)
if (AndroidAccountVault.accounts().length() == 0) MailIdleService.stop(context)
else MailIdleService.start(context)
call.resolve(result.toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not remove the mail account.")
}
}
@PluginMethod
fun connect(call: PluginCall) {
try {
val account = normalizeAccount(call.data)
val status = AndroidMailService.connect(account)
val saved = AndroidAccountVault.saveAccount(account)
MailIdleService.start(context)
call.resolve(AndroidAccountVault.publicAccount(saved)
.put("ok", true)
.put("mailbox", status.optString("mailbox"))
.put("messages", status.optInt("messages")).toJSObject())
} catch (error: Exception) {
call.reject("Could not connect to the mailbox: ${error.message}")
}
}
@PluginMethod
fun updateAccount(call: PluginCall) {
try {
val id = call.getString("id") ?: throw IllegalArgumentException("Choose a mail account.")
val existing = AndroidAccountVault.account(id)
?: throw IllegalStateException("That mail account is no longer available.")
val input = JSONObject(call.data.toString()).apply {
if (optString("password").isBlank()) put("password", existing.optString("password"))
}
val account = normalizeAccount(input).put("id", id)
val status = AndroidMailService.connect(account)
val saved = AndroidAccountVault.saveAccount(account)
MailIdleService.start(context)
call.resolve(AndroidAccountVault.publicAccount(saved)
.put("mailbox", status.optString("mailbox"))
.put("messages", status.optInt("messages")).toJSObject())
} catch (error: Exception) {
call.reject("Could not update the mailbox: ${error.message}")
}
}
@PluginMethod
fun listFolders(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before listing folders.")
call.resolve(AndroidMailService.listFolders(account).toJSObject())
} catch (error: Exception) {
call.resolve(JSObject().put("folders", org.json.JSONArray()).put("offline", true))
}
}
@PluginMethod
fun createFolder(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before creating folders.")
call.resolve(AndroidMailService.createFolder(account, call.getString("name") ?: "").toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not create the folder.")
}
}
@PluginMethod
fun syncFolder(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before syncing.")
val requested = call.getString("folder") ?: "Inbox"
val filters = call.getObject("filters") ?: JSObject()
val filterFolder = filters.getString("folder")
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 offset = (call.getInt("offset") ?: 0).coerceAtLeast(0)
AndroidMailService.flushOutbox(account)
call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not sync the mailbox.")
}
}
@PluginMethod
fun updateMessage(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before changing messages.")
call.resolve(AndroidMailService.updateMessage(account, call.data).toJSObject())
} catch (error: Exception) {
val account = AndroidAccountVault.account()
if (account != null && isConnectivityFailure(error)) {
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
.put("id", UUID.randomUUID().toString())
.put("type", "action")
.put("data", JSONObject(call.data.toString())))
call.resolve(JSObject().put("ok", true).put("queued", true))
} else call.reject(error.message ?: "Could not update the message.")
}
}
@PluginMethod
fun setSnooze(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before setting a reminder.")
val uid = call.getLong("uid") ?: throw IllegalArgumentException("That message could not be identified.")
require(uid > 0) { "That message could not be identified." }
val folder = call.getString("sourceFolder") ?: call.getString("folder") ?: "Inbox"
require(folder in setOf("Inbox", "Sent", "Archive", "Trash")) { "That mailbox cannot be snoozed." }
val dueAt = call.getLong("dueAt")
if (dueAt != null && dueAt <= System.currentTimeMillis()) {
throw IllegalArgumentException("Choose a reminder time in the future.")
}
AndroidAccountVault.setSnooze(
account.optString("id"),
uid,
folder,
dueAt,
call.getString("subject").orEmpty()
)
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("foldersChanged", JSONArray().put("Snoozed").put(folder))
context.sendBroadcast(Intent(MailIdleService.ACTION_MAIL_SYNC)
.setPackage(context.packageName)
.putExtra(MailIdleService.EXTRA_SYNC_UPDATE, update.toString()))
MailIdleService.start(context)
call.resolve(JSObject().put("ok", true).put("snoozed", dueAt != null))
} catch (error: Exception) {
call.reject(error.message ?: "Could not set the reminder.")
}
}
@PluginMethod
fun checkSnoozeReminders(call: PluginCall) {
try {
MailIdleService.checkSnoozeReminders(context)
call.resolve()
} catch (error: Exception) {
call.reject(error.message ?: "Could not check mail reminders.")
}
}
@PluginMethod
fun saveAttachment(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before downloading attachments.")
call.resolve(AndroidMailService.saveAttachment(context, account, call.data).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the attachment.")
}
}
@PluginMethod
fun openExternal(call: PluginCall) {
val raw = call.getString("url").orEmpty()
val uri = runCatching { Uri.parse(raw) }.getOrNull()
if (uri == null || uri.scheme?.lowercase(Locale.ROOT) !in setOf("http", "https") ||
uri.host.isNullOrBlank() || uri.userInfo != null) {
call.reject("Only standard web links can be opened from mail.")
return
}
AlertDialog.Builder(activity)
.setTitle("Open external link?")
.setMessage("Email links can lead to fake sign-in pages or harmful content.\n\nCheck the full address before continuing:\n${uri}")
.setNegativeButton("Cancel") { _, _ -> call.resolve(JSObject().put("opened", false)) }
.setPositiveButton("Open link") { _, _ ->
try {
val intent = Intent(Intent.ACTION_VIEW, uri)
activity.startActivity(intent)
call.resolve(JSObject().put("opened", true))
} catch (_: android.content.ActivityNotFoundException) {
call.reject("No browser is available to open this link.")
} catch (error: Exception) {
call.reject(error.message ?: "Could not open the link.")
}
}
.setOnCancelListener { call.resolve(JSObject().put("opened", false)) }
.show()
}
@PluginMethod
fun send(call: PluginCall) {
val input = JSONObject(call.data.toString()).apply {
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
}
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before sending.")
call.resolve(AndroidMailService.send(account, input).toJSObject())
} catch (error: Exception) {
val account = AndroidAccountVault.account()
if (account != null && isConnectivityFailure(error)) {
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
.put("id", UUID.randomUUID().toString())
.put("type", "send")
.put("data", input))
call.resolve(JSObject().put("ok", true).put("queued", true))
} else call.reject(error.message ?: "Could not send the message.")
}
}
@PluginMethod
fun listDrafts(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before opening drafts.")
call.resolve(JSObject().put("drafts", account.optJSONArray("drafts") ?: JSONArray()).put("offline", true))
} catch (error: Exception) {
call.reject(error.message ?: "Could not open drafts.")
}
}
@PluginMethod
fun saveDraft(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before saving drafts.")
val input = JSONObject(call.data.toString())
val draft = JSONObject()
.put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() })
.put("to", input.optString("to").take(4000))
.put("cc", input.optString("cc").take(4000))
.put("subject", input.optString("subject").take(998))
.put("text", input.optString("text").take(500000))
.put("updatedAt", System.currentTimeMillis())
AndroidAccountVault.saveDraft(account.optString("id"), draft)
call.resolve(draft.toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the draft.")
}
}
@PluginMethod
fun deleteDraft(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before deleting drafts.")
val id = call.getString("id") ?: throw IllegalArgumentException("Choose a draft.")
AndroidAccountVault.deleteDraft(account.optString("id"), id)
call.resolve(JSObject().put("ok", true))
} catch (error: Exception) {
call.reject(error.message ?: "Could not delete the draft.")
}
}
private fun isConnectivityFailure(error: Throwable): Boolean {
var current: Throwable? = error
while (current != null) {
if (current is java.net.UnknownHostException ||
current is java.net.ConnectException ||
current is java.net.SocketTimeoutException ||
current is javax.net.ssl.SSLException) return true
val message = current.message.orEmpty().lowercase(Locale.ROOT)
if (listOf("network is unreachable", "connection timed out", "connection refused", "unable to resolve host", "socket closed").any(message::contains)) return true
current = current.cause
}
return false
}
@PluginMethod
fun davList(call: PluginCall) {
try {
call.resolve(AndroidDavService.list().toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not list DAV accounts.")
}
}
@PluginMethod
fun davConnect(call: PluginCall) {
try {
call.resolve(AndroidDavService.connect(call.data).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not connect the DAV account.")
}
}
@PluginMethod
fun davActivate(call: PluginCall) {
try {
call.resolve(AndroidDavService.activate(call.getString("type") ?: "caldav", call.getString("id") ?: "").toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not activate the DAV account.")
}
}
@PluginMethod
fun davRemove(call: PluginCall) {
try {
call.resolve(AndroidDavService.remove(call.getString("type") ?: "caldav", call.getString("id") ?: "").toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not remove the DAV account.")
}
}
@PluginMethod
fun davSync(call: PluginCall) {
try {
call.resolve(AndroidDavService.sync(call.getString("type") ?: "caldav").toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not sync the DAV account.")
}
}
@PluginMethod
fun davSaveEvent(call: PluginCall) {
try {
val result = AndroidDavService.saveEvent(call.data)
if (result == null) call.resolve() else call.resolve(result.toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the calendar event.")
}
}
@PluginMethod
fun davDeleteEvent(call: PluginCall) {
try {
AndroidDavService.deleteEvent(call.data)
call.resolve()
} catch (error: Exception) {
call.reject(error.message ?: "Could not delete the calendar event.")
}
}
@PluginMethod
fun davSaveContact(call: PluginCall) {
try {
val result = AndroidDavService.saveContact(call.data)
if (result == null) call.resolve() else call.resolve(result.toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the contact.")
}
}
@PluginMethod
fun davDeleteContact(call: PluginCall) {
try {
AndroidDavService.deleteContact(call.data)
call.resolve()
} catch (error: Exception) {
call.reject(error.message ?: "Could not delete the contact.")
}
}
private fun normalizeAccount(input: JSONObject): JSONObject {
val email = input.optString("email").trim()
val password = input.optString("password")
val displayName = input.optString("displayName").trim().take(80)
val imapHost = input.optString("imapHost").trim()
val smtpHost = input.optString("smtpHost").trim()
require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) {
"Enter a valid email, account display name, password, and both mail server names."
}
return JSONObject()
.put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() })
.put("email", email)
.put("password", password)
.put("displayName", displayName)
.put("imapHost", imapHost)
.put("smtpHost", smtpHost)
.put("signature", input.optString("signature").take(5000))
.put("notificationsEnabled", input.optBoolean("notificationsEnabled", true))
.put("syncIntervalMinutes", input.optInt("syncIntervalMinutes", 2).also {
require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." }
})
.put("rules", normalizeRules(input.optJSONArray("rules")))
.put("imapPort", input.optInt("imapPort", 143))
.put("smtpPort", input.optInt("smtpPort", 587))
}
private fun normalizeRules(input: JSONArray?): JSONArray {
val result = JSONArray()
if (input == null) return result
require(input.length() <= 50) { "You can set up to 50 mail rules per account." }
for (index in 0 until input.length()) {
val rule = input.getJSONObject(index)
val sender = rule.optString("senderContains").trim().take(200)
val subject = rule.optString("subjectContains").trim().take(200)
val action = rule.optString("action")
val value = rule.optString("value").trim().take(200)
require((sender.isNotEmpty() || subject.isNotEmpty()) &&
action in setOf("archive", "move", "label", "flag")) {
"Mail rule ${index + 1} needs a sender or subject condition and a valid action."
}
require(action !in setOf("move", "label") || value.isNotEmpty()) {
"Mail rule ${index + 1} needs a destination folder or label."
}
require(action != "move" || !value.any { it == '\r' || it == '\n' || it == '\u0000' }) {
"Mail rule ${index + 1} has an invalid destination folder."
}
require(action != "move" || value in setOf("Inbox", "Archive", "Trash")) {
"Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash."
}
result.put(JSONObject()
.put("id", rule.optString("id").ifBlank { UUID.randomUUID().toString() })
.put("senderContains", sender)
.put("subjectContains", subject)
.put("action", action)
.put("value", value))
}
return result
}
private fun JSONObject.toJSObject(): JSObject = JSObject(toString())
companion object {
private val EMAIL = Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")
}
}
@@ -0,0 +1,55 @@
package studio.daybreak.mail
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.util.concurrent.TimeUnit
class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) {
override fun doWork(): Result {
return try {
AndroidAccountVault.initialize(applicationContext)
MailIdleService.checkSnoozeReminders(applicationContext)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
val newMessages = AndroidMailService.checkForNewMail(account)
if (newMessages > 0) {
MailIdleService.notifyNewMail(applicationContext, account, newMessages)
}
}
Result.success()
} catch (error: Exception) {
android.util.Log.w(TAG, "Periodic mail fallback sync failed", error)
Result.retry()
}
}
companion object {
private const val TAG = "EpMailFallback"
private const val UNIQUE_WORK_NAME = "ep-mail-periodic-sync"
fun schedule(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<MailFallbackWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context.applicationContext).enqueueUniquePeriodicWork(
UNIQUE_WORK_NAME,
ExistingPeriodicWorkPolicy.KEEP,
request
)
}
fun cancel(context: Context) {
WorkManager.getInstance(context.applicationContext).cancelUniqueWork(UNIQUE_WORK_NAME)
}
}
}
@@ -0,0 +1,295 @@
package studio.daybreak.mail
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import org.json.JSONObject
import javax.mail.Folder
import javax.mail.Store
class MailIdleService : Service() {
private data class Watcher(
val account: JSONObject,
val fingerprint: String,
val stopped: AtomicBoolean = AtomicBoolean(false),
@Volatile var store: Store? = null,
@Volatile var folder: Folder? = null,
@Volatile var thread: Thread? = null
) {
fun stop() {
stopped.set(true)
try { folder?.close(false) } catch (_: Exception) {}
try { store?.close() } catch (_: Exception) {}
thread?.interrupt()
}
}
private val watchers = ConcurrentHashMap<String, Watcher>()
override fun onCreate() {
super.onCreate()
AndroidAccountVault.initialize(applicationContext)
createNotificationChannels()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification())
Thread {
try {
reconcile()
if (watchers.isEmpty()) stopSelf(startId)
} catch (error: Exception) {
android.util.Log.e(TAG, "Could not start mailbox watchers", error)
}
}.start()
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
watchers.values.forEach(Watcher::stop)
watchers.clear()
super.onDestroy()
}
@Synchronized
private fun reconcile() {
val accounts = AndroidAccountVault.accounts()
val desired = LinkedHashMap<String, JSONObject>()
for (index in 0 until accounts.length().coerceAtMost(MAX_WATCHERS)) {
val account = accounts.getJSONObject(index)
desired[account.optString("id")] = account
}
for ((id, watcher) in watchers) {
val account = desired[id]
if (account == null || AndroidMailService.accountFingerprint(account) != watcher.fingerprint) {
watcher.stop()
watchers.remove(id, watcher)
}
}
for ((id, account) in desired) {
if (!watchers.containsKey(id)) startWatcher(id, account)
}
}
private fun startWatcher(id: String, account: JSONObject) {
val watcher = Watcher(account, AndroidMailService.accountFingerprint(account))
watchers[id] = watcher
val thread = Thread({
var failures = 0
while (!watcher.stopped.get()) {
try {
AndroidMailService.watchInbox(
account = account,
onNewMail = { count -> onNewMail(account, count) },
shouldStop = { watcher.stopped.get() },
onConnection = { store, folder ->
watcher.store = store
watcher.folder = folder
}
)
failures = 0
} catch (error: Exception) {
if (!watcher.stopped.get()) android.util.Log.w(TAG, "IMAP watcher disconnected for ${account.optString("email")}", error)
failures += 1
} finally {
watcher.folder = null
watcher.store = null
}
if (!watcher.stopped.get()) {
val delayMs = (15_000L * (1L shl failures.coerceAtMost(5))).coerceAtMost(5 * 60_000L)
try {
Thread.sleep(delayMs)
} catch (_: InterruptedException) {
if (watcher.stopped.get()) break
}
}
}
}, "ep-mail-idle-$id")
thread.isDaemon = true
watcher.thread = thread
thread.start()
}
private fun onNewMail(account: JSONObject, count: Int) {
notifyNewMail(this, account, count)
}
private fun foregroundNotification(): Notification = NotificationCompat.Builder(this, SERVICE_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle(getString(R.string.app_name))
.setContentText("Checking mail in the background")
.setContentIntent(appPendingIntent())
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build()
private fun appPendingIntent(): PendingIntent {
val intent = packageManager.getLaunchIntentForPackage(packageName)
?: Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
private fun createNotificationChannels() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(NotificationChannel(
SERVICE_CHANNEL_ID,
"Background mail sync",
NotificationManager.IMPORTANCE_LOW
).apply { description = "Keeps mail synchronized in the background." })
manager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"New mail",
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = "Notifies you when new mail arrives." })
}
companion object {
const val ACTION_MAIL_SYNC = "studio.daybreak.mail.MAIL_SYNC_UPDATE"
const val EXTRA_SYNC_UPDATE = "syncUpdate"
private const val TAG = "EpMailIdle"
private const val MAX_WATCHERS = 2
private const val FOREGROUND_NOTIFICATION_ID = 3410
private const val SERVICE_CHANNEL_ID = "mail-sync-service"
private const val MAIL_CHANNEL_ID = "mail-new-message"
fun start(context: Context) {
AndroidAccountVault.initialize(context)
if (AndroidAccountVault.accounts().length() == 0) return
MailFallbackWorker.schedule(context)
val intent = Intent(context, MailIdleService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
else context.startService(intent)
}
fun stop(context: Context) {
context.stopService(Intent(context, MailIdleService::class.java))
MailFallbackWorker.cancel(context)
}
fun checkSnoozeReminders(context: Context) {
AndroidAccountVault.initialize(context)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
val reminders = AndroidAccountVault.takeDueSnoozes(
account.optString("id"),
System.currentTimeMillis()
)
for (reminderIndex in 0 until reminders.length()) {
notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex))
}
}
}
fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
if (count <= 0) return
val appContext = context.applicationContext
val email = account.optString("email")
if (account.optBoolean("notificationsEnabled", true)) {
val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
notificationManager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"New mail",
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = "Notifies you when new mail arrives." })
}
val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
?: Intent(appContext, MainActivity::class.java)
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
appContext, 0, launchIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val title = if (count == 1) "New mail" else "$count new messages"
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle(title)
.setContentText(email)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.build()
try {
NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification)
} catch (error: SecurityException) {
android.util.Log.w(TAG, "Notification permission is unavailable", error)
}
}
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("newCount", count)
.put("foldersChanged", org.json.JSONArray().put("Inbox"))
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
.setPackage(appContext.packageName)
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
}
fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) {
val appContext = context.applicationContext
val email = account.optString("email")
if (account.optBoolean("notificationsEnabled", true)) {
val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
manager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"Mail reminders",
NotificationManager.IMPORTANCE_DEFAULT
))
}
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle("Mail reminder")
.setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" })
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(appPendingIntentFor(appContext))
.build()
try {
NotificationManagerCompat.from(appContext).notify(
(email + reminder.optLong("uid")).hashCode(),
notification
)
} catch (error: SecurityException) {
android.util.Log.w(TAG, "Reminder notification permission is unavailable", error)
}
}
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("snoozeReminder", true)
.put("foldersChanged", org.json.JSONArray()
.put("Snoozed")
.put(reminder.optString("folder", "Inbox")))
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
.setPackage(appContext.packageName)
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
}
private fun appPendingIntentFor(context: Context): PendingIntent {
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
?: Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
return PendingIntent.getActivity(
context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
}
}
@@ -0,0 +1,19 @@
package studio.daybreak.mail;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(EpMailPlugin.class);
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

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

After

Width:  |  Height:  |  Size: 3.9 KiB

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

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">ep-mail</string>
<string name="title_activity_main">ep-mail</string>
<string name="package_name">studio.daybreak.mail</string>
<string name="custom_url_scheme">studio.daybreak.mail</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -0,0 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
+30
View File
@@ -0,0 +1,30 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.0'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
+3
View File
@@ -0,0 +1,3 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
+22
View File
@@ -0,0 +1,22 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+5
View File
@@ -0,0 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
+16
View File
@@ -0,0 +1,16 @@
ext {
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
androidxAppCompatVersion = '1.7.1'
androidxCoordinatorLayoutVersion = '1.3.0'
androidxCoreVersion = '1.17.0'
androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
}
+8
View File
@@ -0,0 +1,8 @@
{
"appId": "studio.daybreak.mail",
"appName": "ep-mail",
"webDir": "www",
"server": {
"androidScheme": "https"
}
}
+1 -1
View File
@@ -35,4 +35,4 @@ function showDavConnect(type){
root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}}; root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}};
root.querySelector('#dav-server-url').focus(); root.querySelector('#dav-server-url').focus();
} }
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-settings,#caldav-sync,#carddav-settings,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();const type=button.id.startsWith('caldav')?'caldav':'carddav';if(button.id.endsWith('settings'))openDavManager(type);else syncDav(type)},true); document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true);
+926 -76
View File
File diff suppressed because it is too large Load Diff
+10 -1
View File
@@ -1,16 +1,25 @@
const { contextBridge, ipcRenderer } = require('electron'); const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('daybreakMail', { contextBridge.exposeInMainWorld('daybreakMail', {
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
getAccount: () => ipcRenderer.invoke('mail:get-account'), getAccount: () => ipcRenderer.invoke('mail:get-account'),
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'), listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
selectAccount: id => ipcRenderer.invoke('mail:select-account', id), selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id), removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
connect: details => ipcRenderer.invoke('mail:connect', details), connect: details => ipcRenderer.invoke('mail:connect', details),
updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details), updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details),
syncFolder: (folder, offset) => ipcRenderer.invoke('mail:sync-folder', folder, offset), syncFolder: (folder, offset, filters) => ipcRenderer.invoke('mail:sync-folder', folder, offset, filters),
listFolders: () => ipcRenderer.invoke('mail:list-folders'),
createFolder: name => ipcRenderer.invoke('mail:create-folder', { name }),
listDrafts: () => ipcRenderer.invoke('mail:list-drafts'),
saveDraft: draft => ipcRenderer.invoke('mail:save-draft', draft),
deleteDraft: id => ipcRenderer.invoke('mail:delete-draft', id),
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'), syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
updateMessage: details => ipcRenderer.invoke('mail:update-message', details), updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details), saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
openExternal: url => ipcRenderer.invoke('mail:open-external', url),
send: message => ipcRenderer.invoke('mail:send', message), send: message => ipcRenderer.invoke('mail:send', message),
disconnect: id => ipcRenderer.invoke('mail:disconnect', id), disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
davList: () => ipcRenderer.invoke('dav:list'), davList: () => ipcRenderer.invoke('dav:list'),
+6 -2
View File
@@ -19,7 +19,6 @@
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button> <button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button> <button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
<div class="rail-spacer"></div> <div class="rail-spacer"></div>
<button class="avatar tiny profile-button" title="Account settings" aria-label="Account settings"><span>•</span></button>
</aside> </aside>
<aside class="sidebar"> <aside class="sidebar">
@@ -34,6 +33,8 @@
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button> <button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button> <button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
</nav> </nav>
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<div id="custom-folders" class="folder-nav"></div>
<div class="sidebar-divider"></div> <div class="sidebar-divider"></div>
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div> <div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button> <button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
@@ -44,7 +45,7 @@
</aside> </aside>
<main class="main-area"> <main class="main-area">
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button></div></header> <header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
<section id="mail-view" class="content-view mail-layout"> <section id="mail-view" class="content-view mail-layout">
<div class="list-pane"> <div class="list-pane">
@@ -63,9 +64,12 @@
<div id="modal-root"></div> <div id="modal-root"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div> <div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="app.js"></script> <script src="app.js"></script>
<script src="platform-bridge.js"></script>
<script src="mail-ui.js"></script> <script src="mail-ui.js"></script>
<script src="productivity.js"></script> <script src="productivity.js"></script>
<script src="snooze-ui.js"></script>
<script src="account-ui.js"></script> <script src="account-ui.js"></script>
<script src="dav-ui.js"></script> <script src="dav-ui.js"></script>
<script src="shortcuts.js"></script>
</body> </body>
</html> </html>
+485 -41
View File
@@ -1,35 +1,230 @@
let connectedMailAccount = null; let connectedMailAccount = null;
let mailPageOffset = 0; let mailPageOffset = 0;
let mailTotal = 0; let mailTotal = 0;
let mailboxSyncPromise = null;
let mailboxSyncQueued = false;
let mailboxRefreshPending = false;
let folderBeforeSearch = null;
const senderBrandDomains = {
amazon: ['amazon.com', 'amazon.co.uk'],
apple: ['apple.com', 'icloud.com'],
google: ['google.com', 'gmail.com'],
microsoft: ['microsoft.com', 'outlook.com', 'live.com'],
paypal: ['paypal.com']
};
function suspiciousSenderReasons(message) {
const email = String(message.email || '').trim().toLowerCase();
const domain = email.split('@').pop() || '';
if (!domain) return [];
const reasons = [];
if (domain.includes('xn--')) reasons.push('The sender address uses an internationalized domain that may imitate another domain.');
const name = String(message.sender || '').toLowerCase();
for (const [brand, domains] of Object.entries(senderBrandDomains)) {
const brandName = new RegExp(`^(?:the\\s+)?${brand}(?:\\s+(?:customer\\s+service|support|security|account|billing|team|payments?|services?))*$`, 'i');
if (brandName.test(name) && !domains.some(allowed => domain === allowed || domain.endsWith(`.${allowed}`))) {
reasons.push(`The display name mentions ${brand}, but the sender domain is ${domain}.`);
}
}
if (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(name) && name.split('@').pop() !== domain) {
reasons.push('The address-like display name does not match the actual sender domain.');
}
return [...new Set(reasons)];
}
function inspectMailLink(raw) {
const cleaned = String(raw).replace(/[.,!?;:)\]}>"']+$/g, '');
let parsed;
try { parsed = new URL(cleaned); } catch { return null; }
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) return null;
const host = parsed.hostname.toLowerCase();
const reasons = [];
if (parsed.protocol === 'http:') reasons.push('unencrypted HTTP connection');
if (host.includes('xn--')) reasons.push('internationalized domain that may imitate another address');
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host) || host.startsWith('[')) reasons.push('IP-address destination instead of a named website');
if (['bit.ly', 't.co', 'tinyurl.com', 'is.gd', 'lnkd.in'].includes(host)) reasons.push('shortened link hides its final destination');
for (const [brand, domains] of Object.entries(senderBrandDomains)) {
const mentionsBrand = new RegExp(`(^|[.-])${brand.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}([.-]|$)`, 'i').test(host);
if (mentionsBrand && !domains.some(domain => host === domain || host.endsWith(`.${domain}`))) {
reasons.push(`hostname mentions ${brand} without using its usual domain`);
}
}
return { url: parsed.href, host, reasons };
}
function messageLinks(message) {
const bodyLinks = (message.body || []).join('\n').match(/https?:\/\/[^\s<>"']+/gi) || [];
const declaredLinks = Array.isArray(message.links) ? message.links : [];
return [...new Set([...bodyLinks, ...declaredLinks])]
.map(inspectMailLink)
.filter(Boolean)
.slice(0, 30);
}
const originalOpenMessage = openMessage;
openMessage = function (id) {
originalOpenMessage(id);
const message = messages.find(item => item.id === id);
if (!message) return;
const senderReasons = suspiciousSenderReasons(message);
const links = messageLinks(message);
const warnings = [];
if (senderReasons.length) {
warnings.push(`<section class="mail-safety-warning" role="alert"><strong>Sender details may be misleading</strong><ul>${senderReasons.map(reason => `<li>${esc(reason)}</li>`).join('')}</ul><small>Sender names and addresses can be forged. Verify the sender through a trusted channel.</small></section>`);
}
const linkCards = links.map((link, index) => `
<div class="mail-link-row ${link.reasons.length ? 'mail-link-risky' : ''}">
<div><strong>${link.reasons.length ? 'Potentially unsafe link' : 'External link'}</strong><span>${esc(link.host)}</span>
${link.reasons.length ? `<small>${esc(link.reasons.join('; '))}</small>` : ''}</div>
<button type="button" class="mail-link-open" data-mail-link="${index}">Review &amp; open</button>
</div>`).join('');
const reader = $('#reader-pane');
const header = reader.querySelector('.reader-header');
if (warnings.length && header) header.insertAdjacentHTML('afterend', warnings.join(''));
const replyBar = reader.querySelector('.reply-bar');
if (links.length && replyBar) {
replyBar.insertAdjacentHTML('beforebegin', `<section class="mail-links"><h3>Links in this message</h3>${links.some(link => link.reasons.length) ? '<p class="mail-safety-intro">Some links show warning signs. Every link requires confirmation before it opens.</p>' : ''}${linkCards}</section>`);
reader.querySelectorAll('[data-mail-link]').forEach(button => {
button.onclick = async () => {
const link = links[Number(button.dataset.mailLink)];
if (!link) return;
button.disabled = true;
try {
await window.daybreakMail.openExternal(link.url);
} catch (error) {
toast(error.message || 'Could not open this link');
} finally {
button.disabled = false;
}
};
});
}
};
let customFolders = [];
function renderCustomFolders() {
const box = $('#custom-folders');
if (!box) return;
box.replaceChildren(...customFolders.map(folder => {
const button = document.createElement('button');
button.className = 'folder custom-folder';
button.dataset.folder = folder.id;
button.classList.toggle('active', activeFolder === folder.id);
const glyph = document.createElement('span');
glyph.className = 'nav-glyph';
glyph.textContent = '▭';
const label = document.createElement('span');
label.textContent = folder.name;
button.title = folder.path;
button.append(glyph, label);
button.addEventListener('click', () => {
if ($('#filter-folder').value) { $('#filter-folder').value = ''; folderBeforeSearch = null; }
activeFolder = folder.id;
$$('.folder').forEach(item => item.classList.toggle('active', item === button));
$('#sidebar-title').textContent = folder.name;
$('#crumb-current').textContent = folder.name;
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
});
return button;
}));
}
async function loadCustomFolders() {
if (!connectedMailAccount || !window.daybreakMail?.listFolders) return;
try {
customFolders = (await window.daybreakMail.listFolders()).folders || [];
renderCustomFolders();
} catch {}
}
async function createMailFolder() {
if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
const name = prompt('New mail folder name:')?.trim();
if (!name) return;
try {
const result = await window.daybreakMail.createFolder(name);
customFolders = result.folders || customFolders;
renderCustomFolders();
toast(`Folder “${result.folder?.name || name}” created`);
} catch (error) {
toast(error.message || 'Could not create the folder');
}
}
function updateAccountCard(account) { function updateAccountCard(account) {
const card = $('#account-settings'); const card = $('#account-settings');
if (!card) return; if (!card) return;
const email = account.email || ''; const email = account.email || '';
const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase()); const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase());
const displayName = profileSettings.name.trim() || localName; const displayName = account.displayName?.trim() || profileSettings.name.trim() || localName;
const initials = displayName.split(/\s+/).filter(Boolean).map(part => part[0]).join('').slice(0, 2); const initials = displayName.split(/\s+/).filter(Boolean).map(part => part[0]).join('').slice(0, 2);
card.querySelector('.account-avatar').textContent = initials || 'M'; card.querySelector('.account-avatar').textContent = initials || 'M';
card.querySelector('.account-info strong').textContent = displayName; card.querySelector('.account-info strong').textContent = displayName;
card.querySelector('.account-info span').textContent = email; card.querySelector('.account-info span').textContent = email;
card.title = `${displayName} <${email}>`; card.title = `${displayName} <${email}>`;
if (typeof renderLabels === 'function') renderLabels();
void loadCustomFolders();
card.querySelector('.online-dot').style.background = '#70ad7b'; card.querySelector('.online-dot').style.background = '#70ad7b';
const profileButton = $('.top-avatar');
if (profileButton) {
profileButton.textContent = initials || 'M';
profileButton.title = `${displayName} <${email}>`;
profileButton.setAttribute('aria-label', `${displayName} account settings`);
}
} }
function openMailAccount(existingAccount = null) { function openMailAccount(existingAccount = null) {
const root = $('#modal-root'); const root = $('#modal-root');
const editing = Boolean(existingAccount); const editing = Boolean(existingAccount);
const displayName = profileSettings.name || ''; const displayName = existingAccount?.displayName || profileSettings.name || '';
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name"></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><p class="account-note">IMAP uses STARTTLS on port 143 · SMTP uses STARTTLS on port 587.${editing ? ' Leave the password empty to keep the saved password.' : ' Your display name is also used as the sender name.'}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save &amp; reconnect' : 'Test &amp; connect'}</button></div></div></div>`; const ruleMarkup = (existingAccount?.rules || []).map(rule => `
<div class="mail-rule-row">
<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${esc(rule.senderContains || '')}">
<input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${esc(rule.subjectContains || '')}">
<select class="mail-rule-action" aria-label="Rule action">
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')}
</select>
${rule.action==='move'
? `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${rule.value==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${rule.value==='Archive'?' selected':''}>Archive</option><option value="Trash"${rule.value==='Trash'?' selected':''}>Trash</option></select>`
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
</div>`).join('');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${esc(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save &amp; reconnect' : 'Test &amp; connect'}</button></div></div></div>`;
const close = () => { root.innerHTML = ''; }; const close = () => { root.innerHTML = ''; };
$$('.modal-close').forEach(button => button.onclick = close); $$('.modal-close').forEach(button => button.onclick = close);
$('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); }); $('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
$('#disconnect-mail').onclick = close; $('#disconnect-mail').onclick = close;
const addRuleRow = rule => {
const row = document.createElement('div');
row.className = 'mail-rule-row';
row.innerHTML = `<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${esc(rule?.senderContains || '')}"><input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${esc(rule?.subjectContains || '')}"><select class="mail-rule-action" aria-label="Rule action"><option value="archive">Archive</option><option value="move">Move to folder</option><option value="label">Apply label</option><option value="flag">Flag</option></select><input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule?.value || '')}"><button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>`;
row.querySelector('.mail-rule-action').value = rule?.action || 'archive';
$('#mail-rule-list').append(row);
};
$('#add-mail-rule').onclick = () => addRuleRow();
$('#mail-rule-list').onclick = event => {
if (event.target.closest('.remove-mail-rule')) event.target.closest('.mail-rule-row').remove();
};
$('#mail-rule-list').onchange = event => {
if (!event.target.matches('.mail-rule-action')) return;
const row = event.target.closest('.mail-rule-row');
const value = row.querySelector('.mail-rule-value');
if (event.target.value === 'move') {
const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? value.value : 'Inbox';
value.outerHTML = `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${selected==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${selected==='Archive'?' selected':''}>Archive</option><option value="Trash"${selected==='Trash'?' selected':''}>Trash</option></select>`;
} else if (value.tagName === 'SELECT') {
value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`;
}
row.querySelector('.mail-rule-value').disabled = event.target.value === 'flag';
};
$('#connect-mail').onclick = async () => { $('#connect-mail').onclick = async () => {
const button = $('#connect-mail'); const button = $('#connect-mail');
const status = $('#mail-account-status'); const status = $('#mail-account-status');
const password = $('#mail-account-password').value; const password = $('#mail-account-password').value;
const name = $('#mail-account-display-name').value.trim(); const name = $('#mail-account-display-name').value.trim();
if (!name) { status.textContent = 'Enter a display name for this mail account.'; $('#mail-account-display-name').focus(); return; }
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; } if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; }
button.disabled = true; button.disabled = true;
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…'; button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…';
@@ -38,13 +233,22 @@ function openMailAccount(existingAccount = null) {
const details = { const details = {
email: $('#mail-account-email').value, email: $('#mail-account-email').value,
password, password,
displayName: name,
imapHost: $('#mail-account-imap').value, imapHost: $('#mail-account-imap').value,
smtpHost: $('#mail-account-smtp').value smtpHost: $('#mail-account-smtp').value,
signature: $('#mail-account-signature').value,
notificationsEnabled: $('#mail-account-notifications').checked,
syncIntervalMinutes: Number($('#mail-account-sync-interval').value),
rules: [...$('#mail-rule-list').querySelectorAll('.mail-rule-row')].map(row => ({
senderContains: row.querySelector('.mail-rule-sender').value,
subjectContains: row.querySelector('.mail-rule-subject').value,
action: row.querySelector('.mail-rule-action').value,
value: row.querySelector('.mail-rule-value').value
}))
}; };
const account = editing const account = editing
? await window.daybreakMail.updateAccount(existingAccount.id, details) ? await window.daybreakMail.updateAccount(existingAccount.id, details)
: await window.daybreakMail.connect(details); : await window.daybreakMail.connect(details);
if (name) setProfileName(name);
if (editing) { if (editing) {
const accountList = await window.daybreakMail.listAccounts(); const accountList = await window.daybreakMail.listAccounts();
if (accountList.activeId === account.id) { if (accountList.activeId === account.id) {
@@ -72,60 +276,289 @@ function openMailAccount(existingAccount = null) {
}; };
$('#mail-account-email').focus(); $('#mail-account-email').focus();
} }
function mailSearchFilters() {
return {
query: $('#search').value.trim(),
sender: $('#filter-sender').value.trim(),
subject: $('#filter-subject').value.trim(),
after: $('#filter-after').value,
before: $('#filter-before').value,
hasAttachments: $('#filter-attachments').checked,
folder: $('#filter-folder').value
};
}
function renderDrafts(drafts) {
messages.splice(0, messages.length, ...drafts.map(draft => ({
id: draft.id,
sender: 'Draft',
email: draft.to || 'No recipient',
subject: draft.subject || '(no subject)',
snippet: String(draft.text || '').replace(/\s+/g, ' ').slice(0, 180) || 'No message text',
date: new Date(draft.updatedAt || Date.now()).toLocaleString(),
tags: ['Drafts'],
initials: 'D',
color: '#dce6df',
draft
})));
$('#message-list').innerHTML = messages.length ? messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft');
if (start) start.onclick = () => showCompose();
$$('.message').forEach(row => row.onclick = () => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (draft) showCompose(null, false, draft);
});
$('#reader-pane').innerHTML = emptyReader();
$('#pagination').textContent = `${messages.length} drafts`;
$('#load-more').classList.add('hidden');
}
function setupDraftComposer() {
const original = window.showCompose;
window.showCompose = (reply, forward = false, draft = null) => {
original(reply, forward);
const root = $('#modal-root');
const modal = root.querySelector('.compose-modal');
if (!modal) return;
modal.dataset.draftId = draft?.id || '';
if (draft) {
$('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || '';
$('#compose-subject').value = draft.subject || '';
$('#compose-body').value = draft.text || '';
modal.querySelector('.modal-head span').textContent = 'Edit draft';
}
const save = document.createElement('button');
save.type = 'button';
save.className = 'discard';
save.id = 'save-draft';
save.textContent = 'Save draft';
modal.querySelector('.compose-footer').insertBefore(save, $('#send'));
let saveTimer;
let closed = false;
const persist = async () => {
if (closed || !$('#compose-to')) return;
const values = {
id: modal.dataset.draftId || window.crypto.randomUUID(),
to: $('#compose-to').value,
cc: $('#compose-cc').value,
subject: $('#compose-subject').value,
text: $('#compose-body').value
};
if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return;
modal.dataset.draftId = values.id;
const result = await window.daybreakMail.saveDraft(values);
modal.dataset.draftId = result.id;
};
save.onclick = async () => {
try {
await persist();
toast('Draft saved on this device');
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not save draft'); }
};
modal.addEventListener('input', () => {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => persist().catch(error => toast(error.message || 'Could not save draft')), 700);
});
modal.querySelector('.modal-overlay')?.addEventListener('click', event => {
if (!event.target.classList.contains('modal-overlay')) return;
clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft'));
closed = true;
}, true);
root.querySelector('.modal-close')?.addEventListener('click', () => {
clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft'));
closed = true;
}, true);
$('#discard').onclick = async () => {
clearTimeout(saveTimer);
closed = true;
try {
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
root.innerHTML = '';
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete draft'); }
};
$('#send').addEventListener('click', () => {
clearTimeout(saveTimer);
closed = true;
}, true);
};
}
async function syncMailbox(showToast, options = {}) { async function syncMailbox(showToast, options = {}) {
if (mailboxSyncPromise) {
mailboxSyncQueued = true;
return mailboxSyncPromise;
}
if (!connectedMailAccount || !window.daybreakMail) { if (!connectedMailAccount || !window.daybreakMail) {
openMailAccount(); openMailAccount();
return; return;
} }
const refresh = $('#refresh'); const refresh = $('#refresh');
if (refresh) refresh.disabled = true; if (refresh) refresh.disabled = true;
try { const sync = (async () => {
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset); try {
const result = await window.daybreakMail.syncFolder(activeFolder, offset); if (activeFolder === 'Drafts') {
if (options.append) messages.push(...result.messages); const result = await window.daybreakMail.listDrafts();
else messages.splice(0, messages.length, ...result.messages); renderDrafts(result.drafts || []);
messages.forEach(message => { if (showToast) toast(`${result.drafts.length} saved drafts`);
try { return;
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]'); }
message.tags = [...new Set([...(message.tags || []), ...localTags])]; const previouslyActiveMessage = activeMessage;
} catch {} const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
}); const result = await window.daybreakMail.syncFolder(activeFolder, offset, mailSearchFilters());
if (!options.append) mailPageOffset = offset; if (options.append) messages.push(...result.messages);
mailTotal = result.total; else messages.splice(0, messages.length, ...result.messages);
activeMessage = messages[0]?.id; messages.forEach(message => {
selectedIds.clear(); try {
const unread = messages.filter(message => message.unread).length; const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
const inboxCount = $('.folder[data-folder="Inbox"] .count'); message.tags = [...new Set([...(message.tags || []), ...localTags])];
if (inboxCount) inboxCount.textContent = String(unread); } catch {}
const pagination = $('#pagination'); });
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages'; if (!options.append) mailPageOffset = offset;
const loadMore = $('#load-more'); mailTotal = result.total;
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total); activeMessage = messages.some(message => message.id === previouslyActiveMessage)
renderList(); ? previouslyActiveMessage
if (activeMessage) { : messages[0]?.id;
openMessage(activeMessage); selectedIds.clear();
const current = messages.find(message => message.id === activeMessage); const unread = messages.filter(message => message.unread).length;
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: activeFolder, action: 'unread', enabled: false }).catch(() => {}); const inboxCount = $('.folder[data-folder="Inbox"] .count');
if (inboxCount) inboxCount.textContent = String(unread);
const pagination = $('#pagination');
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = $('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
query = '';
renderList();
if (activeMessage) {
openMessage(activeMessage);
const current = messages.find(message => message.id === activeMessage);
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || activeFolder, action: 'unread', enabled: false }).catch(() => {});
}
else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount);
const status = $('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toast(`Synced ${messages.length} messages`);
} catch (error) {
toast(error.message || 'Could not sync the inbox');
} finally {
if (refresh) refresh.disabled = false;
} }
else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount); })();
if (showToast) toast(`Synced ${messages.length} messages`); mailboxSyncPromise = sync;
} catch (error) { try {
toast(error.message || 'Could not sync the inbox'); await sync;
} finally { } finally {
if (refresh) refresh.disabled = false; mailboxSyncPromise = null;
if (mailboxSyncQueued) {
mailboxSyncQueued = false;
void syncMailbox(false);
}
} }
} }
if (window.daybreakMail) { if (window.daybreakMail) {
setupDraftComposer();
let searchTimer;
const searchControls = ['#search', '#filter-folder', '#filter-sender', '#filter-subject', '#filter-after', '#filter-before', '#filter-attachments'];
$('#search-filters-toggle').onclick = () => {
const panel = $('#search-filters');
const expanded = panel.classList.toggle('hidden') === false;
$('#search-filters-toggle').setAttribute('aria-expanded', String(expanded));
};
$('#clear-search-filters').onclick = () => {
$('#filter-folder').value = '';
$('#filter-sender').value = '';
$('#filter-subject').value = '';
$('#filter-after').value = '';
$('#filter-before').value = '';
$('#filter-attachments').checked = false;
$('#search').value = '';
activeFolder = folderBeforeSearch || activeFolder;
folderBeforeSearch = null;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
$('#sidebar-title').textContent = activeFolder;
$('#crumb-current').textContent = activeFolder;
query = '';
renderList();
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
};
for (const selector of searchControls) {
$(selector).addEventListener(selector === '#search' ? 'input' : 'change', () => {
if (selector === '#filter-folder' && $('#filter-folder').value) {
if (!folderBeforeSearch) folderBeforeSearch = activeFolder;
activeFolder = $('#filter-folder').value;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
$('#sidebar-title').textContent = activeFolder;
$('#crumb-current').textContent = activeFolder;
}
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
}, selector === '#search' ? 350 : 0);
});
}
window.daybreakMail.getAppVersion().then(version => {
document.title = `ep-mail v${version}`;
}).catch(error => {
console.error('Could not read app version:', error);
});
window.daybreakMail.onSyncUpdate(update => {
if (update.accountId !== connectedMailAccount?.id) return;
if (update.error) {
toast(update.error);
return;
}
if (update.newCount || (update.foldersChanged || []).length) {
if (document.visibilityState === 'visible') {
syncMailbox(false, update.newCount ? { offset: 0 } : {});
}
else mailboxRefreshPending = true;
}
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && mailboxRefreshPending) {
mailboxRefreshPending = false;
syncMailbox(false, { offset: 0 });
}
});
window.addEventListener('focus', () => {
if (connectedMailAccount) syncMailbox(false);
});
window.addEventListener('online', () => {
if (connectedMailAccount) syncMailbox(false, { offset: 0 });
});
setInterval(() => {
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
syncMailbox(false);
}
}, 60 * 1000);
$('#account-settings').addEventListener('click', openMailAccount); $('#account-settings').addEventListener('click', openMailAccount);
$('#account-settings').addEventListener('keydown', event => { $('#account-settings').addEventListener('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); } if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); }
}); });
$('#settings-button').onclick = () => openPreferences(); $('#settings-button').onclick = () => openPreferences();
$('#refresh').onclick = () => syncMailbox(true); $('#refresh').onclick = () => syncMailbox(true);
$('#add-folder').addEventListener('click', createMailFolder);
$$('.folder').forEach(button => button.addEventListener('click', () => { $$('.folder').forEach(button => button.addEventListener('click', () => {
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred'].includes(button.dataset.folder)) { if ($('#filter-folder').value) {
$('#filter-folder').value = '';
folderBeforeSearch = null;
}
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Drafts'].includes(button.dataset.folder)) {
mailPageOffset = 0; mailPageOffset = 0;
syncMailbox(false, { offset: 0 }); syncMailbox(false, { offset: 0 });
} }
@@ -156,11 +589,22 @@ if (window.daybreakMail) {
cc: $('#compose-cc').value, cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(), subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value, text: $('#compose-body').value,
displayName: profileSettings.name displayName: connectedMailAccount.displayName || profileSettings.name
}); });
if (result.queued) {
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = '';
toast('Offline: message queued and will send when connected');
if (activeFolder === 'Drafts') void syncMailbox(false);
return;
}
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = ''; $('#modal-root').innerHTML = '';
toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved'); toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 }); if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { } catch (error) {
sendButton.disabled = false; sendButton.disabled = false;
sendButton.textContent = 'Send ↗'; sendButton.textContent = 'Send ↗';
+1197 -4
View File
File diff suppressed because it is too large Load Diff
+14 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.1.12", "version": "0.2.1",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"author": "Eternity Project", "author": "Eternity Project",
@@ -15,11 +15,17 @@
"dist:linux": "electron-builder --linux AppImage deb", "dist:linux": "electron-builder --linux AppImage deb",
"dist:linux:appimage": "electron-builder --linux AppImage", "dist:linux:appimage": "electron-builder --linux AppImage",
"dist:linux:deb": "electron-builder --linux deb", "dist:linux:deb": "electron-builder --linux deb",
"bump:build": "npm version patch --no-git-tag-version" "bump:build": "npm version patch --no-git-tag-version",
"build:android-web": "node scripts/prepare-android-web.cjs",
"android:sync": "npm run build:android-web && cap sync android",
"android:open": "npm run android:sync && cap open android",
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs"
}, },
"devDependencies": { "devDependencies": {
"@capacitor/cli": "^8.5.2",
"electron": "44.5.1", "electron": "44.5.1",
"electron-builder": "26.17.0" "electron-builder": "26.17.0",
"esbuild": "^0.28.2"
}, },
"build": { "build": {
"appId": "studio.daybreak.mail", "appId": "studio.daybreak.mail",
@@ -27,6 +33,7 @@
"asar": true, "asar": true,
"files": [ "files": [
"index.html", "index.html",
"platform-bridge.js",
"styles.css", "styles.css",
"branding.css", "branding.css",
"app.js", "app.js",
@@ -34,11 +41,13 @@
"productivity.js", "productivity.js",
"account-ui.js", "account-ui.js",
"dav-ui.js", "dav-ui.js",
"shortcuts.js",
"icon.svg", "icon.svg",
"logo-ep-daylight.svg", "logo-ep-daylight.svg",
"logo-ep-wasteland.svg", "logo-ep-wasteland.svg",
"manifest.webmanifest", "manifest.webmanifest",
"service-worker.js", "service-worker.js",
"snooze-ui.js",
"desktop/**/*" "desktop/**/*"
], ],
"directories": { "directories": {
@@ -71,6 +80,8 @@
"electron-winstaller@5.4.0": true "electron-winstaller@5.4.0": true
}, },
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
"ical.js": "^2.2.1", "ical.js": "^2.2.1",
"imapflow": "2.2.1", "imapflow": "2.2.1",
"mailparser": "3.9.33", "mailparser": "3.9.33",
+553
View File
@@ -0,0 +1,553 @@
(() => {
// node_modules/@capacitor/core/dist/index.js
var ExceptionCode;
(function(ExceptionCode2) {
ExceptionCode2["Unimplemented"] = "UNIMPLEMENTED";
ExceptionCode2["Unavailable"] = "UNAVAILABLE";
})(ExceptionCode || (ExceptionCode = {}));
var CapacitorException = class extends Error {
constructor(message, code, data) {
super(message);
this.message = message;
this.code = code;
this.data = data;
}
};
var getPlatformId = (win) => {
var _a, _b;
if (win === null || win === void 0 ? void 0 : win.androidBridge) {
return "android";
} else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {
return "ios";
} else {
return "web";
}
};
var createCapacitor = (win) => {
const capCustomPlatform = win.CapacitorCustomPlatform || null;
const cap = win.Capacitor || {};
const Plugins = cap.Plugins = cap.Plugins || {};
const getPlatform = () => {
return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win);
};
const isNativePlatform = () => getPlatform() !== "web";
const isPluginAvailable = (pluginName) => {
const plugin = registeredPlugins.get(pluginName);
if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) {
return true;
}
if (getPluginHeader(pluginName)) {
return true;
}
return false;
};
const getPluginHeader = (pluginName) => {
var _a;
return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find((h) => h.name === pluginName);
};
const handleError = (err) => win.console.error(err);
const registeredPlugins = /* @__PURE__ */ new Map();
const registerPlugin2 = (pluginName, jsImplementations = {}) => {
const registeredPlugin = registeredPlugins.get(pluginName);
if (registeredPlugin) {
console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`);
return registeredPlugin.proxy;
}
const platform = getPlatform();
const pluginHeader = getPluginHeader(pluginName);
let jsImplementation;
const loadPluginImplementation = async () => {
if (!jsImplementation && platform in jsImplementations) {
jsImplementation = typeof jsImplementations[platform] === "function" ? jsImplementation = await jsImplementations[platform]() : jsImplementation = jsImplementations[platform];
} else if (capCustomPlatform !== null && !jsImplementation && "web" in jsImplementations) {
jsImplementation = typeof jsImplementations["web"] === "function" ? jsImplementation = await jsImplementations["web"]() : jsImplementation = jsImplementations["web"];
}
return jsImplementation;
};
const createPluginMethod = (impl, prop) => {
var _a, _b;
if (pluginHeader) {
const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find((m) => prop === m.name);
if (methodHeader) {
if (methodHeader.rtype === "promise") {
return (options) => cap.nativePromise(pluginName, prop.toString(), options);
} else {
return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback);
}
} else if (impl) {
return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl);
}
} else if (impl) {
return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl);
} else {
throw new CapacitorException(`"${pluginName}" plugin is not implemented on ${platform}`, ExceptionCode.Unimplemented);
}
};
const createPluginMethodWrapper = (prop) => {
let remove;
const wrapper = (...args) => {
const p = loadPluginImplementation().then((impl) => {
const fn = createPluginMethod(impl, prop);
if (fn) {
const p2 = fn(...args);
remove = p2 === null || p2 === void 0 ? void 0 : p2.remove;
return p2;
} else {
throw new CapacitorException(`"${pluginName}.${prop}()" is not implemented on ${platform}`, ExceptionCode.Unimplemented);
}
});
if (prop === "addListener") {
p.remove = async () => remove();
}
return p;
};
wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`;
Object.defineProperty(wrapper, "name", {
value: prop,
writable: false,
configurable: false
});
return wrapper;
};
const addListener = createPluginMethodWrapper("addListener");
const removeListener = createPluginMethodWrapper("removeListener");
const addListenerNative = (eventName, callback) => {
const call = addListener({ eventName }, callback);
const remove = async () => {
const callbackId = await call;
removeListener({
eventName,
callbackId
}, callback);
};
const p = new Promise((resolve) => call.then(() => resolve({ remove })));
p.remove = async () => {
console.warn(`Using addListener() without 'await' is deprecated.`);
await remove();
};
return p;
};
const proxy = new Proxy({}, {
get(_, prop) {
switch (prop) {
// https://github.com/facebook/react/issues/20030
case "$$typeof":
return void 0;
case "toJSON":
return () => ({});
case "addListener":
return pluginHeader ? addListenerNative : addListener;
case "removeListener":
return removeListener;
default:
return createPluginMethodWrapper(prop);
}
}
});
Plugins[pluginName] = proxy;
registeredPlugins.set(pluginName, {
name: pluginName,
proxy,
platforms: /* @__PURE__ */ new Set([...Object.keys(jsImplementations), ...pluginHeader ? [platform] : []])
});
return proxy;
};
if (!cap.convertFileSrc) {
cap.convertFileSrc = (filePath) => filePath;
}
cap.getPlatform = getPlatform;
cap.handleError = handleError;
cap.isNativePlatform = isNativePlatform;
cap.isPluginAvailable = isPluginAvailable;
cap.registerPlugin = registerPlugin2;
cap.Exception = CapacitorException;
cap.DEBUG = !!cap.DEBUG;
cap.isLoggingEnabled = !!cap.isLoggingEnabled;
return cap;
};
var initCapacitorGlobal = (win) => win.Capacitor = createCapacitor(win);
var Capacitor = /* @__PURE__ */ initCapacitorGlobal(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {});
var registerPlugin = Capacitor.registerPlugin;
var WebPlugin = class {
constructor() {
this.listeners = {};
this.retainedEventArguments = {};
this.windowListeners = {};
}
addListener(eventName, listenerFunc) {
let firstListener = false;
const listeners = this.listeners[eventName];
if (!listeners) {
this.listeners[eventName] = [];
firstListener = true;
}
this.listeners[eventName].push(listenerFunc);
const windowListener = this.windowListeners[eventName];
if (windowListener && !windowListener.registered) {
this.addWindowListener(windowListener);
}
if (firstListener) {
this.sendRetainedArgumentsForEvent(eventName);
}
const remove = async () => this.removeListener(eventName, listenerFunc);
const p = Promise.resolve({ remove });
return p;
}
async removeAllListeners() {
this.listeners = {};
for (const listener in this.windowListeners) {
this.removeWindowListener(this.windowListeners[listener]);
}
this.windowListeners = {};
}
notifyListeners(eventName, data, retainUntilConsumed) {
const listeners = this.listeners[eventName];
if (!listeners) {
if (retainUntilConsumed) {
let args = this.retainedEventArguments[eventName];
if (!args) {
args = [];
}
args.push(data);
this.retainedEventArguments[eventName] = args;
}
return;
}
listeners.forEach((listener) => listener(data));
}
hasListeners(eventName) {
var _a;
return !!((_a = this.listeners[eventName]) === null || _a === void 0 ? void 0 : _a.length);
}
registerWindowListener(windowEventName, pluginEventName) {
this.windowListeners[pluginEventName] = {
registered: false,
windowEventName,
pluginEventName,
handler: (event) => {
this.notifyListeners(pluginEventName, event);
}
};
}
unimplemented(msg = "not implemented") {
return new Capacitor.Exception(msg, ExceptionCode.Unimplemented);
}
unavailable(msg = "not available") {
return new Capacitor.Exception(msg, ExceptionCode.Unavailable);
}
async removeListener(eventName, listenerFunc) {
const listeners = this.listeners[eventName];
if (!listeners) {
return;
}
const index = listeners.indexOf(listenerFunc);
if (index !== -1) {
this.listeners[eventName].splice(index, 1);
}
if (!this.listeners[eventName].length) {
this.removeWindowListener(this.windowListeners[eventName]);
}
}
addWindowListener(handle) {
window.addEventListener(handle.windowEventName, handle.handler);
handle.registered = true;
}
removeWindowListener(handle) {
if (!handle) {
return;
}
window.removeEventListener(handle.windowEventName, handle.handler);
handle.registered = false;
}
sendRetainedArgumentsForEvent(eventName) {
const args = this.retainedEventArguments[eventName];
if (!args) {
return;
}
delete this.retainedEventArguments[eventName];
args.forEach((arg) => {
this.notifyListeners(eventName, arg);
});
}
};
var encode = (str) => encodeURIComponent(str).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
var decode = (str) => str.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
var CapacitorCookiesPluginWeb = class extends WebPlugin {
async getCookies() {
const cookies = document.cookie;
const cookieMap = {};
cookies.split(";").forEach((cookie) => {
if (cookie.length <= 0)
return;
let [key, value] = cookie.replace(/=/, "CAP_COOKIE").split("CAP_COOKIE");
key = decode(key).trim();
value = decode(value).trim();
cookieMap[key] = value;
});
return cookieMap;
}
async setCookie(options) {
try {
const encodedKey = encode(options.key);
const encodedValue = encode(options.value);
const expires = options.expires ? `; expires=${options.expires.replace("expires=", "")}` : "";
const path = (options.path || "/").replace("path=", "");
const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : "";
document.cookie = `${encodedKey}=${encodedValue || ""}${expires}; path=${path}; ${domain};`;
} catch (error) {
return Promise.reject(error);
}
}
async deleteCookie(options) {
try {
document.cookie = `${options.key}=; Max-Age=0`;
} catch (error) {
return Promise.reject(error);
}
}
async clearCookies() {
try {
const cookies = document.cookie.split(";") || [];
for (const cookie of cookies) {
document.cookie = cookie.replace(/^ +/, "").replace(/=.*/, `=;expires=${(/* @__PURE__ */ new Date()).toUTCString()};path=/`);
}
} catch (error) {
return Promise.reject(error);
}
}
async clearAllCookies() {
try {
await this.clearCookies();
} catch (error) {
return Promise.reject(error);
}
}
};
var CapacitorCookies = registerPlugin("CapacitorCookies", {
web: () => new CapacitorCookiesPluginWeb()
});
var readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const base64String = reader.result;
resolve(base64String.indexOf(",") >= 0 ? base64String.split(",")[1] : base64String);
};
reader.onerror = (error) => reject(error);
reader.readAsDataURL(blob);
});
var normalizeHttpHeaders = (headers = {}) => {
const originalKeys = Object.keys(headers);
const loweredKeys = Object.keys(headers).map((k) => k.toLocaleLowerCase());
const normalized = loweredKeys.reduce((acc, key, index) => {
acc[key] = headers[originalKeys[index]];
return acc;
}, {});
return normalized;
};
var buildUrlParams = (params, shouldEncode = true) => {
if (!params)
return null;
const output = Object.entries(params).reduce((accumulator, entry) => {
const [key, value] = entry;
let encodedValue;
let item;
if (Array.isArray(value)) {
item = "";
value.forEach((str) => {
encodedValue = shouldEncode ? encodeURIComponent(str) : str;
item += `${key}=${encodedValue}&`;
});
item.slice(0, -1);
} else {
encodedValue = shouldEncode ? encodeURIComponent(value) : value;
item = `${key}=${encodedValue}`;
}
return `${accumulator}&${item}`;
}, "");
return output.substr(1);
};
var buildRequestInit = (options, extra = {}) => {
const output = Object.assign({ method: options.method || "GET", headers: options.headers }, extra);
const headers = normalizeHttpHeaders(options.headers);
const type = headers["content-type"] || "";
if (typeof options.data === "string") {
output.body = options.data;
} else if (type.includes("application/x-www-form-urlencoded")) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(options.data || {})) {
params.set(key, value);
}
output.body = params.toString();
} else if (type.includes("multipart/form-data") || options.data instanceof FormData) {
const form = new FormData();
if (options.data instanceof FormData) {
options.data.forEach((value, key) => {
form.append(key, value);
});
} else {
for (const key of Object.keys(options.data)) {
form.append(key, options.data[key]);
}
}
output.body = form;
const headers2 = new Headers(output.headers);
headers2.delete("content-type");
output.headers = headers2;
} else if (type.includes("application/json") || typeof options.data === "object") {
output.body = JSON.stringify(options.data);
}
return output;
};
var CapacitorHttpPluginWeb = class extends WebPlugin {
/**
* Perform an Http request given a set of options
* @param options Options to build the HTTP request
*/
async request(options) {
const requestInit = buildRequestInit(options, options.webFetchExtra);
const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams);
const url = urlParams ? `${options.url}?${urlParams}` : options.url;
const response = await fetch(url, requestInit);
const contentType = response.headers.get("content-type") || "";
let { responseType = "text" } = response.ok ? options : {};
if (contentType.includes("application/json")) {
responseType = "json";
}
let data;
let blob;
switch (responseType) {
case "arraybuffer":
case "blob":
blob = await response.blob();
data = await readBlobAsBase64(blob);
break;
case "json":
data = await response.json();
break;
case "document":
case "text":
default:
data = await response.text();
}
const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
return {
data,
headers,
status: response.status,
url: response.url
};
}
/**
* Perform an Http GET request given a set of options
* @param options Options to build the HTTP request
*/
async get(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "GET" }));
}
/**
* Perform an Http POST request given a set of options
* @param options Options to build the HTTP request
*/
async post(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "POST" }));
}
/**
* Perform an Http PUT request given a set of options
* @param options Options to build the HTTP request
*/
async put(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "PUT" }));
}
/**
* Perform an Http PATCH request given a set of options
* @param options Options to build the HTTP request
*/
async patch(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "PATCH" }));
}
/**
* Perform an Http DELETE request given a set of options
* @param options Options to build the HTTP request
*/
async delete(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "DELETE" }));
}
};
var CapacitorHttp = registerPlugin("CapacitorHttp", {
web: () => new CapacitorHttpPluginWeb()
});
var SystemBarsStyle;
(function(SystemBarsStyle2) {
SystemBarsStyle2["Dark"] = "DARK";
SystemBarsStyle2["Light"] = "LIGHT";
SystemBarsStyle2["Default"] = "DEFAULT";
})(SystemBarsStyle || (SystemBarsStyle = {}));
var SystemBarType;
(function(SystemBarType2) {
SystemBarType2["StatusBar"] = "StatusBar";
SystemBarType2["NavigationBar"] = "NavigationBar";
})(SystemBarType || (SystemBarType = {}));
var SystemBarsPluginWeb = class extends WebPlugin {
async setStyle() {
this.unavailable("not available for web");
}
async setAnimation() {
this.unavailable("not available for web");
}
async show() {
this.unavailable("not available for web");
}
async hide() {
this.unavailable("not available for web");
}
};
var SystemBars = registerPlugin("SystemBars", {
web: () => new SystemBarsPluginWeb()
});
// scripts/android-bridge.js
var EpMail = registerPlugin("EpMail");
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") {
window.daybreakMail = {
getAppVersion: () => EpMail.getAppVersion().then((result) => result.version),
getAccount: () => EpMail.getAccount(),
listAccounts: () => EpMail.listAccounts(),
selectAccount: (id) => EpMail.selectAccount({ id }),
removeAccount: (id) => EpMail.removeAccount({ id }),
connect: (details) => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
listFolders: () => EpMail.listFolders(),
createFolder: (name) => EpMail.createFolder({ name }),
listDrafts: () => EpMail.listDrafts(),
saveDraft: (draft) => EpMail.saveDraft(draft),
deleteDraft: (id) => EpMail.deleteDraft({ id }),
syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }),
onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback),
updateMessage: (details) => EpMail.updateMessage(details),
setSnooze: (details) => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
saveAttachment: (details) => EpMail.saveAttachment(details),
openExternal: (url) => EpMail.openExternal({ url }),
send: (message) => EpMail.send(message),
disconnect: (id) => EpMail.removeAccount({ id }),
davList: () => EpMail.davList(),
davConnect: (config) => EpMail.davConnect(config),
davActivate: (type, id) => EpMail.davActivate({ type, id }),
davRemove: (type, id) => EpMail.davRemove({ type, id }),
davSync: (type) => EpMail.davSync({ type }),
davSaveEvent: (event) => EpMail.davSaveEvent(event),
davDeleteEvent: (remote) => EpMail.davDeleteEvent(remote),
davSaveContact: (contact) => EpMail.davSaveContact(contact),
davDeleteContact: (remote) => EpMail.davDeleteContact(remote)
};
}
})();
/*! Bundled license information:
@capacitor/core/dist/index.js:
(*! Capacitor: https://capacitorjs.com/ - MIT License *)
*/
+8 -9
View File
@@ -11,10 +11,10 @@ productWrite(productKeys.contacts, savedContacts);
let savedEvents = productRead(productKeys.events, []); let savedEvents = productRead(productKeys.events, []);
let customLabels = productRead(productKeys.labels, []); let customLabels = productRead(productKeys.labels, []);
let snoozedIds = productRead(productKeys.snoozed, []); let snoozedIds = productRead(productKeys.snoozed, []);
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; $$('.profile-button').forEach(b => b.textContent = profileSettings.name.split(/\s+/).filter(Boolean).map(x=>x[0]).join('').slice(0,2).toUpperCase() || '•'); if (connectedMailAccount) updateAccountCard(connectedMailAccount); } function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); }
function openAccountSettings() { function openAccountSettings() {
const root=$('#modal-root'); const root=$('#modal-root');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting and profile.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`; root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
const close=()=>root.innerHTML=''; const close=()=>root.innerHTML='';
$$('.modal-close').forEach(button=>button.onclick=close); $$('.modal-close').forEach(button=>button.onclick=close);
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; $('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
@@ -34,17 +34,16 @@ function openPreferences() {
$('#theme-select').focus(); $('#theme-select').focus();
} }
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); } function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); }
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-settings">CalDAV servers</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}} function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()} function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()}
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-settings">CardDAV servers</button><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}} function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}}
function renderLabels(){const box=$('#custom-labels');if(!box)return;box.innerHTML=customLabels.map(label=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})} function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
function renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})}
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')} function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')}
function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:activeFolder,action,enabled:action==='star'?!message.star:true})}return Promise.resolve()} function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toast('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}} async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}}
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';}); document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()} function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
const baseMessageRenderer=renderList; const baseMessageRenderer=renderList;
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?snoozedIds.includes(m.id):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()}; renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels,...accountRuleLabels()].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?Boolean(m.snoozedUntil):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()};
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true); document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true);
+39
View File
@@ -0,0 +1,39 @@
import { Capacitor, registerPlugin } from '@capacitor/core';
const EpMail = registerPlugin('EpMail');
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
window.daybreakMail = {
getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
getAccount: () => EpMail.getAccount(),
listAccounts: () => EpMail.listAccounts(),
selectAccount: id => EpMail.selectAccount({ id }),
removeAccount: id => EpMail.removeAccount({ id }),
connect: details => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
listFolders: () => EpMail.listFolders(),
createFolder: name => EpMail.createFolder({ name }),
listDrafts: () => EpMail.listDrafts(),
saveDraft: draft => EpMail.saveDraft(draft),
deleteDraft: id => EpMail.deleteDraft({ id }),
syncInbox: () => EpMail.syncFolder({ folder: 'Inbox', offset: 0 }),
onSyncUpdate: callback => EpMail.addListener('mailSyncUpdate', callback),
updateMessage: details => EpMail.updateMessage(details),
setSnooze: details => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
saveAttachment: details => EpMail.saveAttachment(details),
openExternal: url => EpMail.openExternal({ url }),
send: message => EpMail.send(message),
disconnect: id => EpMail.removeAccount({ id }),
davList: () => EpMail.davList(),
davConnect: config => EpMail.davConnect(config),
davActivate: (type, id) => EpMail.davActivate({ type, id }),
davRemove: (type, id) => EpMail.davRemove({ type, id }),
davSync: type => EpMail.davSync({ type }),
davSaveEvent: event => EpMail.davSaveEvent(event),
davDeleteEvent: remote => EpMail.davDeleteEvent(remote),
davSaveContact: contact => EpMail.davSaveContact(contact),
davDeleteContact: remote => EpMail.davDeleteContact(remote)
};
}
+17
View File
@@ -0,0 +1,17 @@
const { spawnSync } = require('node:child_process');
const path = require('node:path');
const androidDir = path.resolve(__dirname, '..', 'android');
const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';
const result = spawnSync(gradleWrapper, ['assembleDebug'], {
cwd: androidDir,
stdio: 'inherit',
shell: process.platform === 'win32'
});
if (result.error) {
console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`);
process.exitCode = 1;
} else {
process.exitCode = result.status ?? 1;
}
+45
View File
@@ -0,0 +1,45 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const esbuild = require('esbuild');
const root = path.resolve(__dirname, '..');
const output = path.join(root, 'www');
const assets = [
'index.html',
'styles.css',
'branding.css',
'app.js',
'mail-ui.js',
'productivity.js',
'account-ui.js',
'dav-ui.js',
'shortcuts.js',
'icon.svg',
'logo-ep-daylight.svg',
'logo-ep-wasteland.svg',
'manifest.webmanifest',
'service-worker.js',
'snooze-ui.js'
];
async function prepare() {
await fs.rm(output, { recursive: true, force: true });
await fs.mkdir(output, { recursive: true });
for (const asset of assets) {
await fs.copyFile(path.join(root, asset), path.join(output, asset));
}
const bridgePath = path.join(root, 'platform-bridge.js');
await esbuild.build({
entryPoints: [path.join(root, 'scripts', 'android-bridge.js')],
outfile: bridgePath,
bundle: true,
platform: 'browser',
format: 'iife'
});
await fs.copyFile(bridgePath, path.join(output, 'platform-bridge.js'));
}
prepare().catch(error => {
console.error('Could not prepare Android web assets:', error);
process.exitCode = 1;
});
+2 -2
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v2'; const CACHE='ep-mail-v4';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./mail-ui.js','./productivity.js','./account-ui.js','./dav-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
+102
View File
@@ -0,0 +1,102 @@
// Configurable keyboard shortcuts for common mail actions.
const shortcutStorageKey = 'daybreak-shortcuts';
const shortcutActions = [
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
];
function normalizeShortcut(value) {
const text = String(value || '').trim();
if (!text) return '';
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
const key = parts.pop() || '+';
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
}
function loadShortcuts() {
let saved = {};
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
return Object.fromEntries(shortcutActions.map(action => [
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
]));
}
function eventShortcut(event) {
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
const printable = event.key.length === 1;
if (event.shiftKey && !printable) mods.push('Shift');
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
}
function moveMessageSelection(step) {
if (!messages.length) return;
const index = messages.findIndex(message => message.id === activeMessage);
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
}
document.addEventListener('keydown', event => {
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
const target = event.target;
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
const pressed = eventShortcut(event);
if (!pressed) return;
const shortcuts = loadShortcuts();
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
if (!action) return;
event.preventDefault();
action.run();
});
if (typeof openPreferences === 'function') {
const baseOpenPreferences = openPreferences;
openPreferences = function () {
baseOpenPreferences();
const fields = $('#modal-root .compose-fields');
const save = $('#save-appearance');
if (!fields || !save) return;
const shortcuts = loadShortcuts();
const section = document.createElement('div');
section.className = 'shortcut-settings';
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
fields.append(section);
section.addEventListener('keydown', event => {
const input = event.target.closest('.shortcut-input');
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
event.preventDefault();
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
const combo = eventShortcut(event);
if (combo) input.value = combo;
});
$('#reset-shortcuts').onclick = () => {
section.querySelectorAll('.shortcut-input').forEach(input => {
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
});
};
const baseSave = save.onclick;
save.onclick = event => {
const values = {};
const used = new Map();
for (const input of section.querySelectorAll('.shortcut-input')) {
const value = normalizeShortcut(input.value);
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
if (value) used.set(value, label);
values[input.dataset.action] = value;
}
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
baseSave?.call(save, event);
};
};
}
+178
View File
@@ -0,0 +1,178 @@
function localDateTimeValue(date) {
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
return local.toISOString().slice(0, 16);
}
function nextMorning(daysAhead) {
const date = new Date();
date.setDate(date.getDate() + daysAhead);
date.setHours(9, 0, 0, 0);
if (date <= new Date()) date.setDate(date.getDate() + 1);
return date;
}
function openSnoozeDialog(items) {
const eligible = items.filter(message => message?.uid && connectedMailAccount);
if (!eligible.length) {
toast('Snoozing is available for messages in a connected mailbox.');
return;
}
const root = $('#modal-root');
const tomorrow = nextMorning(1);
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</button></div></div></div>`;
const close = () => { root.innerHTML = ''; };
root.querySelectorAll('.modal-close').forEach(button => button.onclick = close);
root.querySelector('.modal-overlay').onclick = event => {
if (event.target.classList.contains('modal-overlay')) close();
};
const schedule = async dueAt => {
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
$('#snooze-status').textContent = 'Choose a reminder time in the future.';
return;
}
const buttons = [...root.querySelectorAll('button')];
buttons.forEach(button => { button.disabled = true; });
try {
for (const message of eligible) {
const sourceFolder = message.sourceFolder ||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(activeFolder) ? activeFolder : 'Inbox');
await window.daybreakMail.setSnooze({
uid: message.uid,
folder: sourceFolder,
sourceFolder,
dueAt,
subject: message.subject
});
}
close();
toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
selectedIds.clear();
await syncMailbox(false, { offset: 0 });
} catch (error) {
$('#snooze-status').textContent = error.message || 'Could not set the reminder.';
buttons.forEach(button => { button.disabled = false; });
}
};
root.querySelectorAll('[data-snooze-at]').forEach(button => {
button.onclick = () => schedule(Number(button.dataset.snoozeAt));
});
$('#snooze-custom').onclick = () => schedule(new Date($('#snooze-custom-time').value).getTime());
$('#snooze-custom-time').focus();
}
function unsnoozeMessage(message) {
const sourceFolder = message.sourceFolder || 'Inbox';
window.daybreakMail.setSnooze({
uid: message.uid,
sourceFolder,
dueAt: null
}).then(async () => {
toast('Message returned to its mailbox');
await syncMailbox(false, { offset: 0 });
}).catch(error => toast(error.message || 'Could not return the message'));
}
function showMessageActions(message) {
const root = $('#modal-root');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
root.querySelector('.modal-overlay').onclick = event => {
if (event.target.classList.contains('modal-overlay')) root.innerHTML = '';
};
}
const renderListBeforeSnooze = renderList;
renderList = function () {
if (activeFolder === 'Snoozed') {
const originalMessages = messages.slice();
const snoozedMessages = messages.filter(message => message.snoozedUntil);
messages.splice(0, messages.length, ...snoozedMessages);
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
const folder = activeFolder;
activeFolder = 'Inbox';
baseMessageRenderer();
activeFolder = folder;
originalFlags.forEach(([message, archived, deleted]) => {
message.archived = archived;
message.deleted = deleted;
});
messages.splice(0, messages.length, ...originalMessages);
for (const row of $$('.message')) {
const message = messages.find(item => item.id === Number(row.dataset.id));
if (!message?.snoozedUntil) continue;
const due = new Date(message.snoozedUntil);
row.title = `Reminder ${due.toLocaleString()}`;
const snippet = row.querySelector('.snippet');
if (snippet) snippet.textContent = `Reminder · ${due.toLocaleString()} · ${message.snippet}`;
}
return;
}
renderListBeforeSnooze();
};
const openMessageBeforeSnooze = openMessage;
openMessage = function (id) {
openMessageBeforeSnooze(id);
const message = messages.find(item => item.id === id);
const tools = $('.reader-tools');
if (!message || !tools) return;
const snoozed = activeFolder === 'Snoozed';
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
};
document.addEventListener('DOMContentLoaded', () => {
$('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
if (window.daybreakMail?.checkSnoozeReminders) {
const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
.catch(error => console.error('Could not check mail reminders:', error));
void checkReminders();
setInterval(checkReminders, 60 * 1000);
}
});
document.addEventListener('click', event => {
const action = event.target.closest('[data-message-action]');
const more = event.target.closest('.reader-tools button[title="More"]');
const snooze = event.target.closest('#reader-snooze, #snooze-selected');
const unsnooze = event.target.closest('#reader-unsnooze');
if (!more && !snooze && !unsnooze && !action) return;
event.preventDefault();
event.stopImmediatePropagation();
if (action) {
const message = messages.find(item => item.id === activeMessage);
$('#modal-root').innerHTML = '';
if (!message) return;
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
else if (action.dataset.messageAction === 'label') addMessageLabel(message);
else {
const type = action.dataset.messageAction;
messageAction(message, type).then(() => {
if (type === 'unread') message.unread = true;
if (type === 'inbox') message.archived = false;
renderList();
toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
}).catch(error => toast(error.message || 'Could not update the message'));
}
return;
}
if (unsnooze) {
const message = messages.find(item => item.id === activeMessage);
if (message) unsnoozeMessage(message);
return;
}
if (snooze?.id === 'snooze-selected') {
openSnoozeDialog(messages.filter(message => selectedIds.has(message.id)));
return;
}
if (more) {
const message = messages.find(item => item.id === activeMessage);
if (message) showMessageActions(message);
return;
}
const message = messages.find(item => item.id === activeMessage);
if (message) openSnoozeDialog([message]);
}, true);
+13
View File
@@ -114,3 +114,16 @@ 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}
.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}
@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}}
.search-filters{position:absolute;right:78px;top:calc(100% + 8px);z-index:12;display:grid;grid-template-columns:1fr 1fr;gap:10px;width:min(360px,calc(100vw - 32px));padding:14px;border:1px solid var(--border,#d8ddd5);border-radius:12px;background:var(--panel,#fff);box-shadow:0 8px 28px #17201724}.search-filters.hidden{display:none}.search-filters label{display:grid;gap:4px;font-size:12px}.search-filters input,.search-filters select{min-width:0;border:1px solid var(--border,#d8ddd5);border-radius:7px;padding:7px;background:transparent;color:inherit;font:inherit}.search-filters .filter-checkbox{display:flex;align-items:center;gap:7px}.search-filters .filter-checkbox input{min-width:auto}.search-filters .text-button{grid-column:1/-1;justify-self:start}.top-actions{position:relative}
body.ep-wasteland .search-filters{background:#211c18;border-color:#4a3f33;color:#d4cbbc}body.ep-wasteland .search-filters input,body.ep-wasteland .search-filters select{border-color:#4a3f33;color:#d4cbbc}
body.ep-daylight .search-filters{background:#fbfbf6;border-color:#b9c5bc;color:#263a3d}
.mail-safety-warning{margin:10px 16px;padding:12px 14px;border:1px solid #d69b43;border-left:4px solid #b87321;border-radius:8px;background:#fff6df;color:#5b3c17;font-size:12px}.mail-safety-warning strong{display:block}.mail-safety-warning ul{margin:7px 0;padding-left:18px}.mail-safety-warning small{display:block;line-height:1.4}.mail-links{padding:12px 16px;border-top:1px solid var(--line,#eaede8)}.mail-links h3{margin:0 0 8px;font-size:12px}.mail-safety-intro{font-size:11px;color:#8d4a16}.mail-link-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 10px;margin-top:6px;border:1px solid var(--line,#eaede8);border-radius:8px;font-size:11px}.mail-link-row>div{min-width:0;display:grid;gap:3px}.mail-link-row span,.mail-link-row small{overflow-wrap:anywhere;color:#727970}.mail-link-risky{border-color:#d69b43;background:#fff8ea}.mail-link-open{flex:none;border:1px solid #9ba99b;border-radius:6px;background:transparent;padding:6px 8px;font-size:10px}.mail-link-open:disabled{opacity:.55;cursor:wait}
body.ep-wasteland .mail-safety-warning{background:#392719;border-color:#a8793e;color:#f0d4a3}body.ep-wasteland .mail-link-row{border-color:#4a3f33}body.ep-wasteland .mail-link-risky{background:#392719;border-color:#a8793e}body.ep-wasteland .mail-link-row span,body.ep-wasteland .mail-link-row small{color:#cbbba0}
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
+26
View File
@@ -0,0 +1,26 @@
async function openAccountManager(){
const root=$('#modal-root');
try{
const data=await window.daybreakMail.listAccounts();
const accounts=data.accounts||[];
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.displayName||account.email)}</strong><small>${esc(account.email)} · ${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
const close=()=>root.innerHTML='';
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
root.querySelector('#add-mail-account').onclick=()=>{close();openMailAccount()};
root.onclick=async event=>{
const switchButton=event.target.closest('[data-switch-account]');
if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
const davButton=event.target.closest('[data-open-dav]');
if(davButton){close();openDavManager(davButton.dataset.openDav);return}
const editButton=event.target.closest('[data-edit-account]');
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)openMailAccount(account);return}
const removeButton=event.target.closest('[data-remove-account]');
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;connectedMailAccount=active;if(active){updateAccountCard(active);close();activeFolder='Inbox';mailPageOffset=0;await syncMailbox(false,{offset:0})}else{updateAccountCard({email:'Connect a mailbox',imapHost:''});messages.splice(0,messages.length);renderList();$('#reader-pane').innerHTML=emptyReader();toast('Mail account removed');openAccountManager()}}catch(error){toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
};
}catch(error){toast(error.message||'Could not load mail accounts')}
}
document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
+17
View File
@@ -0,0 +1,17 @@
if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{}));
const messages = [];
const contacts=[];
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}
function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()}
function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div><div class="reader-body">${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('')}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)}
function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)}
function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send&nbsp; ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()}
function switchView(view){activeView=view;$$('.rail-button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('.mail-layout').classList.toggle('hidden',view!=='mail');$('#calendar-view').classList.toggle('hidden',view!=='calendar');$('#contacts-view').classList.toggle('hidden',view!=='contacts');$('#sidebar-title').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';$('#crumb-parent').textContent=view==='mail'?'Mail':'Workspace';$('#crumb-current').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';}
function renderCalendar(){}
function showEvent(){}
function renderContacts(){}
function showContact(){}
$$('.folder').forEach(b=>b.onclick=()=>{activeFolder=b.dataset.folder;$$('.folder').forEach(x=>x.classList.toggle('active',x===b));$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()});$$('.rail-button[data-view]').forEach(b=>b.onclick=()=>{switchView(b.dataset.view);if(b.dataset.view==='calendar')renderCalendar();if(b.dataset.view==='contacts')renderContacts()});function applyTheme(theme,showToast=false){const themes=['daylight','wasteland','ep-wasteland','ep-daylight'];const selected=themes.includes(theme)?theme:'ep-wasteland';const info={daylight:{name:'Eternity Daylight',icon:'☼'},wasteland:{name:'Wasteland',icon:'☾'},'ep-wasteland':{name:'EP Wasteland',icon:'◈'},'ep-daylight':{name:'EP Daylight',icon:'☀'}}[selected];document.body.classList.remove('wasteland','ep-wasteland','ep-daylight');if(selected!=='daylight')document.body.classList.add(selected);document.querySelector('meta[name=theme-color]')?.setAttribute('content',selected==='ep-wasteland'?'#161210':selected==='ep-daylight'?'#f1f1e9':selected==='wasteland'?'#eee8db':'#f4f5f1');localStorage.setItem('daybreak-theme',selected);const brandLogo=$("#brand-logo");if(brandLogo)brandLogo.src=selected==='ep-wasteland'?'logo-ep-wasteland.svg':'logo-ep-daylight.svg';if(showToast)toast(`${info.name} theme`)}applyTheme(localStorage.getItem('daybreak-theme')||'ep-wasteland');$('#search').oninput=e=>{query=e.target.value;renderList()};$('#search').addEventListener('keydown',e=>{if(e.key==='Escape'){e.target.value='';query='';renderList()}});$('#compose').onclick=()=>showCompose();$('#refresh').onclick=()=>{toast('You’re all up to date');renderList()};$('#select-all').onclick=()=>{const visible=messages.filter(m=>!m.archived&&!m.deleted);const all=visible.every(m=>selectedIds.has(m.id));visible.forEach(m=>all?selectedIds.delete(m.id):selectedIds.add(m.id));renderList()};$('#archive-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.archived=true);selectedIds.clear();renderList();toast('Selected messages archived')};$('#delete-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.deleted=true);selectedIds.clear();renderList();toast('Selected messages moved to Trash')};$('#sidebar-menu').onclick=()=>toast('More mailbox options');$$('.settings-button,.help-button,.tiny-plus,.text-button').forEach(b=>b.onclick=()=>toast('You’re all caught up'));document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#search').focus()}if(e.key==='Escape')$('#modal-root').innerHTML=''});$('#today-label').textContent=new Intl.DateTimeFormat('en-US',{weekday:'long',month:'long',day:'numeric'}).format(new Date()).toUpperCase();$('#reader-pane').innerHTML=emptyReader();renderList();openMessage(activeMessage);
+30
View File
@@ -0,0 +1,30 @@
.brand-mark,
body.wasteland .brand-mark,
body.ep-wasteland .brand-mark,
body.ep-daylight .brand-mark {
background: transparent !important;
box-shadow: none !important;
border-radius: 0;
}
.brand-mark img {
display: block;
width: 35px;
height: 35px;
object-fit: contain;
}
.settings-select {
flex: 1;
border: 0;
padding: 5px 0;
background: transparent;
color: var(--text);
font: inherit;
text-align: right;
}
body.ep-wasteland .settings-select,
body.ep-daylight .settings-select {
color-scheme: inherit;
}
+38
View File
@@ -0,0 +1,38 @@
function davTypeName(type){return type==='caldav'?'calendar':'contacts'}
async function syncDav(type, uploadLocal=false){
try{
const localOnly=type==='caldav'?savedEvents.filter(item=>!item._dav):savedContacts.filter(item=>!item._dav);
const result=await window.daybreakMail.davSync(type);
if(type==='caldav'){
if(uploadLocal)for(const event of localOnly){try{event._dav=await window.daybreakMail.davSaveEvent(event)}catch(error){toast(`Could not upload “${event.title}”: ${error.message}`)}}
savedEvents=[...localOnly,...result.items];
productWrite(productKeys.events,savedEvents);renderCalendar();toast(`Synced ${result.items.length} calendar events`);
}else{
if(uploadLocal)for(const contact of localOnly){try{contact._dav=await window.daybreakMail.davSaveContact(contact)}catch(error){toast(`Could not upload “${contact.name}”: ${error.message}`)}}
savedContacts=[...localOnly,...result.items];
productWrite(productKeys.contacts,savedContacts);renderContacts();toast(`Synced ${result.items.length} contacts`);
}
}catch(error){toast(error.message||`Could not sync ${davTypeName(type)}`)}
}
async function openDavManager(type){
const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
try{
const data=await window.daybreakMail.davList(),accounts=data[type]||[],activeId=data[type==='caldav'?'activeCaldavId':'activeCarddavId'];
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.username)}</strong><small>${esc(account.serverUrl)} · ${account.collections.length} ${type==='caldav'?'calendars':'address books'}</small><small>${account.collections.map(collection=>esc(collection.name)).join(', ')}</small></div><div class="account-row-actions">${account.id===activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-dav-activate="${esc(account.id)}">Use</button>`}<button class="discard" data-dav-remove="${esc(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${label} servers</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||`<p class="account-note">No ${label} server connected.</p>`}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-dav-server">+ Add server</button></div></div></div>`;
const close=()=>root.innerHTML='';root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
root.querySelector('#add-dav-server').onclick=()=>showDavConnect(type);
root.onclick=async event=>{
const activate=event.target.closest('[data-dav-activate]');if(activate){try{await window.daybreakMail.davActivate(type,activate.dataset.davActivate);close();await syncDav(type)}catch(error){toast(error.message)}return}
const remove=event.target.closest('[data-dav-remove]');if(remove){if(!confirm(`Remove this ${label} server from ep-mail?`))return;try{const result=await window.daybreakMail.davRemove(type,remove.dataset.davRemove);close();if(result.activeId)await syncDav(type);else if(type==='caldav'){savedEvents=savedEvents.filter(item=>!item._dav);productWrite(productKeys.events,savedEvents);renderCalendar()}else{savedContacts=savedContacts.filter(item=>!item._dav);productWrite(productKeys.contacts,savedContacts);renderContacts()}await openDavManager(type)}catch(error){toast(error.message)} }
};
}catch(error){toast(error.message||`Could not load ${label} servers`)}
}
function showDavConnect(type){
const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Connect ${label} server</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Use the DAV server URL from your provider. Your password is encrypted in the OS credential store; secure HTTPS is required.</p><label class="compose-line"><span>Server URL</span><input id="dav-server-url" type="url" placeholder="https://dav.example.com/remote.php/dav"></label><label class="compose-line"><span>Username</span><input id="dav-username" autocomplete="username" placeholder="name@example.com"></label><label class="compose-line"><span>Password</span><input id="dav-password" type="password" autocomplete="current-password" placeholder="App password"></label><p id="dav-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="dav-cancel">Cancel</button><button class="send-button" id="dav-connect">Test &amp; connect</button></div></div></div>`;
const close=()=>root.innerHTML='';root.querySelector('.modal-close').onclick=close;root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};root.querySelector('#dav-cancel').onclick=close;
root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}};
root.querySelector('#dav-server-url').focus();
}
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true);
+10
View File
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="12" fill="#0a0c0b"/>
<g fill="none" stroke="#eee9de">
<circle cx="32" cy="32" r="27" stroke-width="3"/>
<path d="M32 4v56" stroke-width="4"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="3" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="3" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="2" opacity=".75" transform="rotate(45 32 32)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 552 B

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

After

Width:  |  Height:  |  Size: 534 B

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

After

Width:  |  Height:  |  Size: 534 B

+621
View File
@@ -0,0 +1,621 @@
let connectedMailAccount = null;
let mailPageOffset = 0;
let mailTotal = 0;
let mailboxSyncPromise = null;
let mailboxSyncQueued = false;
let mailboxRefreshPending = false;
let folderBeforeSearch = null;
const senderBrandDomains = {
amazon: ['amazon.com', 'amazon.co.uk'],
apple: ['apple.com', 'icloud.com'],
google: ['google.com', 'gmail.com'],
microsoft: ['microsoft.com', 'outlook.com', 'live.com'],
paypal: ['paypal.com']
};
function suspiciousSenderReasons(message) {
const email = String(message.email || '').trim().toLowerCase();
const domain = email.split('@').pop() || '';
if (!domain) return [];
const reasons = [];
if (domain.includes('xn--')) reasons.push('The sender address uses an internationalized domain that may imitate another domain.');
const name = String(message.sender || '').toLowerCase();
for (const [brand, domains] of Object.entries(senderBrandDomains)) {
const brandName = new RegExp(`^(?:the\\s+)?${brand}(?:\\s+(?:customer\\s+service|support|security|account|billing|team|payments?|services?))*$`, 'i');
if (brandName.test(name) && !domains.some(allowed => domain === allowed || domain.endsWith(`.${allowed}`))) {
reasons.push(`The display name mentions ${brand}, but the sender domain is ${domain}.`);
}
}
if (/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(name) && name.split('@').pop() !== domain) {
reasons.push('The address-like display name does not match the actual sender domain.');
}
return [...new Set(reasons)];
}
function inspectMailLink(raw) {
const cleaned = String(raw).replace(/[.,!?;:)\]}>"']+$/g, '');
let parsed;
try { parsed = new URL(cleaned); } catch { return null; }
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) return null;
const host = parsed.hostname.toLowerCase();
const reasons = [];
if (parsed.protocol === 'http:') reasons.push('unencrypted HTTP connection');
if (host.includes('xn--')) reasons.push('internationalized domain that may imitate another address');
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(host) || host.startsWith('[')) reasons.push('IP-address destination instead of a named website');
if (['bit.ly', 't.co', 'tinyurl.com', 'is.gd', 'lnkd.in'].includes(host)) reasons.push('shortened link hides its final destination');
for (const [brand, domains] of Object.entries(senderBrandDomains)) {
const mentionsBrand = new RegExp(`(^|[.-])${brand.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}([.-]|$)`, 'i').test(host);
if (mentionsBrand && !domains.some(domain => host === domain || host.endsWith(`.${domain}`))) {
reasons.push(`hostname mentions ${brand} without using its usual domain`);
}
}
return { url: parsed.href, host, reasons };
}
function messageLinks(message) {
const bodyLinks = (message.body || []).join('\n').match(/https?:\/\/[^\s<>"']+/gi) || [];
const declaredLinks = Array.isArray(message.links) ? message.links : [];
return [...new Set([...bodyLinks, ...declaredLinks])]
.map(inspectMailLink)
.filter(Boolean)
.slice(0, 30);
}
const originalOpenMessage = openMessage;
openMessage = function (id) {
originalOpenMessage(id);
const message = messages.find(item => item.id === id);
if (!message) return;
const senderReasons = suspiciousSenderReasons(message);
const links = messageLinks(message);
const warnings = [];
if (senderReasons.length) {
warnings.push(`<section class="mail-safety-warning" role="alert"><strong>Sender details may be misleading</strong><ul>${senderReasons.map(reason => `<li>${esc(reason)}</li>`).join('')}</ul><small>Sender names and addresses can be forged. Verify the sender through a trusted channel.</small></section>`);
}
const linkCards = links.map((link, index) => `
<div class="mail-link-row ${link.reasons.length ? 'mail-link-risky' : ''}">
<div><strong>${link.reasons.length ? 'Potentially unsafe link' : 'External link'}</strong><span>${esc(link.host)}</span>
${link.reasons.length ? `<small>${esc(link.reasons.join('; '))}</small>` : ''}</div>
<button type="button" class="mail-link-open" data-mail-link="${index}">Review &amp; open</button>
</div>`).join('');
const reader = $('#reader-pane');
const header = reader.querySelector('.reader-header');
if (warnings.length && header) header.insertAdjacentHTML('afterend', warnings.join(''));
const replyBar = reader.querySelector('.reply-bar');
if (links.length && replyBar) {
replyBar.insertAdjacentHTML('beforebegin', `<section class="mail-links"><h3>Links in this message</h3>${links.some(link => link.reasons.length) ? '<p class="mail-safety-intro">Some links show warning signs. Every link requires confirmation before it opens.</p>' : ''}${linkCards}</section>`);
reader.querySelectorAll('[data-mail-link]').forEach(button => {
button.onclick = async () => {
const link = links[Number(button.dataset.mailLink)];
if (!link) return;
button.disabled = true;
try {
await window.daybreakMail.openExternal(link.url);
} catch (error) {
toast(error.message || 'Could not open this link');
} finally {
button.disabled = false;
}
};
});
}
};
let customFolders = [];
function renderCustomFolders() {
const box = $('#custom-folders');
if (!box) return;
box.replaceChildren(...customFolders.map(folder => {
const button = document.createElement('button');
button.className = 'folder custom-folder';
button.dataset.folder = folder.id;
button.classList.toggle('active', activeFolder === folder.id);
const glyph = document.createElement('span');
glyph.className = 'nav-glyph';
glyph.textContent = '▭';
const label = document.createElement('span');
label.textContent = folder.name;
button.title = folder.path;
button.append(glyph, label);
button.addEventListener('click', () => {
if ($('#filter-folder').value) { $('#filter-folder').value = ''; folderBeforeSearch = null; }
activeFolder = folder.id;
$$('.folder').forEach(item => item.classList.toggle('active', item === button));
$('#sidebar-title').textContent = folder.name;
$('#crumb-current').textContent = folder.name;
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
});
return button;
}));
}
async function loadCustomFolders() {
if (!connectedMailAccount || !window.daybreakMail?.listFolders) return;
try {
customFolders = (await window.daybreakMail.listFolders()).folders || [];
renderCustomFolders();
} catch {}
}
async function createMailFolder() {
if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
const name = prompt('New mail folder name:')?.trim();
if (!name) return;
try {
const result = await window.daybreakMail.createFolder(name);
customFolders = result.folders || customFolders;
renderCustomFolders();
toast(`Folder “${result.folder?.name || name}” created`);
} catch (error) {
toast(error.message || 'Could not create the folder');
}
}
function updateAccountCard(account) {
const card = $('#account-settings');
if (!card) return;
const email = account.email || '';
const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase());
const displayName = account.displayName?.trim() || profileSettings.name.trim() || localName;
const initials = displayName.split(/\s+/).filter(Boolean).map(part => part[0]).join('').slice(0, 2);
card.querySelector('.account-avatar').textContent = initials || 'M';
card.querySelector('.account-info strong').textContent = displayName;
card.querySelector('.account-info span').textContent = email;
card.title = `${displayName} <${email}>`;
if (typeof renderLabels === 'function') renderLabels();
void loadCustomFolders();
card.querySelector('.online-dot').style.background = '#70ad7b';
const profileButton = $('.top-avatar');
if (profileButton) {
profileButton.textContent = initials || 'M';
profileButton.title = `${displayName} <${email}>`;
profileButton.setAttribute('aria-label', `${displayName} account settings`);
}
}
function openMailAccount(existingAccount = null) {
const root = $('#modal-root');
const editing = Boolean(existingAccount);
const displayName = existingAccount?.displayName || profileSettings.name || '';
const ruleMarkup = (existingAccount?.rules || []).map(rule => `
<div class="mail-rule-row">
<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${esc(rule.senderContains || '')}">
<input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${esc(rule.subjectContains || '')}">
<select class="mail-rule-action" aria-label="Rule action">
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')}
</select>
${rule.action==='move'
? `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${rule.value==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${rule.value==='Archive'?' selected':''}>Archive</option><option value="Trash"${rule.value==='Trash'?' selected':''}>Trash</option></select>`
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
</div>`).join('');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${esc(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save &amp; reconnect' : 'Test &amp; connect'}</button></div></div></div>`;
const close = () => { root.innerHTML = ''; };
$$('.modal-close').forEach(button => button.onclick = close);
$('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
$('#disconnect-mail').onclick = close;
const addRuleRow = rule => {
const row = document.createElement('div');
row.className = 'mail-rule-row';
row.innerHTML = `<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${esc(rule?.senderContains || '')}"><input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${esc(rule?.subjectContains || '')}"><select class="mail-rule-action" aria-label="Rule action"><option value="archive">Archive</option><option value="move">Move to folder</option><option value="label">Apply label</option><option value="flag">Flag</option></select><input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule?.value || '')}"><button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>`;
row.querySelector('.mail-rule-action').value = rule?.action || 'archive';
$('#mail-rule-list').append(row);
};
$('#add-mail-rule').onclick = () => addRuleRow();
$('#mail-rule-list').onclick = event => {
if (event.target.closest('.remove-mail-rule')) event.target.closest('.mail-rule-row').remove();
};
$('#mail-rule-list').onchange = event => {
if (!event.target.matches('.mail-rule-action')) return;
const row = event.target.closest('.mail-rule-row');
const value = row.querySelector('.mail-rule-value');
if (event.target.value === 'move') {
const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? value.value : 'Inbox';
value.outerHTML = `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${selected==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${selected==='Archive'?' selected':''}>Archive</option><option value="Trash"${selected==='Trash'?' selected':''}>Trash</option></select>`;
} else if (value.tagName === 'SELECT') {
value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`;
}
row.querySelector('.mail-rule-value').disabled = event.target.value === 'flag';
};
$('#connect-mail').onclick = async () => {
const button = $('#connect-mail');
const status = $('#mail-account-status');
const password = $('#mail-account-password').value;
const name = $('#mail-account-display-name').value.trim();
if (!name) { status.textContent = 'Enter a display name for this mail account.'; $('#mail-account-display-name').focus(); return; }
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; }
button.disabled = true;
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…';
status.textContent = editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.';
try {
const details = {
email: $('#mail-account-email').value,
password,
displayName: name,
imapHost: $('#mail-account-imap').value,
smtpHost: $('#mail-account-smtp').value,
signature: $('#mail-account-signature').value,
notificationsEnabled: $('#mail-account-notifications').checked,
syncIntervalMinutes: Number($('#mail-account-sync-interval').value),
rules: [...$('#mail-rule-list').querySelectorAll('.mail-rule-row')].map(row => ({
senderContains: row.querySelector('.mail-rule-sender').value,
subjectContains: row.querySelector('.mail-rule-subject').value,
action: row.querySelector('.mail-rule-action').value,
value: row.querySelector('.mail-rule-value').value
}))
};
const account = editing
? await window.daybreakMail.updateAccount(existingAccount.id, details)
: await window.daybreakMail.connect(details);
if (editing) {
const accountList = await window.daybreakMail.listAccounts();
if (accountList.activeId === account.id) {
connectedMailAccount = account;
updateAccountCard(account);
mailPageOffset = 0;
close();
await syncMailbox(false, { offset: 0 });
} else {
close();
}
toast('Mailbox settings updated');
} else {
connectedMailAccount = account;
updateAccountCard(account);
close();
toast('Mailbox connected securely');
await syncMailbox(true);
}
} catch (error) {
status.textContent = error.message || 'Could not connect. Check the account details and try again.';
button.disabled = false;
button.textContent = editing ? 'Save & reconnect' : 'Test & connect';
}
};
$('#mail-account-email').focus();
}
function mailSearchFilters() {
return {
query: $('#search').value.trim(),
sender: $('#filter-sender').value.trim(),
subject: $('#filter-subject').value.trim(),
after: $('#filter-after').value,
before: $('#filter-before').value,
hasAttachments: $('#filter-attachments').checked,
folder: $('#filter-folder').value
};
}
function renderDrafts(drafts) {
messages.splice(0, messages.length, ...drafts.map(draft => ({
id: draft.id,
sender: 'Draft',
email: draft.to || 'No recipient',
subject: draft.subject || '(no subject)',
snippet: String(draft.text || '').replace(/\s+/g, ' ').slice(0, 180) || 'No message text',
date: new Date(draft.updatedAt || Date.now()).toLocaleString(),
tags: ['Drafts'],
initials: 'D',
color: '#dce6df',
draft
})));
$('#message-list').innerHTML = messages.length ? messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft');
if (start) start.onclick = () => showCompose();
$$('.message').forEach(row => row.onclick = () => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (draft) showCompose(null, false, draft);
});
$('#reader-pane').innerHTML = emptyReader();
$('#pagination').textContent = `${messages.length} drafts`;
$('#load-more').classList.add('hidden');
}
function setupDraftComposer() {
const original = window.showCompose;
window.showCompose = (reply, forward = false, draft = null) => {
original(reply, forward);
const root = $('#modal-root');
const modal = root.querySelector('.compose-modal');
if (!modal) return;
modal.dataset.draftId = draft?.id || '';
if (draft) {
$('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || '';
$('#compose-subject').value = draft.subject || '';
$('#compose-body').value = draft.text || '';
modal.querySelector('.modal-head span').textContent = 'Edit draft';
}
const save = document.createElement('button');
save.type = 'button';
save.className = 'discard';
save.id = 'save-draft';
save.textContent = 'Save draft';
modal.querySelector('.compose-footer').insertBefore(save, $('#send'));
let saveTimer;
let closed = false;
const persist = async () => {
if (closed || !$('#compose-to')) return;
const values = {
id: modal.dataset.draftId || window.crypto.randomUUID(),
to: $('#compose-to').value,
cc: $('#compose-cc').value,
subject: $('#compose-subject').value,
text: $('#compose-body').value
};
if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return;
modal.dataset.draftId = values.id;
const result = await window.daybreakMail.saveDraft(values);
modal.dataset.draftId = result.id;
};
save.onclick = async () => {
try {
await persist();
toast('Draft saved on this device');
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not save draft'); }
};
modal.addEventListener('input', () => {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => persist().catch(error => toast(error.message || 'Could not save draft')), 700);
});
modal.querySelector('.modal-overlay')?.addEventListener('click', event => {
if (!event.target.classList.contains('modal-overlay')) return;
clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft'));
closed = true;
}, true);
root.querySelector('.modal-close')?.addEventListener('click', () => {
clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft'));
closed = true;
}, true);
$('#discard').onclick = async () => {
clearTimeout(saveTimer);
closed = true;
try {
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
root.innerHTML = '';
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete draft'); }
};
$('#send').addEventListener('click', () => {
clearTimeout(saveTimer);
closed = true;
}, true);
};
}
async function syncMailbox(showToast, options = {}) {
if (mailboxSyncPromise) {
mailboxSyncQueued = true;
return mailboxSyncPromise;
}
if (!connectedMailAccount || !window.daybreakMail) {
openMailAccount();
return;
}
const refresh = $('#refresh');
if (refresh) refresh.disabled = true;
const sync = (async () => {
try {
if (activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts();
renderDrafts(result.drafts || []);
if (showToast) toast(`${result.drafts.length} saved drafts`);
return;
}
const previouslyActiveMessage = activeMessage;
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
const result = await window.daybreakMail.syncFolder(activeFolder, offset, mailSearchFilters());
if (options.append) messages.push(...result.messages);
else messages.splice(0, messages.length, ...result.messages);
messages.forEach(message => {
try {
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
message.tags = [...new Set([...(message.tags || []), ...localTags])];
} catch {}
});
if (!options.append) mailPageOffset = offset;
mailTotal = result.total;
activeMessage = messages.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage
: messages[0]?.id;
selectedIds.clear();
const unread = messages.filter(message => message.unread).length;
const inboxCount = $('.folder[data-folder="Inbox"] .count');
if (inboxCount) inboxCount.textContent = String(unread);
const pagination = $('#pagination');
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = $('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
query = '';
renderList();
if (activeMessage) {
openMessage(activeMessage);
const current = messages.find(message => message.id === activeMessage);
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || activeFolder, action: 'unread', enabled: false }).catch(() => {});
}
else $('#reader-pane').innerHTML = emptyReader();
updateAccountCard(connectedMailAccount);
const status = $('#mail-status');
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
if (showToast) toast(`Synced ${messages.length} messages`);
} catch (error) {
toast(error.message || 'Could not sync the inbox');
} finally {
if (refresh) refresh.disabled = false;
}
})();
mailboxSyncPromise = sync;
try {
await sync;
} finally {
mailboxSyncPromise = null;
if (mailboxSyncQueued) {
mailboxSyncQueued = false;
void syncMailbox(false);
}
}
}
if (window.daybreakMail) {
setupDraftComposer();
let searchTimer;
const searchControls = ['#search', '#filter-folder', '#filter-sender', '#filter-subject', '#filter-after', '#filter-before', '#filter-attachments'];
$('#search-filters-toggle').onclick = () => {
const panel = $('#search-filters');
const expanded = panel.classList.toggle('hidden') === false;
$('#search-filters-toggle').setAttribute('aria-expanded', String(expanded));
};
$('#clear-search-filters').onclick = () => {
$('#filter-folder').value = '';
$('#filter-sender').value = '';
$('#filter-subject').value = '';
$('#filter-after').value = '';
$('#filter-before').value = '';
$('#filter-attachments').checked = false;
$('#search').value = '';
activeFolder = folderBeforeSearch || activeFolder;
folderBeforeSearch = null;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
$('#sidebar-title').textContent = activeFolder;
$('#crumb-current').textContent = activeFolder;
query = '';
renderList();
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
};
for (const selector of searchControls) {
$(selector).addEventListener(selector === '#search' ? 'input' : 'change', () => {
if (selector === '#filter-folder' && $('#filter-folder').value) {
if (!folderBeforeSearch) folderBeforeSearch = activeFolder;
activeFolder = $('#filter-folder').value;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder));
$('#sidebar-title').textContent = activeFolder;
$('#crumb-current').textContent = activeFolder;
}
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
mailPageOffset = 0;
void syncMailbox(false, { offset: 0 });
}, selector === '#search' ? 350 : 0);
});
}
window.daybreakMail.getAppVersion().then(version => {
document.title = `ep-mail v${version}`;
}).catch(error => {
console.error('Could not read app version:', error);
});
window.daybreakMail.onSyncUpdate(update => {
if (update.accountId !== connectedMailAccount?.id) return;
if (update.error) {
toast(update.error);
return;
}
if (update.newCount || (update.foldersChanged || []).length) {
if (document.visibilityState === 'visible') {
syncMailbox(false, update.newCount ? { offset: 0 } : {});
}
else mailboxRefreshPending = true;
}
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && mailboxRefreshPending) {
mailboxRefreshPending = false;
syncMailbox(false, { offset: 0 });
}
});
window.addEventListener('focus', () => {
if (connectedMailAccount) syncMailbox(false);
});
window.addEventListener('online', () => {
if (connectedMailAccount) syncMailbox(false, { offset: 0 });
});
setInterval(() => {
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
syncMailbox(false);
}
}, 60 * 1000);
$('#account-settings').addEventListener('click', openMailAccount);
$('#account-settings').addEventListener('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); }
});
$('#settings-button').onclick = () => openPreferences();
$('#refresh').onclick = () => syncMailbox(true);
$('#add-folder').addEventListener('click', createMailFolder);
$$('.folder').forEach(button => button.addEventListener('click', () => {
if ($('#filter-folder').value) {
$('#filter-folder').value = '';
folderBeforeSearch = null;
}
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Drafts'].includes(button.dataset.folder)) {
mailPageOffset = 0;
syncMailbox(false, { offset: 0 });
}
}));
$('#previous-page').onclick = () => {
if (mailPageOffset <= 0) return;
mailPageOffset = Math.max(0, mailPageOffset - 20);
syncMailbox(false, { offset: mailPageOffset });
};
$('#next-page').onclick = () => {
if (mailPageOffset + 20 >= mailTotal) return;
mailPageOffset += 20;
syncMailbox(false, { offset: mailPageOffset });
};
$('#load-more').onclick = () => syncMailbox(false, { append: true });
document.addEventListener('click', async event => {
const sendButton = event.target.closest('#send');
if (!sendButton || !connectedMailAccount) return;
event.preventDefault();
event.stopImmediatePropagation();
const recipient = $('#compose-to').value.trim();
if (!recipient) { $('#compose-to').focus(); toast('Add a recipient to send your message'); return; }
sendButton.disabled = true;
sendButton.textContent = 'Sending…';
try {
const result = await window.daybreakMail.send({
to: recipient,
cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value,
displayName: connectedMailAccount.displayName || profileSettings.name
});
if (result.queued) {
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = '';
toast('Offline: message queued and will send when connected');
if (activeFolder === 'Drafts') void syncMailbox(false);
return;
}
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = '';
toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
if (activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) {
sendButton.disabled = false;
sendButton.textContent = 'Send ↗';
toast(error.message || 'Message could not be sent');
}
}, true);
window.daybreakMail.getAccount().then(account => {
if (!account) return;
connectedMailAccount = account;
updateAccountCard(account);
syncMailbox(false);
}).catch(() => {});
}
+10
View File
@@ -0,0 +1,10 @@
{
"name": "ep-mail",
"short_name": "ep-mail",
"description": "Eternity Project mail, calendar, and contacts.",
"start_url": "./",
"display": "standalone",
"background_color": "#f4f5f1",
"theme_color": "#f4f5f1",
"icons": [{"src":"icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}]
}
+553
View File
@@ -0,0 +1,553 @@
(() => {
// node_modules/@capacitor/core/dist/index.js
var ExceptionCode;
(function(ExceptionCode2) {
ExceptionCode2["Unimplemented"] = "UNIMPLEMENTED";
ExceptionCode2["Unavailable"] = "UNAVAILABLE";
})(ExceptionCode || (ExceptionCode = {}));
var CapacitorException = class extends Error {
constructor(message, code, data) {
super(message);
this.message = message;
this.code = code;
this.data = data;
}
};
var getPlatformId = (win) => {
var _a, _b;
if (win === null || win === void 0 ? void 0 : win.androidBridge) {
return "android";
} else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {
return "ios";
} else {
return "web";
}
};
var createCapacitor = (win) => {
const capCustomPlatform = win.CapacitorCustomPlatform || null;
const cap = win.Capacitor || {};
const Plugins = cap.Plugins = cap.Plugins || {};
const getPlatform = () => {
return capCustomPlatform !== null ? capCustomPlatform.name : getPlatformId(win);
};
const isNativePlatform = () => getPlatform() !== "web";
const isPluginAvailable = (pluginName) => {
const plugin = registeredPlugins.get(pluginName);
if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) {
return true;
}
if (getPluginHeader(pluginName)) {
return true;
}
return false;
};
const getPluginHeader = (pluginName) => {
var _a;
return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find((h) => h.name === pluginName);
};
const handleError = (err) => win.console.error(err);
const registeredPlugins = /* @__PURE__ */ new Map();
const registerPlugin2 = (pluginName, jsImplementations = {}) => {
const registeredPlugin = registeredPlugins.get(pluginName);
if (registeredPlugin) {
console.warn(`Capacitor plugin "${pluginName}" already registered. Cannot register plugins twice.`);
return registeredPlugin.proxy;
}
const platform = getPlatform();
const pluginHeader = getPluginHeader(pluginName);
let jsImplementation;
const loadPluginImplementation = async () => {
if (!jsImplementation && platform in jsImplementations) {
jsImplementation = typeof jsImplementations[platform] === "function" ? jsImplementation = await jsImplementations[platform]() : jsImplementation = jsImplementations[platform];
} else if (capCustomPlatform !== null && !jsImplementation && "web" in jsImplementations) {
jsImplementation = typeof jsImplementations["web"] === "function" ? jsImplementation = await jsImplementations["web"]() : jsImplementation = jsImplementations["web"];
}
return jsImplementation;
};
const createPluginMethod = (impl, prop) => {
var _a, _b;
if (pluginHeader) {
const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find((m) => prop === m.name);
if (methodHeader) {
if (methodHeader.rtype === "promise") {
return (options) => cap.nativePromise(pluginName, prop.toString(), options);
} else {
return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback);
}
} else if (impl) {
return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl);
}
} else if (impl) {
return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl);
} else {
throw new CapacitorException(`"${pluginName}" plugin is not implemented on ${platform}`, ExceptionCode.Unimplemented);
}
};
const createPluginMethodWrapper = (prop) => {
let remove;
const wrapper = (...args) => {
const p = loadPluginImplementation().then((impl) => {
const fn = createPluginMethod(impl, prop);
if (fn) {
const p2 = fn(...args);
remove = p2 === null || p2 === void 0 ? void 0 : p2.remove;
return p2;
} else {
throw new CapacitorException(`"${pluginName}.${prop}()" is not implemented on ${platform}`, ExceptionCode.Unimplemented);
}
});
if (prop === "addListener") {
p.remove = async () => remove();
}
return p;
};
wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`;
Object.defineProperty(wrapper, "name", {
value: prop,
writable: false,
configurable: false
});
return wrapper;
};
const addListener = createPluginMethodWrapper("addListener");
const removeListener = createPluginMethodWrapper("removeListener");
const addListenerNative = (eventName, callback) => {
const call = addListener({ eventName }, callback);
const remove = async () => {
const callbackId = await call;
removeListener({
eventName,
callbackId
}, callback);
};
const p = new Promise((resolve) => call.then(() => resolve({ remove })));
p.remove = async () => {
console.warn(`Using addListener() without 'await' is deprecated.`);
await remove();
};
return p;
};
const proxy = new Proxy({}, {
get(_, prop) {
switch (prop) {
// https://github.com/facebook/react/issues/20030
case "$$typeof":
return void 0;
case "toJSON":
return () => ({});
case "addListener":
return pluginHeader ? addListenerNative : addListener;
case "removeListener":
return removeListener;
default:
return createPluginMethodWrapper(prop);
}
}
});
Plugins[pluginName] = proxy;
registeredPlugins.set(pluginName, {
name: pluginName,
proxy,
platforms: /* @__PURE__ */ new Set([...Object.keys(jsImplementations), ...pluginHeader ? [platform] : []])
});
return proxy;
};
if (!cap.convertFileSrc) {
cap.convertFileSrc = (filePath) => filePath;
}
cap.getPlatform = getPlatform;
cap.handleError = handleError;
cap.isNativePlatform = isNativePlatform;
cap.isPluginAvailable = isPluginAvailable;
cap.registerPlugin = registerPlugin2;
cap.Exception = CapacitorException;
cap.DEBUG = !!cap.DEBUG;
cap.isLoggingEnabled = !!cap.isLoggingEnabled;
return cap;
};
var initCapacitorGlobal = (win) => win.Capacitor = createCapacitor(win);
var Capacitor = /* @__PURE__ */ initCapacitorGlobal(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {});
var registerPlugin = Capacitor.registerPlugin;
var WebPlugin = class {
constructor() {
this.listeners = {};
this.retainedEventArguments = {};
this.windowListeners = {};
}
addListener(eventName, listenerFunc) {
let firstListener = false;
const listeners = this.listeners[eventName];
if (!listeners) {
this.listeners[eventName] = [];
firstListener = true;
}
this.listeners[eventName].push(listenerFunc);
const windowListener = this.windowListeners[eventName];
if (windowListener && !windowListener.registered) {
this.addWindowListener(windowListener);
}
if (firstListener) {
this.sendRetainedArgumentsForEvent(eventName);
}
const remove = async () => this.removeListener(eventName, listenerFunc);
const p = Promise.resolve({ remove });
return p;
}
async removeAllListeners() {
this.listeners = {};
for (const listener in this.windowListeners) {
this.removeWindowListener(this.windowListeners[listener]);
}
this.windowListeners = {};
}
notifyListeners(eventName, data, retainUntilConsumed) {
const listeners = this.listeners[eventName];
if (!listeners) {
if (retainUntilConsumed) {
let args = this.retainedEventArguments[eventName];
if (!args) {
args = [];
}
args.push(data);
this.retainedEventArguments[eventName] = args;
}
return;
}
listeners.forEach((listener) => listener(data));
}
hasListeners(eventName) {
var _a;
return !!((_a = this.listeners[eventName]) === null || _a === void 0 ? void 0 : _a.length);
}
registerWindowListener(windowEventName, pluginEventName) {
this.windowListeners[pluginEventName] = {
registered: false,
windowEventName,
pluginEventName,
handler: (event) => {
this.notifyListeners(pluginEventName, event);
}
};
}
unimplemented(msg = "not implemented") {
return new Capacitor.Exception(msg, ExceptionCode.Unimplemented);
}
unavailable(msg = "not available") {
return new Capacitor.Exception(msg, ExceptionCode.Unavailable);
}
async removeListener(eventName, listenerFunc) {
const listeners = this.listeners[eventName];
if (!listeners) {
return;
}
const index = listeners.indexOf(listenerFunc);
if (index !== -1) {
this.listeners[eventName].splice(index, 1);
}
if (!this.listeners[eventName].length) {
this.removeWindowListener(this.windowListeners[eventName]);
}
}
addWindowListener(handle) {
window.addEventListener(handle.windowEventName, handle.handler);
handle.registered = true;
}
removeWindowListener(handle) {
if (!handle) {
return;
}
window.removeEventListener(handle.windowEventName, handle.handler);
handle.registered = false;
}
sendRetainedArgumentsForEvent(eventName) {
const args = this.retainedEventArguments[eventName];
if (!args) {
return;
}
delete this.retainedEventArguments[eventName];
args.forEach((arg) => {
this.notifyListeners(eventName, arg);
});
}
};
var encode = (str) => encodeURIComponent(str).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
var decode = (str) => str.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
var CapacitorCookiesPluginWeb = class extends WebPlugin {
async getCookies() {
const cookies = document.cookie;
const cookieMap = {};
cookies.split(";").forEach((cookie) => {
if (cookie.length <= 0)
return;
let [key, value] = cookie.replace(/=/, "CAP_COOKIE").split("CAP_COOKIE");
key = decode(key).trim();
value = decode(value).trim();
cookieMap[key] = value;
});
return cookieMap;
}
async setCookie(options) {
try {
const encodedKey = encode(options.key);
const encodedValue = encode(options.value);
const expires = options.expires ? `; expires=${options.expires.replace("expires=", "")}` : "";
const path = (options.path || "/").replace("path=", "");
const domain = options.url != null && options.url.length > 0 ? `domain=${options.url}` : "";
document.cookie = `${encodedKey}=${encodedValue || ""}${expires}; path=${path}; ${domain};`;
} catch (error) {
return Promise.reject(error);
}
}
async deleteCookie(options) {
try {
document.cookie = `${options.key}=; Max-Age=0`;
} catch (error) {
return Promise.reject(error);
}
}
async clearCookies() {
try {
const cookies = document.cookie.split(";") || [];
for (const cookie of cookies) {
document.cookie = cookie.replace(/^ +/, "").replace(/=.*/, `=;expires=${(/* @__PURE__ */ new Date()).toUTCString()};path=/`);
}
} catch (error) {
return Promise.reject(error);
}
}
async clearAllCookies() {
try {
await this.clearCookies();
} catch (error) {
return Promise.reject(error);
}
}
};
var CapacitorCookies = registerPlugin("CapacitorCookies", {
web: () => new CapacitorCookiesPluginWeb()
});
var readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const base64String = reader.result;
resolve(base64String.indexOf(",") >= 0 ? base64String.split(",")[1] : base64String);
};
reader.onerror = (error) => reject(error);
reader.readAsDataURL(blob);
});
var normalizeHttpHeaders = (headers = {}) => {
const originalKeys = Object.keys(headers);
const loweredKeys = Object.keys(headers).map((k) => k.toLocaleLowerCase());
const normalized = loweredKeys.reduce((acc, key, index) => {
acc[key] = headers[originalKeys[index]];
return acc;
}, {});
return normalized;
};
var buildUrlParams = (params, shouldEncode = true) => {
if (!params)
return null;
const output = Object.entries(params).reduce((accumulator, entry) => {
const [key, value] = entry;
let encodedValue;
let item;
if (Array.isArray(value)) {
item = "";
value.forEach((str) => {
encodedValue = shouldEncode ? encodeURIComponent(str) : str;
item += `${key}=${encodedValue}&`;
});
item.slice(0, -1);
} else {
encodedValue = shouldEncode ? encodeURIComponent(value) : value;
item = `${key}=${encodedValue}`;
}
return `${accumulator}&${item}`;
}, "");
return output.substr(1);
};
var buildRequestInit = (options, extra = {}) => {
const output = Object.assign({ method: options.method || "GET", headers: options.headers }, extra);
const headers = normalizeHttpHeaders(options.headers);
const type = headers["content-type"] || "";
if (typeof options.data === "string") {
output.body = options.data;
} else if (type.includes("application/x-www-form-urlencoded")) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(options.data || {})) {
params.set(key, value);
}
output.body = params.toString();
} else if (type.includes("multipart/form-data") || options.data instanceof FormData) {
const form = new FormData();
if (options.data instanceof FormData) {
options.data.forEach((value, key) => {
form.append(key, value);
});
} else {
for (const key of Object.keys(options.data)) {
form.append(key, options.data[key]);
}
}
output.body = form;
const headers2 = new Headers(output.headers);
headers2.delete("content-type");
output.headers = headers2;
} else if (type.includes("application/json") || typeof options.data === "object") {
output.body = JSON.stringify(options.data);
}
return output;
};
var CapacitorHttpPluginWeb = class extends WebPlugin {
/**
* Perform an Http request given a set of options
* @param options Options to build the HTTP request
*/
async request(options) {
const requestInit = buildRequestInit(options, options.webFetchExtra);
const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams);
const url = urlParams ? `${options.url}?${urlParams}` : options.url;
const response = await fetch(url, requestInit);
const contentType = response.headers.get("content-type") || "";
let { responseType = "text" } = response.ok ? options : {};
if (contentType.includes("application/json")) {
responseType = "json";
}
let data;
let blob;
switch (responseType) {
case "arraybuffer":
case "blob":
blob = await response.blob();
data = await readBlobAsBase64(blob);
break;
case "json":
data = await response.json();
break;
case "document":
case "text":
default:
data = await response.text();
}
const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
return {
data,
headers,
status: response.status,
url: response.url
};
}
/**
* Perform an Http GET request given a set of options
* @param options Options to build the HTTP request
*/
async get(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "GET" }));
}
/**
* Perform an Http POST request given a set of options
* @param options Options to build the HTTP request
*/
async post(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "POST" }));
}
/**
* Perform an Http PUT request given a set of options
* @param options Options to build the HTTP request
*/
async put(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "PUT" }));
}
/**
* Perform an Http PATCH request given a set of options
* @param options Options to build the HTTP request
*/
async patch(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "PATCH" }));
}
/**
* Perform an Http DELETE request given a set of options
* @param options Options to build the HTTP request
*/
async delete(options) {
return this.request(Object.assign(Object.assign({}, options), { method: "DELETE" }));
}
};
var CapacitorHttp = registerPlugin("CapacitorHttp", {
web: () => new CapacitorHttpPluginWeb()
});
var SystemBarsStyle;
(function(SystemBarsStyle2) {
SystemBarsStyle2["Dark"] = "DARK";
SystemBarsStyle2["Light"] = "LIGHT";
SystemBarsStyle2["Default"] = "DEFAULT";
})(SystemBarsStyle || (SystemBarsStyle = {}));
var SystemBarType;
(function(SystemBarType2) {
SystemBarType2["StatusBar"] = "StatusBar";
SystemBarType2["NavigationBar"] = "NavigationBar";
})(SystemBarType || (SystemBarType = {}));
var SystemBarsPluginWeb = class extends WebPlugin {
async setStyle() {
this.unavailable("not available for web");
}
async setAnimation() {
this.unavailable("not available for web");
}
async show() {
this.unavailable("not available for web");
}
async hide() {
this.unavailable("not available for web");
}
};
var SystemBars = registerPlugin("SystemBars", {
web: () => new SystemBarsPluginWeb()
});
// scripts/android-bridge.js
var EpMail = registerPlugin("EpMail");
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") {
window.daybreakMail = {
getAppVersion: () => EpMail.getAppVersion().then((result) => result.version),
getAccount: () => EpMail.getAccount(),
listAccounts: () => EpMail.listAccounts(),
selectAccount: (id) => EpMail.selectAccount({ id }),
removeAccount: (id) => EpMail.removeAccount({ id }),
connect: (details) => EpMail.connect(details),
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
listFolders: () => EpMail.listFolders(),
createFolder: (name) => EpMail.createFolder({ name }),
listDrafts: () => EpMail.listDrafts(),
saveDraft: (draft) => EpMail.saveDraft(draft),
deleteDraft: (id) => EpMail.deleteDraft({ id }),
syncInbox: () => EpMail.syncFolder({ folder: "Inbox", offset: 0 }),
onSyncUpdate: (callback) => EpMail.addListener("mailSyncUpdate", callback),
updateMessage: (details) => EpMail.updateMessage(details),
setSnooze: (details) => EpMail.setSnooze(details),
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
saveAttachment: (details) => EpMail.saveAttachment(details),
openExternal: (url) => EpMail.openExternal({ url }),
send: (message) => EpMail.send(message),
disconnect: (id) => EpMail.removeAccount({ id }),
davList: () => EpMail.davList(),
davConnect: (config) => EpMail.davConnect(config),
davActivate: (type, id) => EpMail.davActivate({ type, id }),
davRemove: (type, id) => EpMail.davRemove({ type, id }),
davSync: (type) => EpMail.davSync({ type }),
davSaveEvent: (event) => EpMail.davSaveEvent(event),
davDeleteEvent: (remote) => EpMail.davDeleteEvent(remote),
davSaveContact: (contact) => EpMail.davSaveContact(contact),
davDeleteContact: (remote) => EpMail.davDeleteContact(remote)
};
}
})();
/*! Bundled license information:
@capacitor/core/dist/index.js:
(*! Capacitor: https://capacitorjs.com/ - MIT License *)
*/
+49
View File
@@ -0,0 +1,49 @@
// Persistent profile, calendar and contact tools, plus actions for the mail UI.
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
let profileSettings = productRead(productKeys.profile, { name: '' });
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
productWrite(productKeys.contacts, savedContacts);
let savedEvents = productRead(productKeys.events, []);
let customLabels = productRead(productKeys.labels, []);
let snoozedIds = productRead(productKeys.snoozed, []);
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); }
function openAccountSettings() {
const root=$('#modal-root');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
const close=()=>root.innerHTML='';
$$('.modal-close').forEach(button=>button.onclick=close);
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
$('#save-profile').onclick=()=>{const name=$('#profile-name').value.trim();if(!name){toast('Enter your display name');return}setProfileName(name);close();toast('Account settings saved')};
$('#profile-name').focus();
}
function openPreferences() {
const root=$('#modal-root');
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`;
const close=()=>root.innerHTML='';
$$('.modal-close').forEach(button=>button.onclick=close);
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
$('#save-appearance').onclick=()=>{applyTheme($('#theme-select').value);close();toast('Appearance saved')};
$('#theme-select').focus();
}
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); }
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()}
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}}
function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
function renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})}
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')}
function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toast('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}}
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';});
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()}
const baseMessageRenderer=renderList;
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels,...accountRuleLabels()].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?Boolean(m.snoozedUntil):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()};
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true);
+5
View File
@@ -0,0 +1,5 @@
const CACHE='ep-mail-v4';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
+102
View File
@@ -0,0 +1,102 @@
// Configurable keyboard shortcuts for common mail actions.
const shortcutStorageKey = 'daybreak-shortcuts';
const shortcutActions = [
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
];
function normalizeShortcut(value) {
const text = String(value || '').trim();
if (!text) return '';
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
const key = parts.pop() || '+';
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
}
function loadShortcuts() {
let saved = {};
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
return Object.fromEntries(shortcutActions.map(action => [
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
]));
}
function eventShortcut(event) {
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
const printable = event.key.length === 1;
if (event.shiftKey && !printable) mods.push('Shift');
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
}
function moveMessageSelection(step) {
if (!messages.length) return;
const index = messages.findIndex(message => message.id === activeMessage);
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
}
document.addEventListener('keydown', event => {
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
const target = event.target;
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
const pressed = eventShortcut(event);
if (!pressed) return;
const shortcuts = loadShortcuts();
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
if (!action) return;
event.preventDefault();
action.run();
});
if (typeof openPreferences === 'function') {
const baseOpenPreferences = openPreferences;
openPreferences = function () {
baseOpenPreferences();
const fields = $('#modal-root .compose-fields');
const save = $('#save-appearance');
if (!fields || !save) return;
const shortcuts = loadShortcuts();
const section = document.createElement('div');
section.className = 'shortcut-settings';
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
fields.append(section);
section.addEventListener('keydown', event => {
const input = event.target.closest('.shortcut-input');
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
event.preventDefault();
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
const combo = eventShortcut(event);
if (combo) input.value = combo;
});
$('#reset-shortcuts').onclick = () => {
section.querySelectorAll('.shortcut-input').forEach(input => {
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
});
};
const baseSave = save.onclick;
save.onclick = event => {
const values = {};
const used = new Map();
for (const input of section.querySelectorAll('.shortcut-input')) {
const value = normalizeShortcut(input.value);
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
if (value) used.set(value, label);
values[input.dataset.action] = value;
}
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
baseSave?.call(save, event);
};
};
}
+178
View File
@@ -0,0 +1,178 @@
function localDateTimeValue(date) {
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
return local.toISOString().slice(0, 16);
}
function nextMorning(daysAhead) {
const date = new Date();
date.setDate(date.getDate() + daysAhead);
date.setHours(9, 0, 0, 0);
if (date <= new Date()) date.setDate(date.getDate() + 1);
return date;
}
function openSnoozeDialog(items) {
const eligible = items.filter(message => message?.uid && connectedMailAccount);
if (!eligible.length) {
toast('Snoozing is available for messages in a connected mailbox.');
return;
}
const root = $('#modal-root');
const tomorrow = nextMorning(1);
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</button></div></div></div>`;
const close = () => { root.innerHTML = ''; };
root.querySelectorAll('.modal-close').forEach(button => button.onclick = close);
root.querySelector('.modal-overlay').onclick = event => {
if (event.target.classList.contains('modal-overlay')) close();
};
const schedule = async dueAt => {
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
$('#snooze-status').textContent = 'Choose a reminder time in the future.';
return;
}
const buttons = [...root.querySelectorAll('button')];
buttons.forEach(button => { button.disabled = true; });
try {
for (const message of eligible) {
const sourceFolder = message.sourceFolder ||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(activeFolder) ? activeFolder : 'Inbox');
await window.daybreakMail.setSnooze({
uid: message.uid,
folder: sourceFolder,
sourceFolder,
dueAt,
subject: message.subject
});
}
close();
toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
selectedIds.clear();
await syncMailbox(false, { offset: 0 });
} catch (error) {
$('#snooze-status').textContent = error.message || 'Could not set the reminder.';
buttons.forEach(button => { button.disabled = false; });
}
};
root.querySelectorAll('[data-snooze-at]').forEach(button => {
button.onclick = () => schedule(Number(button.dataset.snoozeAt));
});
$('#snooze-custom').onclick = () => schedule(new Date($('#snooze-custom-time').value).getTime());
$('#snooze-custom-time').focus();
}
function unsnoozeMessage(message) {
const sourceFolder = message.sourceFolder || 'Inbox';
window.daybreakMail.setSnooze({
uid: message.uid,
sourceFolder,
dueAt: null
}).then(async () => {
toast('Message returned to its mailbox');
await syncMailbox(false, { offset: 0 });
}).catch(error => toast(error.message || 'Could not return the message'));
}
function showMessageActions(message) {
const root = $('#modal-root');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
root.querySelector('.modal-overlay').onclick = event => {
if (event.target.classList.contains('modal-overlay')) root.innerHTML = '';
};
}
const renderListBeforeSnooze = renderList;
renderList = function () {
if (activeFolder === 'Snoozed') {
const originalMessages = messages.slice();
const snoozedMessages = messages.filter(message => message.snoozedUntil);
messages.splice(0, messages.length, ...snoozedMessages);
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
const folder = activeFolder;
activeFolder = 'Inbox';
baseMessageRenderer();
activeFolder = folder;
originalFlags.forEach(([message, archived, deleted]) => {
message.archived = archived;
message.deleted = deleted;
});
messages.splice(0, messages.length, ...originalMessages);
for (const row of $$('.message')) {
const message = messages.find(item => item.id === Number(row.dataset.id));
if (!message?.snoozedUntil) continue;
const due = new Date(message.snoozedUntil);
row.title = `Reminder ${due.toLocaleString()}`;
const snippet = row.querySelector('.snippet');
if (snippet) snippet.textContent = `Reminder · ${due.toLocaleString()} · ${message.snippet}`;
}
return;
}
renderListBeforeSnooze();
};
const openMessageBeforeSnooze = openMessage;
openMessage = function (id) {
openMessageBeforeSnooze(id);
const message = messages.find(item => item.id === id);
const tools = $('.reader-tools');
if (!message || !tools) return;
const snoozed = activeFolder === 'Snoozed';
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
};
document.addEventListener('DOMContentLoaded', () => {
$('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
if (window.daybreakMail?.checkSnoozeReminders) {
const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
.catch(error => console.error('Could not check mail reminders:', error));
void checkReminders();
setInterval(checkReminders, 60 * 1000);
}
});
document.addEventListener('click', event => {
const action = event.target.closest('[data-message-action]');
const more = event.target.closest('.reader-tools button[title="More"]');
const snooze = event.target.closest('#reader-snooze, #snooze-selected');
const unsnooze = event.target.closest('#reader-unsnooze');
if (!more && !snooze && !unsnooze && !action) return;
event.preventDefault();
event.stopImmediatePropagation();
if (action) {
const message = messages.find(item => item.id === activeMessage);
$('#modal-root').innerHTML = '';
if (!message) return;
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
else if (action.dataset.messageAction === 'label') addMessageLabel(message);
else {
const type = action.dataset.messageAction;
messageAction(message, type).then(() => {
if (type === 'unread') message.unread = true;
if (type === 'inbox') message.archived = false;
renderList();
toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
}).catch(error => toast(error.message || 'Could not update the message'));
}
return;
}
if (unsnooze) {
const message = messages.find(item => item.id === activeMessage);
if (message) unsnoozeMessage(message);
return;
}
if (snooze?.id === 'snooze-selected') {
openSnoozeDialog(messages.filter(message => selectedIds.has(message.id)));
return;
}
if (more) {
const message = messages.find(item => item.id === activeMessage);
if (message) showMessageActions(message);
return;
}
const message = messages.find(item => item.id === activeMessage);
if (message) openSnoozeDialog([message]);
}, true);
+129
View File
File diff suppressed because one or more lines are too long