Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9e2f7fa30 | ||
|
|
5529a8f18f | ||
|
|
63ee146719 | ||
|
|
43be32b162 | ||
|
|
47ec7bdb80 | ||
|
|
cae6825f2c | ||
|
|
9b3a890b1d | ||
|
|
a1b8bca066 | ||
|
|
520056d27c | ||
|
|
7135cbb629 | ||
|
|
e999497e5f |
@@ -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**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash.
|
||||||
|
|||||||
@@ -4,8 +4,25 @@
|
|||||||
|
|
||||||
- [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.
|
- [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.
|
||||||
|
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
|
||||||
|
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
|
||||||
|
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
|
||||||
|
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
|
||||||
|
- [x] Add per-account signatures, notification preferences, and sync settings.
|
||||||
|
- [x] Add the ability to create IMAP folders from the app.
|
||||||
|
- [ ] Block remote images by default and let users load them per message.
|
||||||
|
|
||||||
## Mail security
|
## Mail security
|
||||||
|
|
||||||
- [ ] Add support for encrypting and decrypting mail with private/public keys or a suitable standard. Decide on the encryption format, key storage and exchange flow, and compatibility requirements before implementation.
|
- [ ] Add support for encrypting and decrypting mail with private/public keys or a suitable standard. Decide on the encryption format, key storage and exchange flow, and compatibility requirements before implementation.
|
||||||
@@ -23,12 +40,13 @@
|
|||||||
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
- [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] 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] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
|
||||||
- [ ] Add persistent IMAP IDLE watchers; bounded periodic polling currently provides updates and reconnect/backoff.
|
- [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] 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] Send updates to the renderer over IPC and show native notifications for new inbox mail.
|
||||||
- [x] Add new mail notifications.
|
- [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.
|
||||||
- [x] Display name must be set per account.
|
- [x] Display name must be set per account.
|
||||||
- [x] Remove the display name initials from the bottom-left corner.
|
- [x] Remove the display name initials from the bottom-left corner.
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ async function openAccountManager(){
|
|||||||
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.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('');
|
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]');
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
/build/*
|
||||||
|
!/build/.npmkeep
|
||||||
@@ -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")
|
||||||
|
}
|
||||||
@@ -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()
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,801 @@
|
|||||||
|
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 previewAttachment(account: JSONObject, input: JSONObject): JSONObject =
|
||||||
|
withStore(account) { _, store ->
|
||||||
|
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
|
||||||
|
?: throw IllegalStateException("That mail folder could not be found.")
|
||||||
|
folder.open(Folder.READ_ONLY)
|
||||||
|
try {
|
||||||
|
val message = (folder as? UIDFolder)?.getMessageByUID(input.optLong("uid"))
|
||||||
|
?: throw IllegalStateException("The message is no longer available.")
|
||||||
|
val filename = input.optString("filename")
|
||||||
|
val part = findAttachment(message, filename)
|
||||||
|
?: throw IllegalStateException("No attachment was found in this message.")
|
||||||
|
val mimeType = part.contentType.substringBefore(';').trim().lowercase(Locale.ROOT)
|
||||||
|
val none = JSONObject().put("kind", "none")
|
||||||
|
.put("reason", "No preview is available for this file type. Download it to open it.")
|
||||||
|
if (Regex("image/(png|jpe?g|gif|webp|bmp|svg\\+xml)").matches(mimeType)) {
|
||||||
|
val bytes = part.inputStream.use { it.readBytes() }
|
||||||
|
if (bytes.size > 5 * 1048576) {
|
||||||
|
none.put("reason", "This image is too large to preview. Download it instead.")
|
||||||
|
} else {
|
||||||
|
JSONObject().put("kind", "image").put(
|
||||||
|
"dataUrl", "data:$mimeType;base64," + android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
|
||||||
|
val bytes = part.inputStream.use { it.readBytes() }
|
||||||
|
JSONObject().put("kind", "text")
|
||||||
|
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
|
||||||
|
.put("truncated", bytes.size > 100000)
|
||||||
|
} else none
|
||||||
|
} finally {
|
||||||
|
folder.close(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun checkForNewMail(account: JSONObject): Int {
|
||||||
|
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("&", "&") }
|
||||||
|
.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,518 @@
|
|||||||
|
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 previewAttachment(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val account = AndroidAccountVault.account()
|
||||||
|
?: throw IllegalStateException("Add a mail account before previewing attachments.")
|
||||||
|
call.resolve(AndroidMailService.previewAttachment(account, JSONObject(call.data.toString())).toJSObject())
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not preview 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 7.5 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 9.0 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
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>
|
||||||
|
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>
|
||||||
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 9.6 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 9.2 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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')
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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" "$@"
|
||||||
@@ -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
|
||||||
@@ -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'
|
||||||
@@ -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'
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
||||||
|
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||||
|
let attachmentItems = [];
|
||||||
|
|
||||||
|
function attachmentKind(filename) {
|
||||||
|
const ext = String(filename).toLowerCase().split('.').pop();
|
||||||
|
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
||||||
|
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
||||||
|
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
||||||
|
return 'Other';
|
||||||
|
}
|
||||||
|
|
||||||
|
function attachmentSize(size) {
|
||||||
|
if (!size) return '';
|
||||||
|
if (typeof size === 'string') return size;
|
||||||
|
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function previewAttachment(target, details) {
|
||||||
|
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
||||||
|
target.textContent = 'Previews are available for connected mailbox messages.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
target.textContent = 'Loading preview…';
|
||||||
|
try {
|
||||||
|
const result = await window.daybreakMail.previewAttachment(details);
|
||||||
|
target.replaceChildren();
|
||||||
|
if (result.kind === 'image') {
|
||||||
|
const image = document.createElement('img');
|
||||||
|
image.className = 'attachment-preview-image';
|
||||||
|
image.alt = details.filename;
|
||||||
|
image.src = result.dataUrl;
|
||||||
|
target.append(image);
|
||||||
|
} else if (result.kind === 'text') {
|
||||||
|
const pre = document.createElement('pre');
|
||||||
|
pre.className = 'attachment-preview-text';
|
||||||
|
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
||||||
|
target.append(pre);
|
||||||
|
} else {
|
||||||
|
target.textContent = result.reason || 'No preview is available for this file type.';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
target.textContent = error.message || 'Could not load the preview.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadAttachment(details) {
|
||||||
|
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
|
||||||
|
window.daybreakMail.saveAttachment(details)
|
||||||
|
.then(result => { if (result.saved) toast('Attachment saved'); })
|
||||||
|
.catch(error => toast(error.message || 'Could not save attachment'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a Preview button to each attachment in the reader.
|
||||||
|
if (typeof openMessage === 'function') {
|
||||||
|
const baseOpenMessage = openMessage;
|
||||||
|
openMessage = function (id) {
|
||||||
|
baseOpenMessage(id);
|
||||||
|
const message = messages.find(item => item.id === id);
|
||||||
|
if (!message?.uid) return;
|
||||||
|
$$('#reader-pane .attachment').forEach(row => {
|
||||||
|
const download = row.querySelector('.download');
|
||||||
|
if (!download || row.querySelector('.preview-attachment')) return;
|
||||||
|
const button = document.createElement('button');
|
||||||
|
button.className = 'preview-attachment icon-button';
|
||||||
|
button.title = 'Preview';
|
||||||
|
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
||||||
|
button.textContent = '👁';
|
||||||
|
button.addEventListener('click', event => {
|
||||||
|
event.stopPropagation();
|
||||||
|
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
||||||
|
if (panel) { panel.remove(); return; }
|
||||||
|
panel = document.createElement('div');
|
||||||
|
panel.className = 'attachment-preview';
|
||||||
|
row.after(panel);
|
||||||
|
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
|
||||||
|
});
|
||||||
|
download.before(button);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collectAttachments() {
|
||||||
|
const items = [];
|
||||||
|
for (const folder of attachmentFolders) {
|
||||||
|
let offset = 0;
|
||||||
|
for (let page = 0; page < 5; page += 1) {
|
||||||
|
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
||||||
|
for (const message of result.messages || []) {
|
||||||
|
for (const file of message.attachments || []) {
|
||||||
|
items.push({
|
||||||
|
uid: message.uid, folder, filename: file.filename, size: file.size,
|
||||||
|
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
||||||
|
kind: attachmentKind(file.filename)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
offset += (result.messages || []).length;
|
||||||
|
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items.sort((a, b) => b.timestamp - a.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openAttachmentsView() {
|
||||||
|
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
|
||||||
|
const root = $('#modal-root');
|
||||||
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></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(); };
|
||||||
|
const list = $('#attachment-list');
|
||||||
|
const render = () => {
|
||||||
|
const text = $('#attachment-search').value.trim().toLowerCase();
|
||||||
|
const type = $('#attachment-type').value;
|
||||||
|
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
||||||
|
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
||||||
|
list.replaceChildren();
|
||||||
|
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
||||||
|
shown.forEach(item => {
|
||||||
|
const row = document.createElement('div');
|
||||||
|
row.className = 'attachment-row';
|
||||||
|
const info = document.createElement('div');
|
||||||
|
info.className = 'attachment-row-info';
|
||||||
|
const name = document.createElement('strong');
|
||||||
|
name.textContent = item.filename;
|
||||||
|
const meta = document.createElement('small');
|
||||||
|
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
||||||
|
info.append(name, meta);
|
||||||
|
const preview = document.createElement('button');
|
||||||
|
preview.className = 'discard';
|
||||||
|
preview.textContent = 'Preview';
|
||||||
|
const save = document.createElement('button');
|
||||||
|
save.className = 'discard';
|
||||||
|
save.textContent = 'Download';
|
||||||
|
const panel = document.createElement('div');
|
||||||
|
panel.className = 'attachment-preview';
|
||||||
|
panel.hidden = true;
|
||||||
|
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
||||||
|
preview.onclick = () => {
|
||||||
|
panel.hidden = !panel.hidden;
|
||||||
|
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
||||||
|
};
|
||||||
|
save.onclick = () => downloadAttachment(details);
|
||||||
|
row.append(info, preview, save, panel);
|
||||||
|
list.append(row);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
$('#attachment-search').oninput = render;
|
||||||
|
$('#attachment-type').onchange = render;
|
||||||
|
try {
|
||||||
|
attachmentItems = await collectAttachments();
|
||||||
|
if ($('#attachment-list')) render();
|
||||||
|
} catch (error) {
|
||||||
|
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||||
|
});
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"appId": "studio.daybreak.mail",
|
||||||
|
"appName": "ep-mail",
|
||||||
|
"webDir": "www",
|
||||||
|
"server": {
|
||||||
|
"androidScheme": "https"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
|||||||
@@ -10,14 +10,20 @@ const ICAL = require('ical.js');
|
|||||||
|
|
||||||
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
|
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
|
||||||
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
|
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
|
||||||
const backgroundSyncIntervalMs = 2 * 60 * 1000;
|
const backgroundSyncIntervalMs = 30 * 1000;
|
||||||
|
const backgroundRetryIntervalMs = 2 * 60 * 1000;
|
||||||
const backgroundSyncConcurrency = 2;
|
const backgroundSyncConcurrency = 2;
|
||||||
|
const backgroundIdleConcurrency = 2;
|
||||||
|
const snoozeCheckIntervalMs = 30 * 1000;
|
||||||
let accountStoreQueue = Promise.resolve();
|
let accountStoreQueue = Promise.resolve();
|
||||||
let backgroundSyncInProgress = false;
|
let backgroundSyncInProgress = false;
|
||||||
let backgroundSyncRequested = false;
|
let backgroundSyncRequested = false;
|
||||||
|
let snoozeReminderCheckInProgress = false;
|
||||||
const backgroundSyncGenerations = new Map();
|
const backgroundSyncGenerations = new Map();
|
||||||
const backgroundSyncFailures = new Map();
|
const backgroundSyncFailures = new Map();
|
||||||
const flagSnapshots = new Map();
|
const flagSnapshots = new Map();
|
||||||
|
const idleWatchers = new Map();
|
||||||
|
const lastBackgroundSyncAt = new Map();
|
||||||
|
|
||||||
function updateAccountStore(update) {
|
function updateAccountStore(update) {
|
||||||
const operation = accountStoreQueue.then(async () => {
|
const operation = accountStoreQueue.then(async () => {
|
||||||
@@ -39,6 +45,53 @@ function sendMailSyncUpdate(update) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function checkSnoozeReminders() {
|
||||||
|
if (snoozeReminderCheckInProgress) return;
|
||||||
|
snoozeReminderCheckInProgress = true;
|
||||||
|
try {
|
||||||
|
const current = await readAccountStore();
|
||||||
|
if (!current?.accounts.some(account =>
|
||||||
|
(account.snoozedMessages || []).some(item => Number(item.dueAt) <= Date.now())
|
||||||
|
)) return;
|
||||||
|
const due = await updateAccountStore(store => {
|
||||||
|
const reminders = [];
|
||||||
|
for (const account of store.accounts) {
|
||||||
|
const snoozes = account.snoozedMessages || [];
|
||||||
|
const remaining = [];
|
||||||
|
for (const item of snoozes) {
|
||||||
|
if (Number(item.dueAt) <= Date.now()) reminders.push({
|
||||||
|
accountId: account.id,
|
||||||
|
email: account.email,
|
||||||
|
notificationsEnabled: account.notificationsEnabled !== false,
|
||||||
|
...item
|
||||||
|
});
|
||||||
|
else remaining.push(item);
|
||||||
|
}
|
||||||
|
account.snoozedMessages = remaining;
|
||||||
|
}
|
||||||
|
return reminders;
|
||||||
|
});
|
||||||
|
for (const reminder of due) {
|
||||||
|
if (reminder.notificationsEnabled !== false && Notification.isSupported()) {
|
||||||
|
new Notification({
|
||||||
|
title: 'Mail reminder',
|
||||||
|
body: `${reminder.subject || 'A message'}${reminder.email ? ` · ${reminder.email}` : ''}`
|
||||||
|
}).show();
|
||||||
|
}
|
||||||
|
sendMailSyncUpdate({
|
||||||
|
accountId: reminder.accountId,
|
||||||
|
snoozeReminder: true,
|
||||||
|
snoozedFolder: reminder.folder,
|
||||||
|
foldersChanged: ['Snoozed', reminder.folder]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Could not process snooze reminders:', error);
|
||||||
|
} finally {
|
||||||
|
snoozeReminderCheckInProgress = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function requestBackgroundSync(accountId = null, force = false) {
|
function requestBackgroundSync(accountId = null, force = false) {
|
||||||
if (accountId) {
|
if (accountId) {
|
||||||
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
|
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
|
||||||
@@ -48,6 +101,7 @@ function requestBackgroundSync(accountId = null, force = false) {
|
|||||||
if (force) {
|
if (force) {
|
||||||
for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0;
|
for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0;
|
||||||
}
|
}
|
||||||
|
void reconcileIdleWatchers().catch(error => console.error('Could not reconcile IMAP IDLE watchers:', error));
|
||||||
if (backgroundSyncInProgress) {
|
if (backgroundSyncInProgress) {
|
||||||
if (accountId || force) backgroundSyncRequested = true;
|
if (accountId || force) backgroundSyncRequested = true;
|
||||||
return;
|
return;
|
||||||
@@ -56,6 +110,89 @@ function requestBackgroundSync(accountId = null, force = false) {
|
|||||||
void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error));
|
void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function stopIdleWatcher(accountId) {
|
||||||
|
const watcher = idleWatchers.get(accountId);
|
||||||
|
if (!watcher) return;
|
||||||
|
watcher.stopped = true;
|
||||||
|
watcher.client?.close();
|
||||||
|
idleWatchers.delete(accountId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function startIdleWatcher(account) {
|
||||||
|
if (idleWatchers.has(account.id)) return;
|
||||||
|
const watcher = {
|
||||||
|
generation: backgroundSyncGenerations.get(account.id) || 0,
|
||||||
|
stopped: false,
|
||||||
|
client: null
|
||||||
|
};
|
||||||
|
idleWatchers.set(account.id, watcher);
|
||||||
|
void runIdleWatcher(account.id, watcher).catch(error => {
|
||||||
|
console.error(`IMAP IDLE watcher failed for ${account.email}:`, error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runIdleWatcher(accountId, watcher) {
|
||||||
|
let failures = 0;
|
||||||
|
while (!watcher.stopped && backgroundSyncGenerations.get(accountId) === watcher.generation) {
|
||||||
|
let client;
|
||||||
|
try {
|
||||||
|
const account = await readAccount(accountId);
|
||||||
|
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||||
|
client = imapClient(account, {
|
||||||
|
autoIdleDelay: 10_000,
|
||||||
|
maxIdleTime: 25 * 60 * 1000,
|
||||||
|
socketTimeout: 30 * 60 * 1000
|
||||||
|
});
|
||||||
|
watcher.client = client;
|
||||||
|
let signalDisconnected;
|
||||||
|
const disconnected = new Promise(resolve => { signalDisconnected = resolve; });
|
||||||
|
client.on('exists', event => {
|
||||||
|
if (event.path.toLowerCase() === 'inbox' && event.count > event.prevCount) requestBackgroundSync();
|
||||||
|
});
|
||||||
|
client.on('flags', event => {
|
||||||
|
if (event.path.toLowerCase() === 'inbox') requestBackgroundSync();
|
||||||
|
});
|
||||||
|
client.on('error', error => {
|
||||||
|
if (!watcher.stopped) console.error(`IMAP IDLE connection failed for ${account.email}:`, error);
|
||||||
|
signalDisconnected();
|
||||||
|
});
|
||||||
|
client.once('close', signalDisconnected);
|
||||||
|
await client.connect();
|
||||||
|
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||||
|
await client.mailboxOpen('INBOX', { readOnly: true });
|
||||||
|
const connectedAt = Date.now();
|
||||||
|
await disconnected;
|
||||||
|
if (Date.now() - connectedAt > 60_000) failures = 0;
|
||||||
|
} catch (error) {
|
||||||
|
if (!watcher.stopped) console.error(`IMAP IDLE watcher disconnected for ${accountId}:`, error);
|
||||||
|
} finally {
|
||||||
|
if (watcher.client === client) watcher.client = null;
|
||||||
|
if (client?.usable) await client.logout().catch(() => client.close());
|
||||||
|
else client?.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||||
|
const retryDelay = Math.min(5 * 60 * 1000, 15_000 * (2 ** Math.min(failures, 5)));
|
||||||
|
failures += 1;
|
||||||
|
await new Promise(resolve => {
|
||||||
|
const timer = setTimeout(resolve, retryDelay);
|
||||||
|
timer.unref();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reconcileIdleWatchers() {
|
||||||
|
const store = (await readAccountStore()) || { accounts: [] };
|
||||||
|
const desiredAccounts = store.accounts.slice(0, backgroundIdleConcurrency);
|
||||||
|
const desiredIds = new Set(desiredAccounts.map(account => account.id));
|
||||||
|
for (const [accountId, watcher] of idleWatchers) {
|
||||||
|
if (!desiredIds.has(accountId) || watcher.generation !== (backgroundSyncGenerations.get(accountId) || 0)) {
|
||||||
|
stopIdleWatcher(accountId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const account of desiredAccounts) startIdleWatcher(account);
|
||||||
|
}
|
||||||
|
|
||||||
async function readDavStore() {
|
async function readDavStore() {
|
||||||
try {
|
try {
|
||||||
const encrypted = await fs.readFile(davCredentialsPath());
|
const encrypted = await fs.readFile(davCredentialsPath());
|
||||||
@@ -115,10 +252,40 @@ function normalizeAccount(input) {
|
|||||||
throw new Error('Enter a valid email, password, and both mail server names.');
|
throw new Error('Enter a valid email, password, and both mail server names.');
|
||||||
}
|
}
|
||||||
if (!displayName) throw new Error('Enter a display name for this mail account.');
|
if (!displayName) throw new Error('Enter a display name for this mail account.');
|
||||||
return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
|
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
|
||||||
|
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
|
||||||
|
throw new Error('Choose a supported mailbox sync interval.');
|
||||||
|
}
|
||||||
|
const inputRules = Array.isArray(input?.rules) ? input.rules : [];
|
||||||
|
if (inputRules.length > 50) throw new Error('You can set up to 50 mail rules per account.');
|
||||||
|
const rules = inputRules.map((rule, index) => {
|
||||||
|
const senderContains = String(rule?.senderContains || '').trim().slice(0, 200);
|
||||||
|
const subjectContains = String(rule?.subjectContains || '').trim().slice(0, 200);
|
||||||
|
const action = String(rule?.action || '');
|
||||||
|
const value = String(rule?.value || '').trim().slice(0, 200);
|
||||||
|
if ((!senderContains && !subjectContains) || !['archive', 'move', 'label', 'flag'].includes(action)) {
|
||||||
|
throw new Error(`Mail rule ${index + 1} needs a sender or subject condition and a valid action.`);
|
||||||
|
}
|
||||||
|
if ((action === 'move' || action === 'label') && !value) {
|
||||||
|
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
|
||||||
|
}
|
||||||
|
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value)) {
|
||||||
|
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash.`);
|
||||||
|
}
|
||||||
|
return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value };
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
email, password, displayName, imapHost, smtpHost,
|
||||||
|
signature: String(input?.signature || '').slice(0, 5000),
|
||||||
|
notificationsEnabled: input?.notificationsEnabled !== false,
|
||||||
|
syncIntervalMinutes,
|
||||||
|
rules,
|
||||||
|
imapPort: 143,
|
||||||
|
smtpPort: 587
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function imapClient(account) {
|
function imapClient(account, options = {}) {
|
||||||
return new ImapFlow({
|
return new ImapFlow({
|
||||||
host: account.imapHost,
|
host: account.imapHost,
|
||||||
port: account.imapPort,
|
port: account.imapPort,
|
||||||
@@ -129,7 +296,8 @@ function imapClient(account) {
|
|||||||
logger: false,
|
logger: false,
|
||||||
connectionTimeout: 15000,
|
connectionTimeout: 15000,
|
||||||
greetingTimeout: 10000,
|
greetingTimeout: 10000,
|
||||||
socketTimeout: 20000
|
socketTimeout: 20000,
|
||||||
|
...options
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,7 +353,17 @@ async function readAccount(accountId = null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function publicAccount(account) {
|
function publicAccount(account) {
|
||||||
return { id: account.id, email: account.email, displayName: account.displayName || '', imapHost: account.imapHost, smtpHost: account.smtpHost };
|
return {
|
||||||
|
id: account.id,
|
||||||
|
email: account.email,
|
||||||
|
displayName: account.displayName || '',
|
||||||
|
imapHost: account.imapHost,
|
||||||
|
smtpHost: account.smtpHost,
|
||||||
|
signature: account.signature || '',
|
||||||
|
notificationsEnabled: account.notificationsEnabled !== false,
|
||||||
|
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
|
||||||
|
rules: Array.isArray(account.rules) ? account.rules : []
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveAccount(account) {
|
async function saveAccount(account) {
|
||||||
@@ -226,6 +404,28 @@ async function findSentMailbox(client, createIfMissing = false) {
|
|||||||
return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null);
|
return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CUSTOM_FOLDER_PREFIX = 'Folder:';
|
||||||
|
const RESERVED_FOLDER_NAMES = new Set(['inbox', 'sent', 'drafts', 'archive', 'trash', 'starred', 'snoozed', 'junk', 'spam']);
|
||||||
|
|
||||||
|
async function listCustomFolders(client) {
|
||||||
|
return (await client.list())
|
||||||
|
.filter(mailbox => !mailbox.flags?.has('\\Noselect') && !mailbox.specialUse &&
|
||||||
|
mailbox.path.toUpperCase() !== 'INBOX' &&
|
||||||
|
!RESERVED_FOLDER_NAMES.has(mailbox.path.toLowerCase().split(/[./]/).pop()) &&
|
||||||
|
!['sent items', 'sent mail', 'sent messages', 'archives', 'all mail', 'deleted items', 'deleted messages']
|
||||||
|
.includes(mailbox.path.toLowerCase().split(/[./]/).pop()))
|
||||||
|
.map(mailbox => ({ name: mailbox.name, path: mailbox.path, id: CUSTOM_FOLDER_PREFIX + mailbox.path }))
|
||||||
|
.sort((a, b) => a.path.localeCompare(b.path));
|
||||||
|
}
|
||||||
|
|
||||||
|
function validFolderName(input) {
|
||||||
|
const name = String(input || '').trim();
|
||||||
|
if (!name || name.length > 100) throw new Error('Enter a folder name of up to 100 characters.');
|
||||||
|
if (/[\\/.*%#&\u0000-\u001f]/.test(name)) throw new Error('Folder names cannot contain / \\ . * % # & or control characters.');
|
||||||
|
if (RESERVED_FOLDER_NAMES.has(name.toLowerCase())) throw new Error('That folder name is reserved.');
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
async function folderPath(client, folder, createIfMissing = false) {
|
async function folderPath(client, folder, createIfMissing = false) {
|
||||||
if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX';
|
if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX';
|
||||||
const definitions = {
|
const definitions = {
|
||||||
@@ -234,17 +434,83 @@ async function folderPath(client, folder, createIfMissing = false) {
|
|||||||
Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash']
|
Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash']
|
||||||
};
|
};
|
||||||
const definition = definitions[folder];
|
const definition = definitions[folder];
|
||||||
|
if (!definition && typeof folder === 'string' && folder.startsWith(CUSTOM_FOLDER_PREFIX)) {
|
||||||
|
const path = folder.slice(CUSTOM_FOLDER_PREFIX.length);
|
||||||
|
const match = (await client.list()).find(mailbox => mailbox.path === path);
|
||||||
|
if (!match || match.flags?.has('\\Noselect')) throw new Error('This folder is not available on the mail server.');
|
||||||
|
return match.path;
|
||||||
|
}
|
||||||
if (!definition) throw new Error('This folder is not available on the mail server.');
|
if (!definition) throw new Error('This folder is not available on the mail server.');
|
||||||
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
|
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
function filterMailboxMessages(messages, filters = {}) {
|
||||||
|
const text = String(filters.query || '').trim().toLowerCase();
|
||||||
|
const sender = String(filters.sender || '').trim().toLowerCase();
|
||||||
|
const subject = String(filters.subject || '').trim().toLowerCase();
|
||||||
|
const after = filters.after ? new Date(`${filters.after}T00:00:00`).getTime() : null;
|
||||||
|
const before = filters.before ? new Date(`${filters.before}T23:59:59.999`).getTime() : null;
|
||||||
|
return messages.filter(message => {
|
||||||
|
const haystack = `${message.sender || ''} ${message.email || ''} ${message.subject || ''} ${message.snippet || ''} ${(message.body || []).join(' ')}`.toLowerCase();
|
||||||
|
const date = Number(message.timestamp || 0);
|
||||||
|
return (!text || text.split(/\s+/).every(term => haystack.includes(term))) &&
|
||||||
|
(!sender || `${message.sender || ''} ${message.email || ''}`.toLowerCase().includes(sender)) &&
|
||||||
|
(!subject || String(message.subject || '').toLowerCase().includes(subject)) &&
|
||||||
|
(!after || date >= after) && (!before || date <= before) &&
|
||||||
|
(!filters.hasAttachments || (message.attachments || []).length > 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cacheMailboxMessages(accountId, folder, messages) {
|
||||||
|
if (!messages.length) return;
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const account = store.accounts.find(item => item.id === accountId);
|
||||||
|
if (!account) return;
|
||||||
|
account.mailCache = account.mailCache || {};
|
||||||
|
const previous = account.mailCache[folder] || [];
|
||||||
|
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
|
||||||
|
for (const message of messages) merged.set(String(message.uid || message.id), message);
|
||||||
|
account.mailCache[folder] = [...merged.values()].slice(-50);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
|
||||||
|
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
|
||||||
|
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
|
||||||
|
const start = Math.max(0, Number(offset) || 0);
|
||||||
|
const messages = all.slice(start, start + limit);
|
||||||
|
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
|
||||||
|
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
|
||||||
const client = imapClient(account);
|
const client = imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
const mailboxPath = await folderPath(client, folder);
|
const mailboxPath = await folderPath(client, folder);
|
||||||
if (!mailboxPath) return { messages: [], total: 0 };
|
if (!mailboxPath) return { messages: [], total: 0 };
|
||||||
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
|
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
|
||||||
|
const snoozed = new Set((account.snoozedMessages || [])
|
||||||
|
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
|
||||||
|
.map(item => Number(item.uid)));
|
||||||
|
if (Object.values(filters).some(value => value && value !== false)) {
|
||||||
|
const searchStart = Math.max(1, mailbox.exists - 4999);
|
||||||
|
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
|
||||||
|
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||||
|
}) : [];
|
||||||
|
const all = [];
|
||||||
|
for (const item of fetched) {
|
||||||
|
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
||||||
|
const message = await toUiMessage(item, folder);
|
||||||
|
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
||||||
|
all.push(message);
|
||||||
|
}
|
||||||
|
await cacheMailboxMessages(account.id, folder, all);
|
||||||
|
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
|
||||||
|
const start = Math.max(0, Number(offset) || 0);
|
||||||
|
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||||
|
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
|
||||||
|
}
|
||||||
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
|
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
|
||||||
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
|
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
|
||||||
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
|
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
|
||||||
@@ -257,13 +523,30 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
|||||||
});
|
});
|
||||||
const messages = [];
|
const messages = [];
|
||||||
for (const item of fetched.reverse()) {
|
for (const item of fetched.reverse()) {
|
||||||
if (!item.source) continue;
|
if (!item.source || snoozed.has(Number(item.uid))) continue;
|
||||||
|
const message = await toUiMessage(item, folder);
|
||||||
|
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
|
||||||
|
messages.push(message);
|
||||||
|
}
|
||||||
|
await cacheMailboxMessages(account.id, folder, messages);
|
||||||
|
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toUiMessage(item, folder) {
|
||||||
const parsed = await simpleParser(item.source);
|
const parsed = await simpleParser(item.source);
|
||||||
const sender = parsed.from?.value?.[0];
|
const sender = parsed.from?.value?.[0];
|
||||||
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim();
|
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
|
||||||
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
|
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
|
||||||
const date = parsed.date || item.internalDate || new Date();
|
const date = parsed.date || item.internalDate || new Date();
|
||||||
messages.push({
|
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
|
||||||
|
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
|
||||||
|
.map(match => (match[1] || match[2] || match[3] || '').replace(/&/gi, '&').replace(///gi, '/'))
|
||||||
|
.filter(Boolean)
|
||||||
|
.slice(0, 30);
|
||||||
|
return {
|
||||||
id: Number(item.uid),
|
id: Number(item.uid),
|
||||||
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
|
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
|
||||||
color: '#dce6df',
|
color: '#dce6df',
|
||||||
@@ -273,23 +556,58 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) {
|
|||||||
snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
||||||
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
||||||
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
||||||
|
timestamp: date.getTime(),
|
||||||
unread: !item.flags?.has('\\Seen'),
|
unread: !item.flags?.has('\\Seen'),
|
||||||
star: item.flags?.has('\\Flagged') || false,
|
star: item.flags?.has('\\Flagged') || false,
|
||||||
tags: [folder],
|
tags: [folder],
|
||||||
sent: folder === 'Sent',
|
sent: folder === 'Sent',
|
||||||
archived: folder === 'Archive',
|
archived: folder === 'Archive',
|
||||||
deleted: folder === 'Trash',
|
deleted: folder === 'Trash',
|
||||||
|
sourceFolder: folder,
|
||||||
body,
|
body,
|
||||||
|
links,
|
||||||
uid: Number(item.uid),
|
uid: Number(item.uid),
|
||||||
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
||||||
attachment: parsed.attachments?.[0]?.filename || null,
|
attachment: parsed.attachments?.[0]?.filename || null,
|
||||||
size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
|
size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchSnoozedMailbox(account, offset, limit) {
|
||||||
|
const now = Date.now();
|
||||||
|
const pending = (account.snoozedMessages || [])
|
||||||
|
.filter(item => Number(item.dueAt) > now)
|
||||||
|
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
|
||||||
|
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
|
||||||
|
const client = imapClient(account);
|
||||||
|
const messages = [];
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
for (const snooze of selected) {
|
||||||
|
const sourceFolder = String(snooze.folder || 'Inbox');
|
||||||
|
const mailboxPath = await folderPath(client, sourceFolder);
|
||||||
|
if (!mailboxPath) continue;
|
||||||
|
const lock = await client.getMailboxLock(mailboxPath);
|
||||||
|
try {
|
||||||
|
const item = await client.fetchOne(Number(snooze.uid), {
|
||||||
|
uid: true, envelope: true, flags: true, internalDate: true, source: true
|
||||||
|
}, { uid: true });
|
||||||
|
if (!item?.source) continue;
|
||||||
|
const message = await toUiMessage(item, 'Snoozed');
|
||||||
|
message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || []));
|
||||||
|
messages.push({
|
||||||
|
...message,
|
||||||
|
sourceFolder,
|
||||||
|
snoozedUntil: Number(snooze.dueAt)
|
||||||
});
|
});
|
||||||
|
} finally {
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return { messages, total: mailbox.exists, start: first, end: Math.min(end, mailbox.exists), folder };
|
|
||||||
} finally {
|
} finally {
|
||||||
if (client.usable) await client.logout().catch(() => {});
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
}
|
}
|
||||||
|
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveAccountSyncState(accountId, generation, folders) {
|
async function saveAccountSyncState(accountId, generation, folders) {
|
||||||
@@ -316,6 +634,7 @@ function backgroundFolderLabel(mailbox) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function syncAccountMailboxes(account) {
|
async function syncAccountMailboxes(account) {
|
||||||
|
await flushMailOutbox(account);
|
||||||
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
||||||
const client = imapClient(account);
|
const client = imapClient(account);
|
||||||
try {
|
try {
|
||||||
@@ -325,6 +644,7 @@ async function syncAccountMailboxes(account) {
|
|||||||
const accountSnapshots = new Map(flagSnapshots.get(account.id) || []);
|
const accountSnapshots = new Map(flagSnapshots.get(account.id) || []);
|
||||||
let inboxNewCount = 0;
|
let inboxNewCount = 0;
|
||||||
const changedFolders = [];
|
const changedFolders = [];
|
||||||
|
const ruleActions = [];
|
||||||
|
|
||||||
for (const listedMailbox of mailboxes) {
|
for (const listedMailbox of mailboxes) {
|
||||||
const mailbox = await client.mailboxOpen(listedMailbox.path, { readOnly: true });
|
const mailbox = await client.mailboxOpen(listedMailbox.path, { readOnly: true });
|
||||||
@@ -355,6 +675,17 @@ async function syncAccountMailboxes(account) {
|
|||||||
const added = uidCeiling > previousUid
|
const added = uidCeiling > previousUid
|
||||||
? await client.fetchAll(`${previousUid + 1}:${uidCeiling}`, { uid: true, envelope: true, flags: true }, { uid: true })
|
? await client.fetchAll(`${previousUid + 1}:${uidCeiling}`, { uid: true, envelope: true, flags: true }, { uid: true })
|
||||||
: [];
|
: [];
|
||||||
|
if (label === 'Inbox' && account.rules?.length) {
|
||||||
|
for (const item of added) {
|
||||||
|
const rule = account.rules.find(candidate => {
|
||||||
|
const sender = (item.envelope?.from || []).map(address => `${address.name || ''} ${address.address || ''}`).join(' ').toLowerCase();
|
||||||
|
const subject = String(item.envelope?.subject || '').toLowerCase();
|
||||||
|
return (!candidate.senderContains || sender.includes(candidate.senderContains.toLowerCase())) &&
|
||||||
|
(!candidate.subjectContains || subject.includes(candidate.subjectContains.toLowerCase()));
|
||||||
|
});
|
||||||
|
if (rule) ruleActions.push({ uid: Number(item.uid), folder, rule });
|
||||||
|
}
|
||||||
|
}
|
||||||
let flagsChanged = false;
|
let flagsChanged = false;
|
||||||
|
|
||||||
if (mailbox.highestModseq && oldState.highestModseq) {
|
if (mailbox.highestModseq && oldState.highestModseq) {
|
||||||
@@ -382,6 +713,39 @@ async function syncAccountMailboxes(account) {
|
|||||||
if (added.length || flagsChanged) changedFolders.push(label);
|
if (added.length || flagsChanged) changedFolders.push(label);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ruleLabels = [];
|
||||||
|
for (const { uid, folder, rule } of ruleActions) {
|
||||||
|
const lock = await client.getMailboxLock(folder);
|
||||||
|
try {
|
||||||
|
if (rule.action === 'flag') {
|
||||||
|
await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
|
||||||
|
} else if (rule.action === 'archive' || rule.action === 'move') {
|
||||||
|
const target = rule.action === 'archive'
|
||||||
|
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
|
||||||
|
: await folderPath(client, rule.value);
|
||||||
|
if (!target) throw new Error(`Rule destination mailbox "${rule.value}" was not found.`);
|
||||||
|
if (target !== folder) await client.messageMove(uid, target, { uid: true });
|
||||||
|
changedFolders.push(rule.action === 'archive' ? 'Archive' : backgroundFolderLabel({ path: target }));
|
||||||
|
} else if (rule.action === 'label') {
|
||||||
|
ruleLabels.push({ key: `${folder}:${uid}`, label: rule.value });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Could not apply mail rule "${rule.id}" to message ${uid}:`, error);
|
||||||
|
} finally {
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ruleLabels.length) {
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) return;
|
||||||
|
saved.ruleLabels = saved.ruleLabels || {};
|
||||||
|
for (const { key, label } of ruleLabels) {
|
||||||
|
saved.ruleLabels[key] = [...new Set([...(saved.ruleLabels[key] || []), label])];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const saved = await saveAccountSyncState(account.id, generation, states);
|
const saved = await saveAccountSyncState(account.id, generation, states);
|
||||||
if (!saved || backgroundSyncGenerations.get(account.id) !== generation) {
|
if (!saved || backgroundSyncGenerations.get(account.id) !== generation) {
|
||||||
return { newCount: 0, changedFolders: [] };
|
return { newCount: 0, changedFolders: [] };
|
||||||
@@ -394,7 +758,7 @@ async function syncAccountMailboxes(account) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function showNewMailNotification(account, count) {
|
function showNewMailNotification(account, count) {
|
||||||
if (!count || !Notification.isSupported()) return;
|
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
|
||||||
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
|
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
|
||||||
if (focused) return;
|
if (focused) return;
|
||||||
const notification = new Notification({
|
const notification = new Notification({
|
||||||
@@ -404,9 +768,14 @@ function showNewMailNotification(account, count) {
|
|||||||
notification.show();
|
notification.show();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function syncAccountWithBackoff(account) {
|
async function syncAccountWithBackoff(account, periodicOnly = false) {
|
||||||
|
if (periodicOnly) {
|
||||||
|
const intervalMs = (Number(account.syncIntervalMinutes) || 2) * 60 * 1000;
|
||||||
|
if (Date.now() - (lastBackgroundSyncAt.get(account.id) || 0) < intervalMs) return;
|
||||||
|
}
|
||||||
const failure = backgroundSyncFailures.get(account.id);
|
const failure = backgroundSyncFailures.get(account.id);
|
||||||
if (failure && Date.now() < failure.retryAt) return;
|
if (failure && Date.now() < failure.retryAt) return;
|
||||||
|
lastBackgroundSyncAt.set(account.id, Date.now());
|
||||||
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
const generation = backgroundSyncGenerations.get(account.id) || 0;
|
||||||
try {
|
try {
|
||||||
const result = await syncAccountMailboxes(account);
|
const result = await syncAccountMailboxes(account);
|
||||||
@@ -419,26 +788,29 @@ async function syncAccountWithBackoff(account) {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const attempts = (failure?.attempts || 0) + 1;
|
const attempts = (failure?.attempts || 0) + 1;
|
||||||
const retryDelay = Math.min(30 * 60 * 1000, backgroundSyncIntervalMs * (2 ** Math.min(attempts - 1, 4)));
|
const retryDelay = Math.min(30 * 60 * 1000, backgroundRetryIntervalMs * (2 ** Math.min(attempts - 1, 4)));
|
||||||
backgroundSyncFailures.set(account.id, { attempts, retryAt: Date.now() + retryDelay });
|
backgroundSyncFailures.set(account.id, { attempts, retryAt: Date.now() + retryDelay });
|
||||||
console.error(`Background mail sync failed for ${account.email}:`, error);
|
console.error(`Background mail sync failed for ${account.email}:`, error);
|
||||||
if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' });
|
if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runBackgroundSync() {
|
async function runBackgroundSync(periodicOnly = false) {
|
||||||
if (backgroundSyncInProgress) {
|
if (backgroundSyncInProgress) {
|
||||||
backgroundSyncRequested = true;
|
if (!periodicOnly) backgroundSyncRequested = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
backgroundSyncInProgress = true;
|
backgroundSyncInProgress = true;
|
||||||
|
let onlyDueAccounts = periodicOnly;
|
||||||
try {
|
try {
|
||||||
do {
|
do {
|
||||||
backgroundSyncRequested = false;
|
backgroundSyncRequested = false;
|
||||||
const store = (await readAccountStore()) || { accounts: [] };
|
const store = (await readAccountStore()) || { accounts: [] };
|
||||||
for (let index = 0; index < store.accounts.length; index += backgroundSyncConcurrency) {
|
for (let index = 0; index < store.accounts.length; index += backgroundSyncConcurrency) {
|
||||||
await Promise.all(store.accounts.slice(index, index + backgroundSyncConcurrency).map(syncAccountWithBackoff));
|
await Promise.all(store.accounts.slice(index, index + backgroundSyncConcurrency)
|
||||||
|
.map(account => syncAccountWithBackoff(account, onlyDueAccounts)));
|
||||||
}
|
}
|
||||||
|
if (backgroundSyncRequested) onlyDueAccounts = false;
|
||||||
} while (backgroundSyncRequested);
|
} while (backgroundSyncRequested);
|
||||||
} finally {
|
} finally {
|
||||||
backgroundSyncInProgress = false;
|
backgroundSyncInProgress = false;
|
||||||
@@ -492,7 +864,12 @@ ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
|
|||||||
if (!current) throw new Error('That mail account is no longer available.');
|
if (!current) throw new Error('That mail account is no longer available.');
|
||||||
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
|
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
|
||||||
store.accounts = store.accounts.map(item => item.id === existing.id
|
store.accounts = store.accounts.map(item => item.id === existing.id
|
||||||
? { ...account, syncState: endpointChanged ? undefined : current.syncState }
|
? {
|
||||||
|
...account,
|
||||||
|
syncState: endpointChanged ? undefined : current.syncState,
|
||||||
|
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []),
|
||||||
|
ruleLabels: endpointChanged ? {} : (current.ruleLabels || {})
|
||||||
|
}
|
||||||
: item);
|
: item);
|
||||||
return store.accounts.find(item => item.id === existing.id);
|
return store.accounts.find(item => item.id === existing.id);
|
||||||
});
|
});
|
||||||
@@ -515,22 +892,137 @@ ipcMain.handle('mail:connect', async (_event, input) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) => {
|
ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before syncing.');
|
if (!account) throw new Error('Add a mail account before syncing.');
|
||||||
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
|
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
|
||||||
const folder = allowedFolders.has(requestedFolder) ? requestedFolder : 'Inbox';
|
const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder;
|
||||||
return fetchMailbox(account, folder, offset);
|
const folder = allowedFolders.has(selectedFolder) || String(selectedFolder).startsWith(CUSTOM_FOLDER_PREFIX)
|
||||||
|
? selectedFolder : 'Inbox';
|
||||||
|
const { folder: _filterFolder, ...criteria } = filters;
|
||||||
|
try {
|
||||||
|
await flushMailOutbox(account);
|
||||||
|
return await fetchMailbox(account, folder, offset, 20, criteria);
|
||||||
|
} catch (error) {
|
||||||
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
|
const cached = cachedMailbox(account, folder, offset, 20, criteria);
|
||||||
|
if (!cached.total) throw error;
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.handle('mail:update-message', async (_event, input) => {
|
ipcMain.handle('mail:list-folders', async () => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before changing messages.');
|
if (!account) throw new Error('Add a mail account before listing folders.');
|
||||||
|
const client = imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
return { folders: await listCustomFolders(client) };
|
||||||
|
} catch (error) {
|
||||||
|
if (isConnectivityFailure(error)) return { folders: [], offline: true };
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('mail:create-folder', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before creating folders.');
|
||||||
|
const name = validFolderName(input?.name);
|
||||||
|
const client = imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const existing = await client.list();
|
||||||
|
if (existing.some(mailbox => mailbox.path.toLowerCase() === name.toLowerCase())) {
|
||||||
|
throw new Error('A folder with that name already exists.');
|
||||||
|
}
|
||||||
|
const created = await client.mailboxCreate(name);
|
||||||
|
await client.mailboxSubscribe(created.path).catch(() => {});
|
||||||
|
return { ok: true, folder: { name, path: created.path, id: CUSTOM_FOLDER_PREFIX + created.path }, folders: await listCustomFolders(client) };
|
||||||
|
} catch (error) {
|
||||||
|
if (error.message === 'A folder with that name already exists.') throw error;
|
||||||
|
throw new Error(`Could not create the folder: ${error.message}`);
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('mail:list-drafts', async () => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before opening drafts.');
|
||||||
|
return { drafts: account.drafts || [], offline: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('mail:save-draft', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before saving drafts.');
|
||||||
|
const draft = {
|
||||||
|
id: String(input?.id || randomUUID()),
|
||||||
|
to: String(input?.to || '').slice(0, 4000),
|
||||||
|
cc: String(input?.cc || '').slice(0, 4000),
|
||||||
|
subject: String(input?.subject || '').slice(0, 998),
|
||||||
|
text: String(input?.text || '').slice(0, 500000),
|
||||||
|
updatedAt: Date.now()
|
||||||
|
};
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
|
const drafts = saved.drafts || [];
|
||||||
|
saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500);
|
||||||
|
});
|
||||||
|
return draft;
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('mail:delete-draft', async (_event, id) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before deleting drafts.');
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id);
|
||||||
|
});
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('mail:set-snooze', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before setting a reminder.');
|
||||||
|
const uid = Number(input?.uid);
|
||||||
|
const folder = String(input?.sourceFolder || input?.folder || 'Inbox');
|
||||||
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||||
|
if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.');
|
||||||
|
const dueAt = input?.dueAt == null ? null : Number(input.dueAt);
|
||||||
|
if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) {
|
||||||
|
throw new Error('Choose a reminder time in the future.');
|
||||||
|
}
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
|
const snoozes = saved.snoozedMessages || [];
|
||||||
|
const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder));
|
||||||
|
if (dueAt != null) {
|
||||||
|
remaining.push({
|
||||||
|
uid,
|
||||||
|
folder,
|
||||||
|
dueAt,
|
||||||
|
subject: String(input.subject || '').slice(0, 200)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
saved.snoozedMessages = remaining;
|
||||||
|
});
|
||||||
|
sendMailSyncUpdate({
|
||||||
|
accountId: account.id,
|
||||||
|
foldersChanged: ['Snoozed', folder]
|
||||||
|
});
|
||||||
|
return { ok: true, snoozed: dueAt != null };
|
||||||
|
});
|
||||||
|
|
||||||
|
async function applyMessageAction(account, input) {
|
||||||
const uid = Number(input?.uid);
|
const uid = Number(input?.uid);
|
||||||
const folder = String(input?.folder || 'Inbox');
|
const folder = String(input?.folder || 'Inbox');
|
||||||
const action = String(input?.action || '');
|
const action = String(input?.action || '');
|
||||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||||
if (!['star', 'unread', 'archive', 'delete'].includes(action)) throw new Error('That mail action is not supported.');
|
if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
|
||||||
const client = imapClient(account);
|
const client = imapClient(account);
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
@@ -547,17 +1039,102 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
|
|||||||
} else {
|
} else {
|
||||||
const target = action === 'archive'
|
const target = action === 'archive'
|
||||||
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
|
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
|
||||||
: await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash');
|
: action === 'delete'
|
||||||
if (action === 'delete' && sourcePath === target) await client.messageDelete(uid, { uid: true });
|
? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
|
||||||
|
: 'INBOX';
|
||||||
|
if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
|
||||||
|
if (action === 'delete') await client.messageDelete(uid, { uid: true });
|
||||||
|
}
|
||||||
else await client.messageMove(uid, target, { uid: true });
|
else await client.messageMove(uid, target, { uid: true });
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
lock.release();
|
lock.release();
|
||||||
}
|
}
|
||||||
|
if (action === 'archive' || action === 'delete' || action === 'inbox') {
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (saved) {
|
||||||
|
saved.snoozedMessages = (saved.snoozedMessages || [])
|
||||||
|
.filter(item => Number(item.uid) !== uid || item.folder !== folder);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} finally {
|
} finally {
|
||||||
if (client.usable) await client.logout().catch(() => {});
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isConnectivityFailure(error) {
|
||||||
|
const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']);
|
||||||
|
for (let current = error; current; current = current.cause) {
|
||||||
|
if (networkCodes.has(current.code)) return true;
|
||||||
|
if (/network is unreachable|connection timed out|connection refused|could not resolve|socket hang up/i.test(current.message || '')) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyQueuedActionToCache(account, input) {
|
||||||
|
const folder = String(input.folder || 'Inbox');
|
||||||
|
const cache = account.mailCache?.[folder];
|
||||||
|
if (!cache) return;
|
||||||
|
const index = cache.findIndex(message => Number(message.uid || message.id) === Number(input.uid));
|
||||||
|
if (index < 0) return;
|
||||||
|
const [message] = cache.splice(index, 1);
|
||||||
|
if (input.action === 'star' || input.action === 'unread') {
|
||||||
|
message[input.action] = Boolean(input.enabled);
|
||||||
|
cache.splice(index, 0, message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const target = input.action === 'archive' ? 'Archive' : input.action === 'delete' ? 'Trash' : input.action === 'inbox' ? 'Inbox' : null;
|
||||||
|
if (!target) {
|
||||||
|
cache.splice(index, 0, message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
message.sourceFolder = target;
|
||||||
|
message.archived = target === 'Archive';
|
||||||
|
message.deleted = target === 'Trash';
|
||||||
|
account.mailCache[target] = account.mailCache[target] || [];
|
||||||
|
account.mailCache[target] = [...account.mailCache[target].filter(item => Number(item.uid || item.id) !== Number(input.uid)), message].slice(-50);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushMailOutbox(account) {
|
||||||
|
const operations = [...(account.mailOutbox || [])];
|
||||||
|
for (const operation of operations) {
|
||||||
|
try {
|
||||||
|
if (operation.type === 'send') await sendMailNow(account, operation.data);
|
||||||
|
else if (operation.type === 'action') await applyMessageAction(account, operation.data);
|
||||||
|
else throw new Error('Unsupported queued mail operation.');
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (saved) saved.mailOutbox = (saved.mailOutbox || []).filter(item => item.id !== operation.id);
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (isConnectivityFailure(error)) break;
|
||||||
|
console.error(`Could not complete queued mail operation ${operation.id}:`, error);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ipcMain.handle('mail:update-message', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before changing messages.');
|
||||||
|
try {
|
||||||
|
return await applyMessageAction(account, input);
|
||||||
|
} catch (error) {
|
||||||
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
|
saved.mailOutbox = saved.mailOutbox || [];
|
||||||
|
saved.mailOutbox = saved.mailOutbox.filter(item => !(item.type === 'action' &&
|
||||||
|
Number(item.data?.uid) === Number(input.uid) && item.data?.folder === input.folder && item.data?.action === input.action));
|
||||||
|
saved.mailOutbox.push({ id: randomUUID(), type: 'action', data: input, createdAt: Date.now() });
|
||||||
|
applyQueuedActionToCache(saved, input);
|
||||||
|
});
|
||||||
|
return { ok: true, queued: true };
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.handle('mail:save-attachment', async (event, input) => {
|
ipcMain.handle('mail:save-attachment', async (event, input) => {
|
||||||
@@ -592,26 +1169,89 @@ ipcMain.handle('mail:save-attachment', async (event, input) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('mail:preview-attachment', async (_event, input) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before previewing attachments.');
|
||||||
|
const uid = Number(input?.uid);
|
||||||
|
const folder = String(input?.folder || 'Inbox');
|
||||||
|
const filename = String(input?.filename || 'attachment');
|
||||||
|
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||||
|
const client = imapClient(account);
|
||||||
|
try {
|
||||||
|
await client.connect();
|
||||||
|
const mailboxPath = await folderPath(client, folder);
|
||||||
|
if (!mailboxPath) throw new Error('That mail folder could not be found.');
|
||||||
|
const lock = await client.getMailboxLock(mailboxPath);
|
||||||
|
try {
|
||||||
|
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
|
||||||
|
if (!item?.source) throw new Error('The message is no longer available.');
|
||||||
|
const parsed = await simpleParser(item.source);
|
||||||
|
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename);
|
||||||
|
if (!attachment) throw new Error('No attachment was found in this message.');
|
||||||
|
const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0];
|
||||||
|
const size = attachment.content.length;
|
||||||
|
if (/^image\/(png|jpe?g|gif|webp|bmp|svg\+xml)$/.test(mimeType)) {
|
||||||
|
if (size > 5 * 1048576) return { kind: 'none', reason: 'This image is too large to preview. Download it instead.' };
|
||||||
|
return { kind: 'image', dataUrl: `data:${mimeType};base64,${attachment.content.toString('base64')}` };
|
||||||
|
}
|
||||||
|
if (mimeType.startsWith('text/') || ['application/json', 'application/xml'].includes(mimeType)) {
|
||||||
|
return { kind: 'text', text: attachment.content.subarray(0, 100000).toString('utf8'), truncated: size > 100000 };
|
||||||
|
}
|
||||||
|
return { kind: 'none', reason: 'No preview is available for this file type. Download it to open it.' };
|
||||||
|
} finally {
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (client.usable) await client.logout().catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle('mail:open-external', async (event, rawUrl) => {
|
||||||
|
let target;
|
||||||
|
try {
|
||||||
|
target = new URL(String(rawUrl || ''));
|
||||||
|
} catch {
|
||||||
|
throw new Error('This link is not a valid web address.');
|
||||||
|
}
|
||||||
|
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
|
||||||
|
throw new Error('Only standard web links can be opened from mail.');
|
||||||
|
}
|
||||||
|
const parent = BrowserWindow.fromWebContents(event.sender);
|
||||||
|
const confirmation = await dialog.showMessageBox(parent, {
|
||||||
|
type: 'warning',
|
||||||
|
title: 'Open external link?',
|
||||||
|
message: 'Email links can lead to fake sign-in pages or harmful content.',
|
||||||
|
detail: `Check the full address before continuing:\n${target.href}`,
|
||||||
|
buttons: ['Cancel', 'Open link'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 0,
|
||||||
|
noLink: true
|
||||||
|
});
|
||||||
|
if (confirmation.response !== 1) return { opened: false };
|
||||||
|
await shell.openExternal(target.href);
|
||||||
|
return { opened: true };
|
||||||
|
});
|
||||||
|
|
||||||
ipcMain.handle('mail:sync-inbox', async () => {
|
ipcMain.handle('mail:sync-inbox', async () => {
|
||||||
const account = await readAccount();
|
const account = await readAccount();
|
||||||
if (!account) throw new Error('Add a mail account before syncing.');
|
if (!account) throw new Error('Add a mail account before syncing.');
|
||||||
return fetchMailbox(account, 'Inbox');
|
return fetchMailbox(account, 'Inbox');
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.handle('mail:send', async (_event, message) => {
|
async function sendMailNow(account, message) {
|
||||||
const account = await readAccount();
|
|
||||||
if (!account) throw new Error('Add a mail account before sending.');
|
|
||||||
const to = String(message?.to || '').trim();
|
const to = String(message?.to || '').trim();
|
||||||
if (!to) throw new Error('Add at least one recipient.');
|
if (!to) throw new Error('Add at least one recipient.');
|
||||||
const transport = smtpTransport(account);
|
const transport = smtpTransport(account);
|
||||||
const sentMessageId = `<${require('node:crypto').randomUUID()}@ep-mail.local>`;
|
const sentMessageId = String(message.messageId || `<${require('node:crypto').randomUUID()}@ep-mail.local>`);
|
||||||
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||||
|
const body = String(message?.text || '').slice(0, 500000);
|
||||||
|
const signature = String(account.signature || '').slice(0, 5000);
|
||||||
const messageOptions = {
|
const messageOptions = {
|
||||||
from: { name: fromName, address: account.email },
|
from: { name: fromName, address: account.email },
|
||||||
to,
|
to,
|
||||||
cc: String(message.cc || '').trim() || undefined,
|
cc: String(message.cc || '').trim() || undefined,
|
||||||
subject: String(message.subject || '(no subject)').slice(0, 998),
|
subject: String(message.subject || '(no subject)').slice(0, 998),
|
||||||
text: String(message.text || '').slice(0, 500000),
|
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
|
||||||
messageId: sentMessageId
|
messageId: sentMessageId
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
@@ -642,6 +1282,24 @@ ipcMain.handle('mail:send', async (_event, message) => {
|
|||||||
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
|
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
|
||||||
}
|
}
|
||||||
return { ok: true, savedToSent };
|
return { ok: true, savedToSent };
|
||||||
|
}
|
||||||
|
|
||||||
|
ipcMain.handle('mail:send', async (_event, message) => {
|
||||||
|
const account = await readAccount();
|
||||||
|
if (!account) throw new Error('Add a mail account before sending.');
|
||||||
|
const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` };
|
||||||
|
try {
|
||||||
|
return await sendMailNow(account, queuedMessage);
|
||||||
|
} catch (error) {
|
||||||
|
if (!isConnectivityFailure(error)) throw error;
|
||||||
|
await updateAccountStore(store => {
|
||||||
|
const saved = store.accounts.find(item => item.id === account.id);
|
||||||
|
if (!saved) throw new Error('That mail account is no longer available.');
|
||||||
|
saved.mailOutbox = saved.mailOutbox || [];
|
||||||
|
saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() });
|
||||||
|
});
|
||||||
|
return { ok: true, queued: true };
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.handle('mail:disconnect', async (_event, accountId) => {
|
ipcMain.handle('mail:disconnect', async (_event, accountId) => {
|
||||||
@@ -833,8 +1491,7 @@ function createWindow() {
|
|||||||
window.once('ready-to-show', () => window.show());
|
window.once('ready-to-show', () => window.show());
|
||||||
|
|
||||||
window.loadFile(path.join(__dirname, '..', 'index.html'));
|
window.loadFile(path.join(__dirname, '..', 'index.html'));
|
||||||
window.webContents.setWindowOpenHandler(({ url }) => {
|
window.webContents.setWindowOpenHandler(() => {
|
||||||
if (url.startsWith('https://') || url.startsWith('mailto:')) shell.openExternal(url);
|
|
||||||
return { action: 'deny' };
|
return { action: 'deny' };
|
||||||
});
|
});
|
||||||
window.webContents.on('will-navigate', (event, url) => {
|
window.webContents.on('will-navigate', (event, url) => {
|
||||||
@@ -845,9 +1502,17 @@ function createWindow() {
|
|||||||
app.whenReady().then(() => {
|
app.whenReady().then(() => {
|
||||||
app.setAppUserModelId('studio.daybreak.mail');
|
app.setAppUserModelId('studio.daybreak.mail');
|
||||||
createWindow();
|
createWindow();
|
||||||
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
|
const syncTimer = setInterval(() => {
|
||||||
|
void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error));
|
||||||
|
}, backgroundSyncIntervalMs);
|
||||||
syncTimer.unref();
|
syncTimer.unref();
|
||||||
|
const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs);
|
||||||
|
snoozeTimer.unref();
|
||||||
|
void checkSnoozeReminders();
|
||||||
requestBackgroundSync();
|
requestBackgroundSync();
|
||||||
|
powerMonitor.on('suspend', () => {
|
||||||
|
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||||
|
});
|
||||||
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
||||||
app.on('activate', () => {
|
app.on('activate', () => {
|
||||||
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
||||||
@@ -857,3 +1522,7 @@ app.whenReady().then(() => {
|
|||||||
app.on('window-all-closed', () => {
|
app.on('window-all-closed', () => {
|
||||||
if (process.platform !== 'darwin') app.quit();
|
if (process.platform !== 'darwin') app.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
app.on('before-quit', () => {
|
||||||
|
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||||
|
});
|
||||||
|
|||||||
@@ -8,11 +8,19 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
|||||||
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)),
|
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),
|
||||||
|
previewAttachment: details => ipcRenderer.invoke('mail:preview-attachment', 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'),
|
||||||
|
|||||||
@@ -33,6 +33,9 @@
|
|||||||
<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>
|
||||||
|
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||||
|
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
||||||
|
<div id="custom-folders" class="folder-nav"></div>
|
||||||
<div class="sidebar-divider"></div>
|
<div class="sidebar-divider"></div>
|
||||||
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
|
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
|
||||||
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
|
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
|
||||||
@@ -43,7 +46,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">
|
||||||
@@ -62,9 +65,13 @@
|
|||||||
<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>
|
||||||
|
<script src="attachments.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -4,6 +4,155 @@ let mailTotal = 0;
|
|||||||
let mailboxSyncPromise = null;
|
let mailboxSyncPromise = null;
|
||||||
let mailboxSyncQueued = false;
|
let mailboxSyncQueued = false;
|
||||||
let mailboxRefreshPending = 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 & 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');
|
||||||
@@ -16,6 +165,8 @@ function updateAccountCard(account) {
|
|||||||
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');
|
const profileButton = $('.top-avatar');
|
||||||
if (profileButton) {
|
if (profileButton) {
|
||||||
@@ -28,11 +179,46 @@ function openMailAccount(existingAccount = null) {
|
|||||||
const root = $('#modal-root');
|
const root = $('#modal-root');
|
||||||
const editing = Boolean(existingAccount);
|
const editing = Boolean(existingAccount);
|
||||||
const displayName = existingAccount?.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>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><p class="account-note">This display name is saved for this mailbox and used on outgoing messages. IMAP uses STARTTLS on port 143 · SMTP uses STARTTLS on port 587.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & 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 & reconnect' : 'Test & 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');
|
||||||
@@ -49,7 +235,16 @@ function openMailAccount(existingAccount = null) {
|
|||||||
password,
|
password,
|
||||||
displayName: name,
|
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)
|
||||||
@@ -81,6 +276,124 @@ 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) {
|
if (mailboxSyncPromise) {
|
||||||
mailboxSyncQueued = true;
|
mailboxSyncQueued = true;
|
||||||
@@ -94,9 +407,15 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
if (refresh) refresh.disabled = true;
|
if (refresh) refresh.disabled = true;
|
||||||
const sync = (async () => {
|
const sync = (async () => {
|
||||||
try {
|
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 previouslyActiveMessage = activeMessage;
|
||||||
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
|
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset);
|
||||||
const result = await window.daybreakMail.syncFolder(activeFolder, offset);
|
const result = await window.daybreakMail.syncFolder(activeFolder, offset, mailSearchFilters());
|
||||||
if (options.append) messages.push(...result.messages);
|
if (options.append) messages.push(...result.messages);
|
||||||
else messages.splice(0, messages.length, ...result.messages);
|
else messages.splice(0, messages.length, ...result.messages);
|
||||||
messages.forEach(message => {
|
messages.forEach(message => {
|
||||||
@@ -118,20 +437,24 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||||
const loadMore = $('#load-more');
|
const loadMore = $('#load-more');
|
||||||
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
|
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total);
|
||||||
|
query = '';
|
||||||
renderList();
|
renderList();
|
||||||
if (activeMessage) {
|
if (activeMessage) {
|
||||||
openMessage(activeMessage);
|
openMessage(activeMessage);
|
||||||
const current = messages.find(message => message.id === activeMessage);
|
const current = messages.find(message => message.id === activeMessage);
|
||||||
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
||||||
}
|
}
|
||||||
else $('#reader-pane').innerHTML = emptyReader();
|
else $('#reader-pane').innerHTML = emptyReader();
|
||||||
updateAccountCard(connectedMailAccount);
|
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`);
|
if (showToast) toast(`Synced ${messages.length} messages`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast(error.message || 'Could not sync the inbox');
|
toast(error.message || 'Could not sync the inbox');
|
||||||
} finally {
|
} finally {
|
||||||
if (refresh) refresh.disabled = false;
|
if (refresh) refresh.disabled = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
})();
|
})();
|
||||||
mailboxSyncPromise = sync;
|
mailboxSyncPromise = sync;
|
||||||
try {
|
try {
|
||||||
@@ -146,6 +469,48 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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 => {
|
window.daybreakMail.getAppVersion().then(version => {
|
||||||
document.title = `ep-mail v${version}`;
|
document.title = `ep-mail v${version}`;
|
||||||
}).catch(error => {
|
}).catch(error => {
|
||||||
@@ -173,6 +538,9 @@ if (window.daybreakMail) {
|
|||||||
window.addEventListener('focus', () => {
|
window.addEventListener('focus', () => {
|
||||||
if (connectedMailAccount) syncMailbox(false);
|
if (connectedMailAccount) syncMailbox(false);
|
||||||
});
|
});
|
||||||
|
window.addEventListener('online', () => {
|
||||||
|
if (connectedMailAccount) syncMailbox(false, { offset: 0 });
|
||||||
|
});
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
|
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') {
|
||||||
syncMailbox(false);
|
syncMailbox(false);
|
||||||
@@ -184,8 +552,13 @@ if (window.daybreakMail) {
|
|||||||
});
|
});
|
||||||
$('#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 });
|
||||||
}
|
}
|
||||||
@@ -218,9 +591,20 @@ if (window.daybreakMail) {
|
|||||||
text: $('#compose-body').value,
|
text: $('#compose-body').value,
|
||||||
displayName: connectedMailAccount.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 ↗';
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.1.15",
|
"version": "0.2.3",
|
||||||
"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,14 @@
|
|||||||
"productivity.js",
|
"productivity.js",
|
||||||
"account-ui.js",
|
"account-ui.js",
|
||||||
"dav-ui.js",
|
"dav-ui.js",
|
||||||
|
"shortcuts.js",
|
||||||
|
"attachments.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 +81,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",
|
||||||
|
|||||||
@@ -0,0 +1,554 @@
|
|||||||
|
(() => {
|
||||||
|
// 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(),
|
||||||
|
previewAttachment: (details) => EpMail.previewAttachment(details),
|
||||||
|
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 *)
|
||||||
|
*/
|
||||||
@@ -34,16 +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);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
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(),
|
||||||
|
previewAttachment: details => EpMail.previewAttachment(details),
|
||||||
|
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)
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
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',
|
||||||
|
'attachments.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;
|
||||||
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
const CACHE='ep-mail-v2';
|
const CACHE='ep-mail-v5';
|
||||||
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','./attachments.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'))))});
|
||||||
|
|||||||
@@ -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);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
@@ -114,3 +114,17 @@ 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}
|
||||||
|
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{}));
|
||||||
|
const messages = [];
|
||||||
|
const contacts=[];
|
||||||
|
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
|
||||||
|
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
||||||
|
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
||||||
|
function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<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">↶ Reply</button><button class="reply-button" id="forward">↗ 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 ↗</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);
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
||||||
|
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||||
|
let attachmentItems = [];
|
||||||
|
|
||||||
|
function attachmentKind(filename) {
|
||||||
|
const ext = String(filename).toLowerCase().split('.').pop();
|
||||||
|
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
||||||
|
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
||||||
|
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
||||||
|
return 'Other';
|
||||||
|
}
|
||||||
|
|
||||||
|
function attachmentSize(size) {
|
||||||
|
if (!size) return '';
|
||||||
|
if (typeof size === 'string') return size;
|
||||||
|
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function previewAttachment(target, details) {
|
||||||
|
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
||||||
|
target.textContent = 'Previews are available for connected mailbox messages.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
target.textContent = 'Loading preview…';
|
||||||
|
try {
|
||||||
|
const result = await window.daybreakMail.previewAttachment(details);
|
||||||
|
target.replaceChildren();
|
||||||
|
if (result.kind === 'image') {
|
||||||
|
const image = document.createElement('img');
|
||||||
|
image.className = 'attachment-preview-image';
|
||||||
|
image.alt = details.filename;
|
||||||
|
image.src = result.dataUrl;
|
||||||
|
target.append(image);
|
||||||
|
} else if (result.kind === 'text') {
|
||||||
|
const pre = document.createElement('pre');
|
||||||
|
pre.className = 'attachment-preview-text';
|
||||||
|
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
||||||
|
target.append(pre);
|
||||||
|
} else {
|
||||||
|
target.textContent = result.reason || 'No preview is available for this file type.';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
target.textContent = error.message || 'Could not load the preview.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadAttachment(details) {
|
||||||
|
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
|
||||||
|
window.daybreakMail.saveAttachment(details)
|
||||||
|
.then(result => { if (result.saved) toast('Attachment saved'); })
|
||||||
|
.catch(error => toast(error.message || 'Could not save attachment'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a Preview button to each attachment in the reader.
|
||||||
|
if (typeof openMessage === 'function') {
|
||||||
|
const baseOpenMessage = openMessage;
|
||||||
|
openMessage = function (id) {
|
||||||
|
baseOpenMessage(id);
|
||||||
|
const message = messages.find(item => item.id === id);
|
||||||
|
if (!message?.uid) return;
|
||||||
|
$$('#reader-pane .attachment').forEach(row => {
|
||||||
|
const download = row.querySelector('.download');
|
||||||
|
if (!download || row.querySelector('.preview-attachment')) return;
|
||||||
|
const button = document.createElement('button');
|
||||||
|
button.className = 'preview-attachment icon-button';
|
||||||
|
button.title = 'Preview';
|
||||||
|
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
||||||
|
button.textContent = '👁';
|
||||||
|
button.addEventListener('click', event => {
|
||||||
|
event.stopPropagation();
|
||||||
|
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
||||||
|
if (panel) { panel.remove(); return; }
|
||||||
|
panel = document.createElement('div');
|
||||||
|
panel.className = 'attachment-preview';
|
||||||
|
row.after(panel);
|
||||||
|
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
|
||||||
|
});
|
||||||
|
download.before(button);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function collectAttachments() {
|
||||||
|
const items = [];
|
||||||
|
for (const folder of attachmentFolders) {
|
||||||
|
let offset = 0;
|
||||||
|
for (let page = 0; page < 5; page += 1) {
|
||||||
|
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
||||||
|
for (const message of result.messages || []) {
|
||||||
|
for (const file of message.attachments || []) {
|
||||||
|
items.push({
|
||||||
|
uid: message.uid, folder, filename: file.filename, size: file.size,
|
||||||
|
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
||||||
|
kind: attachmentKind(file.filename)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
offset += (result.messages || []).length;
|
||||||
|
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return items.sort((a, b) => b.timestamp - a.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openAttachmentsView() {
|
||||||
|
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
|
||||||
|
const root = $('#modal-root');
|
||||||
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></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(); };
|
||||||
|
const list = $('#attachment-list');
|
||||||
|
const render = () => {
|
||||||
|
const text = $('#attachment-search').value.trim().toLowerCase();
|
||||||
|
const type = $('#attachment-type').value;
|
||||||
|
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
||||||
|
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
||||||
|
list.replaceChildren();
|
||||||
|
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
||||||
|
shown.forEach(item => {
|
||||||
|
const row = document.createElement('div');
|
||||||
|
row.className = 'attachment-row';
|
||||||
|
const info = document.createElement('div');
|
||||||
|
info.className = 'attachment-row-info';
|
||||||
|
const name = document.createElement('strong');
|
||||||
|
name.textContent = item.filename;
|
||||||
|
const meta = document.createElement('small');
|
||||||
|
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
||||||
|
info.append(name, meta);
|
||||||
|
const preview = document.createElement('button');
|
||||||
|
preview.className = 'discard';
|
||||||
|
preview.textContent = 'Preview';
|
||||||
|
const save = document.createElement('button');
|
||||||
|
save.className = 'discard';
|
||||||
|
save.textContent = 'Download';
|
||||||
|
const panel = document.createElement('div');
|
||||||
|
panel.className = 'attachment-preview';
|
||||||
|
panel.hidden = true;
|
||||||
|
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
||||||
|
preview.onclick = () => {
|
||||||
|
panel.hidden = !panel.hidden;
|
||||||
|
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
||||||
|
};
|
||||||
|
save.onclick = () => downloadAttachment(details);
|
||||||
|
row.append(info, preview, save, panel);
|
||||||
|
list.append(row);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
$('#attachment-search').oninput = render;
|
||||||
|
$('#attachment-type').onchange = render;
|
||||||
|
try {
|
||||||
|
attachmentItems = await collectAttachments();
|
||||||
|
if ($('#attachment-list')) render();
|
||||||
|
} catch (error) {
|
||||||
|
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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 & 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);
|
||||||
@@ -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 |
@@ -0,0 +1,77 @@
|
|||||||
|
<!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>
|
||||||
|
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||||
|
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
||||||
|
<div id="custom-folders" class="folder-nav"></div>
|
||||||
|
<div class="sidebar-divider"></div>
|
||||||
|
<div class="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>
|
||||||
|
<script src="attachments.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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 |
@@ -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 |
@@ -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 & 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 & reconnect' : 'Test & 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(() => {});
|
||||||
|
}
|
||||||
@@ -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"}]
|
||||||
|
}
|
||||||
@@ -0,0 +1,554 @@
|
|||||||
|
(() => {
|
||||||
|
// 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(),
|
||||||
|
previewAttachment: (details) => EpMail.previewAttachment(details),
|
||||||
|
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 *)
|
||||||
|
*/
|
||||||
@@ -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);
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
const CACHE='ep-mail-v5';
|
||||||
|
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','./attachments.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'))))});
|
||||||
@@ -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);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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);
|
||||||