Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cf0856197 | ||
|
|
f282065536 | ||
|
|
d7ee8b7c46 |
No files matched your search
+18
-3
@@ -19,6 +19,18 @@ jobs:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# Gitea rejects a workflow file it can't parse without running
|
||||
# anything, which for release.yml only shows up when a tag is pushed.
|
||||
# Parsing them all here catches that on master, before tagging.
|
||||
- name: Check workflow files parse
|
||||
run: |
|
||||
python3 - <<'PY'
|
||||
import glob, yaml
|
||||
for f in sorted(glob.glob(".gitea/workflows/*.yml")):
|
||||
yaml.safe_load(open(f))
|
||||
print("ok", f)
|
||||
PY
|
||||
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
@@ -26,8 +38,8 @@ jobs:
|
||||
java-version: '17'
|
||||
|
||||
# Installed explicitly rather than via android-actions/setup-android
|
||||
# so the SDK package versions are pinned to match compileSdk 35 /
|
||||
# build-tools 35.0.0, instead of whatever the action defaults to.
|
||||
# so the SDK package versions are pinned to match compileSdk 37 /
|
||||
# build-tools 36.0.0, instead of whatever the action defaults to.
|
||||
# Persists in $HOME on this self-hosted runner, so it's a one-time cost.
|
||||
- name: Set up Android SDK
|
||||
run: |
|
||||
@@ -43,7 +55,7 @@ jobs:
|
||||
fi
|
||||
yes | "$SDK/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null 2>&1 || true
|
||||
"$SDK/cmdline-tools/latest/bin/sdkmanager" \
|
||||
"platform-tools" "platforms;android-35" "build-tools;35.0.0" >/dev/null
|
||||
"platform-tools" "platforms;android-37.0" "build-tools;36.0.0" >/dev/null
|
||||
echo "ANDROID_HOME=$SDK" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_SDK_ROOT=$SDK" >> "$GITHUB_ENV"
|
||||
|
||||
@@ -57,6 +69,9 @@ jobs:
|
||||
- name: Build debug APK
|
||||
run: ./gradlew assembleDebug --no-daemon
|
||||
|
||||
- name: Unit tests
|
||||
run: ./gradlew testDebugUnitTest --no-daemon
|
||||
|
||||
# Hard constraint from android-client-spec.md §7: nothing Google-
|
||||
# dependent, including transitive pulls. Cheap to assert here, and far
|
||||
# easier than noticing a library dragged it in three months from now.
|
||||
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
fi
|
||||
yes | "$SDK/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null 2>&1 || true
|
||||
"$SDK/cmdline-tools/latest/bin/sdkmanager" \
|
||||
"platform-tools" "platforms;android-35" "build-tools;35.0.0" >/dev/null
|
||||
"platform-tools" "platforms;android-37.0" "build-tools;36.0.0" >/dev/null
|
||||
echo "ANDROID_HOME=$SDK" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_SDK_ROOT=$SDK" >> "$GITHUB_ENV"
|
||||
|
||||
|
||||
@@ -10,3 +10,8 @@
|
||||
.cxx
|
||||
local.properties
|
||||
.kotlin
|
||||
|
||||
# Local Claude and tooling files
|
||||
/CLAUDE.md
|
||||
/scripts/
|
||||
/.claude/
|
||||
@@ -1,22 +1,61 @@
|
||||
# tern-android
|
||||
|
||||
Android client for [Tern](../) — see [`docs/android-client-spec.md`](docs/android-client-spec.md) and [`docs/branding-spec.md`](docs/branding-spec.md).
|
||||
Android client for [Tern](../). See [`docs/android-client-spec.md`](docs/android-client-spec.md) and [`docs/branding-spec.md`](docs/branding-spec.md).
|
||||
|
||||
**Status: thin scaffold.** The server (IMAP sync + REST API) was the priority for this first pass, and the Android client is the last item in the build order anyway (`server-architecture-spec.md` §9, item 8). What's here:
|
||||
It needs no Google services, so it runs on GrapheneOS as is: nothing from Play Services or Firebase is anywhere in the dependency tree, and CI checks that on every build (§7).
|
||||
|
||||
- Jetpack Compose + Material 3, Kotlin, no Play Services/Firebase anywhere in the dependency tree (§7 — hard constraint).
|
||||
- Dynamic color (Material You) with the branding doc's static palette as the fallback (§2).
|
||||
- Edge-to-edge drawing, `SplashScreen` API, predictive back enabled in the manifest (§3, §6).
|
||||
- Adaptive-layout dependencies present for the list-detail scaffold (§4), not yet used.
|
||||
- Adaptive launcher icon with a **monochrome/themed variant** (§2 / branding §2) — placeholder wing mark, since the real icon design is still an open item in the branding doc.
|
||||
- `allowBackup="false"` — the mail cache shouldn't land in cloud backups (§7).
|
||||
## What's in it
|
||||
|
||||
**Not built yet:** the list-detail mail UI, Room cache, UnifiedPush receiver + `MessagingStyle` notifications, swipe actions, biometric app-lock, first-run/account-setup flow. All of those depend on client-facing server work that also isn't finished.
|
||||
- **First run** (§6): connect to the Tern server, add a mail account if the server has none, then an optional notifications step. That step is the only place the notification permission is asked for.
|
||||
- **Mail**, laid out list–detail (§4): one pane on phones, list and conversation side by side on tablets and unfolded foldables. The drawer is modal on narrow screens and permanent on wide ones. Views are Inbox, All mail, Sent, Junk, Trash, your folders and your tags, plus the Outbox.
|
||||
- **Swipe actions** (§3): right to archive, left to delete, left to restore in Trash. The whole row is the swipe target, so swipes never collide with the system back gesture. Screen readers get the same actions as accessibility actions (§8).
|
||||
- **Reading:**
|
||||
- Plain-text mail renders as text.
|
||||
- HTML mail goes in a locked-down WebView: no JavaScript, and no file, content or network access.
|
||||
- Remote images and tracking pixels stay blocked until you allow them for that message.
|
||||
- Links open in the browser.
|
||||
- **Actions:** archive, delete/restore, mark unread, report spam/not spam, move to folder, tags. These are the same actions the server's rules and the webapp use.
|
||||
- **Compose:** new mail, reply and reply-all (with the same recipient rules as the webapp), drafts, and an outbox showing queued and failed mail.
|
||||
- **Notifications** (§5): details below.
|
||||
- **Offline cache** (§7): a Room database in app-private storage. It opens instantly and stays readable offline. It's excluded from backups and device transfer, and the session token is encrypted with an Android Keystore key.
|
||||
- **Theming** (§2): Material You dynamic colour, falling back to the brand palette. Light, dark, or follow system, set in Settings.
|
||||
|
||||
## Notifications
|
||||
|
||||
Delivery goes through [UnifiedPush](https://unifiedpush.org): a distributor app on the phone (e.g. **ntfy** from F-Droid) keeps one connection to its push server. When new mail should notify, the Tern server pushes to the endpoint the phone registered.
|
||||
|
||||
- **The push carries no content.** It's an encrypted "sync now". Tern then fetches the actual changes over its own authenticated connection. The server's rules decide which mail notifies (*notify* / *don't notify* actions).
|
||||
- **One notification per conversation,** conversation-style (`MessagingStyle`). A busy thread updates in place instead of stacking up, and a summary groups several threads.
|
||||
- **Archive and Mark read** work straight from the notification. They run as background work, so they survive a flaky connection.
|
||||
- **Syncing** runs as WorkManager jobs (§9). While the app is open it also checks for changes every 30 seconds.
|
||||
- **Settings → Notifications** shows the registration state and any error from the last push, lets you choose between distributors when more than one is installed, and can send a test push through the whole chain.
|
||||
|
||||
### Setting up with a self-hosted ntfy
|
||||
|
||||
1. Install ntfy from F-Droid. In its settings, set **Default server** to your ntfy server.
|
||||
2. In Tern, turn notifications on (in first-run or in Settings). Tern registers with ntfy, and ntfy hands it an endpoint on your server.
|
||||
3. The Tern server must be able to reach that endpoint. If it should reach ntfy by a different address than the phone uses, or ntfy sits behind a private CA, see `PUSH_URL_REWRITE`, `PUSH_CA_CERT` and `PUSH_TLS_INSECURE` in the server README.
|
||||
|
||||
## Connecting to your server
|
||||
|
||||
- **Release builds are HTTPS-only.** They trust system CAs and **user-installed** CAs. So a server behind a private CA works once that CA is installed on the phone (Settings → Security → Encryption & credentials → Install a certificate).
|
||||
- **Debug builds also allow plain HTTP,** for a development server such as `http://10.0.2.2:8080` from the emulator.
|
||||
|
||||
## Not built yet
|
||||
|
||||
- **App lock** (§7): biometric or device credential. Agreed to come later.
|
||||
- **Quick reply from the notification** (§10): an open item in the spec.
|
||||
- **Configurable swipe directions** (§10).
|
||||
- **Rules, tags and folders are managed in the webapp.** The app applies them but doesn't edit them.
|
||||
- **Opening attachments.** Conversations show a paperclip when they have attachments. The server stores the files but has no download endpoint yet, so neither client can open them.
|
||||
|
||||
## Building
|
||||
|
||||
```bash
|
||||
./gradlew assembleDebug
|
||||
./gradlew testDebugUnitTest
|
||||
```
|
||||
|
||||
Needs an Android SDK (`ANDROID_HOME` / `local.properties`). Version pins (AGP 8.7, Kotlin 2.0.21, Compose BOM 2024.10.01, compileSdk 35) are deliberately conservative — Android Studio may offer an AGP upgrade on first open, which is fine to accept.
|
||||
- **Toolchain:** AGP 9.4 (built-in Kotlin), Kotlin 2.4, Gradle 9.7, JDK 17. compileSdk 37, targetSdk 36, minSdk 29.
|
||||
- **SDK:** needs an Android SDK (`ANDROID_HOME` or `local.properties`). AGP downloads any missing platform packages itself. CI pins them explicitly.
|
||||
- **Release signing** comes from environment variables. See the release section of the server repo's [`docs/release-process.md`](https://git.app.ygg/mtps/tern-server/src/branch/master/docs/release-process.md).
|
||||
+38
-20
@@ -1,7 +1,8 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
id("org.jetbrains.kotlin.plugin.serialization")
|
||||
id("com.google.devtools.ksp")
|
||||
}
|
||||
|
||||
// Release signing and versioning come from the environment so CI can supply
|
||||
@@ -14,14 +15,14 @@ val buildVersionCode: Int = System.getenv("TERN_VERSION_CODE")?.toInt() ?: 1
|
||||
|
||||
android {
|
||||
namespace = "pl.mtps.tern"
|
||||
compileSdk = 35
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "pl.mtps.tern"
|
||||
// GrapheneOS/modern-Pixel-only target (android-client-spec.md §1) —
|
||||
// no need to support old platform versions for a from-scratch app.
|
||||
minSdk = 29
|
||||
targetSdk = 35
|
||||
targetSdk = 36
|
||||
versionCode = buildVersionCode
|
||||
versionName = buildVersionName
|
||||
|
||||
@@ -55,10 +56,6 @@ android {
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
@@ -70,29 +67,50 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(platform("androidx.compose:compose-bom:2024.10.01"))
|
||||
ksp {
|
||||
arg("room.schemaLocation", "$projectDir/schemas")
|
||||
}
|
||||
|
||||
implementation("androidx.core:core-ktx:1.13.1")
|
||||
implementation("androidx.core:core-splashscreen:1.0.1") // Android 12+ SplashScreen API (§6)
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
|
||||
implementation("androidx.activity:activity-compose:1.9.3")
|
||||
dependencies {
|
||||
val composeBom = platform("androidx.compose:compose-bom:2026.09.00")
|
||||
implementation(composeBom)
|
||||
|
||||
implementation("androidx.core:core-ktx:1.19.0")
|
||||
implementation("androidx.core:core-splashscreen:1.2.0") // Android 12+ SplashScreen API (§6)
|
||||
implementation("androidx.activity:activity-compose:1.13.0")
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.0")
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
|
||||
implementation("androidx.lifecycle:lifecycle-process:2.11.0")
|
||||
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.compose.ui:ui-graphics")
|
||||
implementation("androidx.compose.ui:ui-tooling-preview")
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.material3.adaptive:adaptive:1.0.0")
|
||||
implementation("androidx.compose.material3.adaptive:adaptive-layout:1.0.0")
|
||||
implementation("androidx.compose.material3.adaptive:adaptive-navigation:1.0.0")
|
||||
implementation("androidx.compose.material:material-icons-core")
|
||||
implementation("androidx.compose.material3.adaptive:adaptive:1.3.0")
|
||||
implementation("androidx.compose.material3.adaptive:adaptive-layout:1.3.0")
|
||||
implementation("androidx.compose.material3.adaptive:adaptive-navigation:1.3.0")
|
||||
implementation("androidx.compose.material:material-icons-extended")
|
||||
|
||||
// Local cache (§6 of the server spec, §7 here): Room, not a hand-rolled store.
|
||||
implementation("androidx.room:room-runtime:2.8.5")
|
||||
implementation("androidx.room:room-ktx:2.8.5")
|
||||
ksp("androidx.room:room-compiler:2.8.5")
|
||||
implementation("androidx.datastore:datastore-preferences:1.2.1")
|
||||
// Push-triggered sync runs as WorkManager jobs (§9).
|
||||
implementation("androidx.work:work-runtime-ktx:2.11.2")
|
||||
|
||||
implementation("com.squareup.okhttp3:okhttp:5.3.2")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.11.0")
|
||||
|
||||
// UnifiedPush (§5): the connector only — never the embedded FCM
|
||||
// distributor, which would bring Firebase in.
|
||||
implementation("org.unifiedpush.android:connector:3.3.5")
|
||||
|
||||
debugImplementation("androidx.compose.ui:ui-tooling")
|
||||
debugImplementation("androidx.compose.ui:ui-test-manifest")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation(platform("androidx.compose:compose-bom:2024.10.01"))
|
||||
androidTestImplementation("androidx.test.ext:junit:1.2.1")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
|
||||
androidTestImplementation(composeBom)
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 1,
|
||||
"identityHash": "7e1ac1f2b0caf6b35d3df12e267dba79",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "threads",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`viewKey` TEXT NOT NULL, `threadId` TEXT NOT NULL, `position` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`viewKey`, `threadId`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "viewKey",
|
||||
"columnName": "viewKey",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "threadId",
|
||||
"columnName": "threadId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "position",
|
||||
"columnName": "position",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "json",
|
||||
"columnName": "json",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"viewKey",
|
||||
"threadId"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "messages",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `threadId` TEXT NOT NULL, `position` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "threadId",
|
||||
"columnName": "threadId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "position",
|
||||
"columnName": "position",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "json",
|
||||
"columnName": "json",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "meta",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`key`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "key",
|
||||
"columnName": "key",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "json",
|
||||
"columnName": "json",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"key"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '7e1ac1f2b0caf6b35d3df12e267dba79')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Debug builds only: also allow plain HTTP, for a development server
|
||||
(e.g. http://10.0.2.2:8080 from the emulator). Release builds are
|
||||
HTTPS-only. -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="true">
|
||||
<trust-anchors>
|
||||
<certificates src="system" />
|
||||
<certificates src="user" />
|
||||
</trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
@@ -1,9 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<!-- Requested contextually at runtime, not on first launch (§5). -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- Push-triggered sync runs as expedited work; below Android 12 that
|
||||
briefly uses a data-sync foreground service. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
|
||||
<application
|
||||
android:name=".TernApplication"
|
||||
@@ -13,12 +19,16 @@
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Tern.Splash"
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:allowBackup="false"
|
||||
android:fullBackupContent="false">
|
||||
android:fullBackupContent="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
tools:targetApi="36">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:theme="@style/Theme.Tern.Splash"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:resizeableActivity="true"
|
||||
@@ -28,6 +38,24 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- UnifiedPush events from the distributor (§5). -->
|
||||
<service
|
||||
android:name=".push.TernPushService"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="org.unifiedpush.android.connector.PUSH_EVENT" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<receiver
|
||||
android:name=".notify.NotificationActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<service
|
||||
android:name="androidx.work.impl.foreground.SystemForegroundService"
|
||||
android:foregroundServiceType="dataSync"
|
||||
tools:node="merge" />
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,8 @@
|
||||
package pl.mtps.tern
|
||||
|
||||
import android.content.Context
|
||||
|
||||
object BuildConfigInfo {
|
||||
fun versionName(context: Context): String =
|
||||
runCatching { context.packageManager.getPackageInfo(context.packageName, 0).versionName }.getOrNull() ?: "?"
|
||||
}
|
||||
@@ -1,47 +1,54 @@
|
||||
package pl.mtps.tern
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.mtps.tern.notify.Notifier
|
||||
import pl.mtps.tern.push.Push
|
||||
import pl.mtps.tern.ui.TernApp
|
||||
import pl.mtps.tern.ui.theme.ThemeMode
|
||||
import pl.mtps.tern.ui.theme.TernTheme
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
/** A conversation to open, from a tapped notification. */
|
||||
private var openThread by mutableStateOf<String?>(null)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
installSplashScreen()
|
||||
// Draw behind status bar and gesture nav area (§3) — Scaffold below
|
||||
// handles the inset padding.
|
||||
// Draw behind status bar and gesture nav area (§3); Scaffolds pad.
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
openThread = intent.getStringExtra(Notifier.EXTRA_THREAD)
|
||||
|
||||
// Distributors expect apps to re-register on start; it also heals a
|
||||
// registration lost when the distributor was reinstalled.
|
||||
lifecycleScope.launch {
|
||||
if (tern.settings.session.first() != null && tern.settings.pushWanted.first()) {
|
||||
runCatching { Push.refresh(this@MainActivity) }
|
||||
}
|
||||
}
|
||||
|
||||
setContent {
|
||||
TernTheme {
|
||||
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
|
||||
PlaceholderScreen(Modifier.padding(innerPadding))
|
||||
}
|
||||
val theme by tern.settings.theme.collectAsState(ThemeMode.SYSTEM)
|
||||
val dynamic by tern.settings.dynamicColor.collectAsState(true)
|
||||
TernTheme(themeMode = theme, dynamicColor = dynamic) {
|
||||
TernApp(openThread = openThread, onOpenThreadHandled = { openThread = null })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PlaceholderScreen(modifier: Modifier = Modifier) {
|
||||
Column(modifier = modifier.padding(16.dp)) {
|
||||
Text(text = "Tern", style = MaterialTheme.typography.headlineMedium)
|
||||
Text(
|
||||
text = "Scaffold only. The list-detail mail UI, UnifiedPush notifications, " +
|
||||
"and the local Room cache land in a later phase.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
intent.getStringExtra(Notifier.EXTRA_THREAD)?.let { openThread = it }
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,27 @@
|
||||
package pl.mtps.tern
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import pl.mtps.tern.data.MailRepository
|
||||
import pl.mtps.tern.data.Settings
|
||||
import pl.mtps.tern.data.db.TernDatabase
|
||||
import pl.mtps.tern.notify.Notifier
|
||||
|
||||
class TernApplication : Application()
|
||||
/** Holds the app-wide singletons; small enough not to need a DI framework. */
|
||||
class TernApplication : Application() {
|
||||
lateinit var settings: Settings
|
||||
private set
|
||||
lateinit var repository: MailRepository
|
||||
private set
|
||||
lateinit var notifier: Notifier
|
||||
private set
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
settings = Settings(this)
|
||||
repository = MailRepository(settings, TernDatabase.open(this).cache())
|
||||
notifier = Notifier(this).also { it.createChannels() }
|
||||
}
|
||||
}
|
||||
|
||||
val Context.tern: TernApplication get() = applicationContext as TernApplication
|
||||
@@ -0,0 +1,182 @@
|
||||
package pl.mtps.tern.data
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.put
|
||||
import okhttp3.HttpUrl
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** The server said no: a 4xx/5xx with its `{"error": …}` message. */
|
||||
class ApiException(val status: Int, message: String) : IOException(message) {
|
||||
val unauthorized: Boolean get() = status == 401
|
||||
}
|
||||
|
||||
/**
|
||||
* tern-server's REST API (server-architecture-spec.md §4). The app never
|
||||
* speaks IMAP/SMTP; everything goes through here.
|
||||
*/
|
||||
class Api(
|
||||
private val baseUrl: HttpUrl,
|
||||
private val token: () -> String?,
|
||||
private val client: OkHttpClient = defaultClient,
|
||||
) {
|
||||
companion object {
|
||||
val json = Json { ignoreUnknownKeys = true; explicitNulls = false; encodeDefaults = true }
|
||||
private val JSON = "application/json".toMediaType()
|
||||
val defaultClient: OkHttpClient = OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
/**
|
||||
* Accepts what people type — `mail.example.org`, with or without a
|
||||
* scheme or trailing slash — and returns the server's base URL.
|
||||
* HTTPS unless a scheme is given.
|
||||
*/
|
||||
fun normalizeServerUrl(input: String): HttpUrl {
|
||||
val trimmed = input.trim().trimEnd('/')
|
||||
require(trimmed.isNotEmpty()) { "Enter your Tern server's address" }
|
||||
val withScheme = if ("://" in trimmed) trimmed else "https://$trimmed"
|
||||
return try {
|
||||
withScheme.toHttpUrl()
|
||||
} catch (e: IllegalArgumentException) {
|
||||
throw IllegalArgumentException("That doesn't look like a server address")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun url(path: String, query: Map<String, String?> = emptyMap()): HttpUrl =
|
||||
baseUrl.newBuilder().apply {
|
||||
addPathSegments("api/" + path.trimStart('/'))
|
||||
query.forEach { (k, v) -> if (v != null) addQueryParameter(k, v) }
|
||||
}.build()
|
||||
|
||||
private suspend fun <T> call(
|
||||
method: String,
|
||||
url: HttpUrl,
|
||||
body: String?,
|
||||
serializer: KSerializer<T>?,
|
||||
): T? = withContext(Dispatchers.IO) {
|
||||
val request = Request.Builder().url(url).apply {
|
||||
token()?.let { header("Authorization", "Bearer $it") }
|
||||
method(method, body?.toRequestBody(JSON) ?: if (method == "GET") null else "".toRequestBody(JSON))
|
||||
}.build()
|
||||
client.newCall(request).execute().use { res ->
|
||||
val text = res.body.string()
|
||||
if (!res.isSuccessful) {
|
||||
val message = runCatching {
|
||||
json.parseToJsonElement(text).let { (it as JsonObject)["error"]?.jsonPrimitive?.content }
|
||||
}.getOrNull() ?: "Server answered ${res.code}"
|
||||
throw ApiException(res.code, message)
|
||||
}
|
||||
serializer?.let { json.decodeFromString(it, text) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> get(path: String, s: KSerializer<T>, query: Map<String, String?> = emptyMap()): T =
|
||||
call("GET", url(path, query), null, s)!!
|
||||
|
||||
private suspend fun <B, T> send(method: String, path: String, bs: KSerializer<B>, body: B, s: KSerializer<T>): T =
|
||||
call(method, url(path), json.encodeToString(bs, body), s)!!
|
||||
|
||||
private suspend fun post(path: String, body: JsonObject? = null) {
|
||||
call("POST", url(path), body?.toString(), null as KSerializer<Unit>?)
|
||||
}
|
||||
|
||||
private suspend fun delete(path: String) {
|
||||
call("DELETE", url(path), null, null as KSerializer<Unit>?)
|
||||
}
|
||||
|
||||
// --- auth ---------------------------------------------------------------
|
||||
|
||||
suspend fun signIn(username: String, password: String, register: Boolean): SessionResponse {
|
||||
val body = buildJsonObject { put("username", username); put("password", password) }
|
||||
return call("POST", url(if (register) "auth/register" else "auth/login"), body.toString(), SessionResponse.serializer())!!
|
||||
}
|
||||
|
||||
// --- mail ---------------------------------------------------------------
|
||||
|
||||
suspend fun accounts(): List<Account> = get("accounts", ListSerializer(Account.serializer()))
|
||||
suspend fun addAccount(a: NewAccount): Account = send("POST", "accounts", NewAccount.serializer(), a, Account.serializer())
|
||||
suspend fun folders(): List<Folder> = get("folders", ListSerializer(Folder.serializer()))
|
||||
suspend fun tags(): List<Tag> = get("tags", ListSerializer(Tag.serializer()))
|
||||
|
||||
suspend fun threads(view: MailView, before: String? = null, limit: Int = 50): ThreadPage {
|
||||
val (kind, id) = when (view) {
|
||||
is MailView.InFolder -> "folder" to view.id
|
||||
is MailView.Tagged -> "tag" to view.id
|
||||
else -> view.key to null
|
||||
}
|
||||
return get(
|
||||
"threads", ThreadPage.serializer(),
|
||||
mapOf(
|
||||
"view" to kind,
|
||||
"folder_id" to id.takeIf { view is MailView.InFolder },
|
||||
"tag_id" to id.takeIf { view is MailView.Tagged },
|
||||
"before" to before,
|
||||
"limit" to limit.toString(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun thread(id: String): List<Message> = get("threads/$id", ListSerializer(Message.serializer()))
|
||||
|
||||
suspend fun act(threadId: String, actions: List<JsonObject>) =
|
||||
post("threads/$threadId/actions", buildJsonObject { put("actions", buildJsonArray { actions.forEach { add(it) } }) })
|
||||
|
||||
suspend fun markRead(threadId: String) = post("threads/$threadId/read")
|
||||
|
||||
// --- sending ------------------------------------------------------------
|
||||
|
||||
suspend fun outbox(): List<OutboxItem> = get("outbox", ListSerializer(OutboxItem.serializer()))
|
||||
suspend fun compose(req: ComposeRequest): OutboxItem =
|
||||
send("POST", "outbox", ComposeRequest.serializer(), req, OutboxItem.serializer())
|
||||
suspend fun updateDraft(id: String, d: DraftUpdate): OutboxItem =
|
||||
send("PUT", "outbox/$id", DraftUpdate.serializer(), d, OutboxItem.serializer())
|
||||
suspend fun sendDraft(id: String): OutboxItem = call("POST", url("outbox/$id/send"), "", OutboxItem.serializer())!!
|
||||
suspend fun deleteOutbox(id: String) = delete("outbox/$id")
|
||||
|
||||
// --- sync & push --------------------------------------------------------
|
||||
|
||||
suspend fun events(since: Long?): EventPage =
|
||||
get("events", EventPage.serializer(), mapOf("since" to since?.toString()))
|
||||
|
||||
suspend fun pushInfo(): PushInfo = get("push", PushInfo.serializer())
|
||||
suspend fun devices(): List<Device> = get("devices", ListSerializer(Device.serializer()))
|
||||
suspend fun registerDevice(r: DeviceRequest): Device =
|
||||
send("POST", "devices", DeviceRequest.serializer(), r, Device.serializer())
|
||||
suspend fun deleteDevice(id: String) = delete("devices/$id")
|
||||
suspend fun testDevice(id: String): PushOutcome = call("POST", url("devices/$id/test"), "", PushOutcome.serializer())!!
|
||||
}
|
||||
|
||||
/** Thread actions, in the server's rule-action format. */
|
||||
object Actions {
|
||||
private fun simple(type: String) = buildJsonObject { put("type", type) }
|
||||
val archive get() = simple("archive")
|
||||
val delete get() = simple("delete")
|
||||
val restore get() = simple("restore")
|
||||
val junk get() = simple("junk")
|
||||
val markRead get() = simple("mark_read")
|
||||
val markUnread get() = simple("mark_unread")
|
||||
/** `null` moves back to the inbox — the key must still be present. */
|
||||
fun move(folderId: String?) = buildJsonObject {
|
||||
put("type", "move")
|
||||
if (folderId == null) put("folder_id", JsonNull) else put("folder_id", folderId)
|
||||
}
|
||||
fun tag(id: String) = buildJsonObject { put("type", "tag"); put("tag_id", id) }
|
||||
fun untag(id: String) = buildJsonObject { put("type", "untag"); put("tag_id", id) }
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package pl.mtps.tern.data
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import pl.mtps.tern.data.db.CacheDao
|
||||
import pl.mtps.tern.data.db.CachedMessage
|
||||
import pl.mtps.tern.data.db.CachedMeta
|
||||
import pl.mtps.tern.data.db.CachedThread
|
||||
|
||||
/** New mail the server decided should notify (after rules). */
|
||||
data class NewMail(val threadId: String, val messageId: String, val from: String, val subject: String)
|
||||
|
||||
data class SyncResult(
|
||||
/** Notifying mail since the last sync, oldest first. */
|
||||
val newMail: List<NewMail> = emptyList(),
|
||||
/** Threads that changed in any way (read elsewhere, archived, …). */
|
||||
val touchedThreads: Set<String> = emptySet(),
|
||||
/** Anything could have changed; the cache was rebuilt. */
|
||||
val reset: Boolean = false,
|
||||
)
|
||||
|
||||
class NotSignedIn : IllegalStateException("Not signed in")
|
||||
|
||||
/**
|
||||
* The app's single way to mail: talks to the server, keeps the cache in
|
||||
* step, and exposes the cache as flows for the UI.
|
||||
*/
|
||||
class MailRepository(private val settings: Settings, private val cache: CacheDao) {
|
||||
private val json = Api.json
|
||||
@Volatile private var apiFor: Pair<Session, Api>? = null
|
||||
|
||||
suspend fun api(): Api {
|
||||
val session = settings.currentSession() ?: throw NotSignedIn()
|
||||
apiFor?.let { (s, a) -> if (s == session) return a }
|
||||
return Api(Api.normalizeServerUrl(session.serverUrl), { session.token }).also { apiFor = session to it }
|
||||
}
|
||||
|
||||
// --- session --------------------------------------------------------------
|
||||
|
||||
suspend fun signIn(server: String, username: String, password: String, register: Boolean) {
|
||||
val base = Api.normalizeServerUrl(server)
|
||||
val res = Api(base, { null }).signIn(username.trim(), password, register)
|
||||
cache.clearAll()
|
||||
settings.signIn(base.toString().trimEnd('/'), res.token, username.trim())
|
||||
// Start the change feed from "now": everything older is loaded fresh.
|
||||
settings.setCursor(api().events(null).cursor)
|
||||
}
|
||||
|
||||
suspend fun signOut() {
|
||||
settings.signOut()
|
||||
cache.clearAll()
|
||||
apiFor = null
|
||||
}
|
||||
|
||||
// --- cached reads -------------------------------------------------------
|
||||
|
||||
fun threads(view: MailView): Flow<List<ThreadSummary>> =
|
||||
cache.threads(view.key).map { rows -> rows.map { json.decodeFromString(ThreadSummary.serializer(), it.json) } }
|
||||
|
||||
fun messages(threadId: String): Flow<List<Message>> =
|
||||
cache.messages(threadId).map { rows -> rows.map { json.decodeFromString(Message.serializer(), it.json) } }
|
||||
|
||||
private fun <T> metaList(key: String, s: KSerializer<T>): Flow<List<T>> =
|
||||
cache.meta(key).map { row -> row?.let { json.decodeFromString(ListSerializer(s), it.json) } ?: emptyList() }
|
||||
|
||||
val folders: Flow<List<Folder>> = metaList("folders", Folder.serializer())
|
||||
val tags: Flow<List<Tag>> = metaList("tags", Tag.serializer())
|
||||
val accounts: Flow<List<Account>> = metaList("accounts", Account.serializer())
|
||||
val outbox: Flow<List<OutboxItem>> = metaList("outbox", OutboxItem.serializer())
|
||||
|
||||
private suspend fun <T> putMeta(key: String, s: KSerializer<T>, items: List<T>) =
|
||||
cache.putMeta(CachedMeta(key, json.encodeToString(ListSerializer(s), items)))
|
||||
|
||||
// --- refreshes ----------------------------------------------------------
|
||||
|
||||
/** Re-reads a view from the top, keeping as many rows as were loaded. Returns the next-page cursor. */
|
||||
suspend fun refresh(view: MailView): String? {
|
||||
val keep = cache.threadCount(view.key).coerceIn(50, 200)
|
||||
val page = api().threads(view, limit = keep)
|
||||
cache.replaceView(view.key, page.threads.mapIndexed { i, t -> row(view, i, t) })
|
||||
return page.nextCursor
|
||||
}
|
||||
|
||||
suspend fun loadMore(view: MailView, cursor: String): String? {
|
||||
val start = cache.threadCount(view.key)
|
||||
val page = api().threads(view, before = cursor)
|
||||
cache.putThreads(page.threads.mapIndexed { i, t -> row(view, start + i, t) })
|
||||
return page.nextCursor
|
||||
}
|
||||
|
||||
private fun row(view: MailView, position: Int, t: ThreadSummary) =
|
||||
CachedThread(view.key, t.threadId, position, json.encodeToString(ThreadSummary.serializer(), t))
|
||||
|
||||
suspend fun refreshThread(threadId: String): List<Message> {
|
||||
val messages = api().thread(threadId)
|
||||
cache.replaceMessages(
|
||||
threadId,
|
||||
messages.mapIndexed { i, m -> CachedMessage(m.id, threadId, i, json.encodeToString(Message.serializer(), m)) },
|
||||
)
|
||||
return messages
|
||||
}
|
||||
|
||||
suspend fun refreshMeta() {
|
||||
val api = api()
|
||||
putMeta("folders", Folder.serializer(), api.folders())
|
||||
putMeta("tags", Tag.serializer(), api.tags())
|
||||
putMeta("accounts", Account.serializer(), api.accounts())
|
||||
}
|
||||
|
||||
suspend fun refreshOutbox() = putMeta("outbox", OutboxItem.serializer(), api().outbox())
|
||||
|
||||
// --- actions ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Applies actions to a conversation. When the action takes it out of the
|
||||
* current view (archive, delete, move…), the row is removed from the
|
||||
* cache first so the list reacts at once; the refresh that follows
|
||||
* corrects anything the guess got wrong.
|
||||
*/
|
||||
suspend fun act(threadId: String, actions: List<JsonObject>, view: MailView?, leavesView: Boolean) {
|
||||
if (leavesView && view != null) dropFromView(view, threadId)
|
||||
try {
|
||||
api().act(threadId, actions)
|
||||
} finally {
|
||||
view?.let { runCatching { refresh(it) } }
|
||||
runCatching { refreshThread(threadId) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun dropFromView(view: MailView, threadId: String) {
|
||||
val current = cache.threads(view.key).first()
|
||||
cache.replaceView(view.key, current.filter { it.threadId != threadId }.mapIndexed { i, r -> r.copy(position = i) })
|
||||
}
|
||||
|
||||
suspend fun markRead(threadId: String) {
|
||||
api().markRead(threadId)
|
||||
runCatching { refreshThread(threadId) }
|
||||
}
|
||||
|
||||
// --- sending ------------------------------------------------------------
|
||||
|
||||
suspend fun compose(req: ComposeRequest): OutboxItem = api().compose(req).also { runCatching { refreshOutbox() } }
|
||||
|
||||
suspend fun saveDraft(id: String, d: DraftUpdate, send: Boolean): OutboxItem {
|
||||
val api = api()
|
||||
var item = api.updateDraft(id, d)
|
||||
if (send) item = api.sendDraft(id)
|
||||
runCatching { refreshOutbox() }
|
||||
return item
|
||||
}
|
||||
|
||||
suspend fun deleteOutbox(id: String) {
|
||||
api().deleteOutbox(id)
|
||||
runCatching { refreshOutbox() }
|
||||
}
|
||||
|
||||
suspend fun addAccount(a: NewAccount): Account = api().addAccount(a).also { runCatching { refreshMeta() } }
|
||||
|
||||
// --- delta sync ---------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Catches up on the server's change log since the last sync
|
||||
* (`GET /api/events`) and refreshes what it touched. Runs on push, on
|
||||
* app start and periodically while the app is open. The cursor only
|
||||
* advances once the changes are applied, so a failed sync repeats
|
||||
* rather than skipping anything.
|
||||
*/
|
||||
suspend fun sync(): SyncResult {
|
||||
val api = api()
|
||||
var cursor = settings.cursor() ?: run {
|
||||
settings.setCursor(api.events(null).cursor)
|
||||
refreshEverything()
|
||||
return SyncResult(reset = true)
|
||||
}
|
||||
|
||||
val events = mutableListOf<LiveEvent>()
|
||||
while (true) {
|
||||
val page = api.events(cursor)
|
||||
if (page.reset) {
|
||||
refreshEverything()
|
||||
settings.setCursor(page.cursor)
|
||||
return SyncResult(reset = true)
|
||||
}
|
||||
events += page.events
|
||||
cursor = page.cursor
|
||||
if (!page.more) break
|
||||
}
|
||||
if (events.isEmpty()) return SyncResult()
|
||||
|
||||
val newMail = mutableListOf<NewMail>()
|
||||
val touched = mutableSetOf<String>()
|
||||
var mailChanged = false
|
||||
var everything = false
|
||||
var meta = false
|
||||
var outbox = false
|
||||
for (e in events) {
|
||||
when (e.kind) {
|
||||
"message_new" -> {
|
||||
mailChanged = true
|
||||
val thread = e.data.str("thread_id")
|
||||
thread?.let(touched::add)
|
||||
if (e.data["notify"]?.jsonPrimitive?.booleanOrNull == true && thread != null) {
|
||||
newMail += NewMail(
|
||||
threadId = thread,
|
||||
messageId = e.data.str("message_id") ?: "",
|
||||
from = e.data.str("from") ?: "Unknown sender",
|
||||
subject = e.data.str("subject") ?: "(no subject)",
|
||||
)
|
||||
}
|
||||
}
|
||||
"mailbox_changed" -> {
|
||||
mailChanged = true
|
||||
val ids = e.data["thread_ids"]
|
||||
if (ids == null || ids is JsonNull) everything = true
|
||||
else ids.jsonArray.mapNotNullTo(touched) { it.jsonPrimitive.contentOrNull }
|
||||
}
|
||||
"config_changed" -> meta = true
|
||||
"outbox_changed" -> outbox = true
|
||||
}
|
||||
}
|
||||
|
||||
if (mailChanged) refresh(MailView.Inbox)
|
||||
if (meta) refreshMeta()
|
||||
if (outbox) refreshOutbox()
|
||||
// Keep opened conversations current; others load when opened.
|
||||
for (t in touched) if (cachedMessageCount(t) > 0) refreshThread(t)
|
||||
settings.setCursor(cursor)
|
||||
return SyncResult(newMail, touched, reset = everything)
|
||||
}
|
||||
|
||||
private suspend fun cachedMessageCount(threadId: String) =
|
||||
cache.messages(threadId).first().size
|
||||
|
||||
private suspend fun refreshEverything() {
|
||||
cache.clearAll()
|
||||
refreshMeta()
|
||||
refresh(MailView.Inbox)
|
||||
refreshOutbox()
|
||||
}
|
||||
|
||||
private fun JsonObject.str(key: String) = this[key]?.jsonPrimitive?.contentOrNull
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package pl.mtps.tern.data
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
|
||||
// Mirrors tern-server's JSON. Unknown fields are ignored (see Api.json), so
|
||||
// the server can grow without breaking installed apps.
|
||||
|
||||
@Serializable
|
||||
data class SessionResponse(val token: String, @SerialName("user_id") val userId: String)
|
||||
|
||||
@Serializable
|
||||
data class Account(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val username: String,
|
||||
@SerialName("email_address") val emailAddress: String? = null,
|
||||
@SerialName("display_name") val displayName: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class NewAccount(
|
||||
val name: String,
|
||||
@SerialName("imap_host") val imapHost: String,
|
||||
@SerialName("imap_port") val imapPort: Int,
|
||||
@SerialName("smtp_host") val smtpHost: String,
|
||||
@SerialName("smtp_port") val smtpPort: Int,
|
||||
val username: String,
|
||||
val password: String,
|
||||
@SerialName("email_address") val emailAddress: String?,
|
||||
@SerialName("display_name") val displayName: String?,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Folder(val id: String, val name: String, val role: String? = null)
|
||||
|
||||
@Serializable
|
||||
data class Tag(val id: String, val name: String, val color: String? = null)
|
||||
|
||||
@Serializable
|
||||
data class ThreadSummary(
|
||||
@SerialName("thread_id") val threadId: String,
|
||||
val subject: String? = null,
|
||||
@SerialName("last_from") val lastFrom: String? = null,
|
||||
@SerialName("last_message_at") val lastMessageAt: String? = null,
|
||||
@SerialName("message_count") val messageCount: Int = 0,
|
||||
@SerialName("unread_count") val unreadCount: Int = 0,
|
||||
@SerialName("has_attachments") val hasAttachments: Boolean = false,
|
||||
@SerialName("tag_ids") val tagIds: List<String> = emptyList(),
|
||||
@SerialName("purges_at") val purgesAt: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ThreadPage(val threads: List<ThreadSummary>, @SerialName("next_cursor") val nextCursor: String? = null)
|
||||
|
||||
@Serializable
|
||||
data class MessageBody(
|
||||
@SerialName("text_body") val textBody: String? = null,
|
||||
@SerialName("html_body") val htmlBody: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Message(
|
||||
val id: String,
|
||||
@SerialName("thread_id") val threadId: String,
|
||||
@SerialName("account_id") val accountId: String,
|
||||
val subject: String? = null,
|
||||
@SerialName("from_addr") val fromAddr: String? = null,
|
||||
@SerialName("from_name") val fromName: String? = null,
|
||||
@SerialName("to_addrs") val toAddrs: List<String> = emptyList(),
|
||||
@SerialName("cc_addrs") val ccAddrs: List<String> = emptyList(),
|
||||
@SerialName("sent_at") val sentAt: String? = null,
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
val flags: List<String> = emptyList(),
|
||||
val source: String = "imap",
|
||||
@SerialName("deleted_at") val deletedAt: String? = null,
|
||||
@SerialName("spam_score") val spamScore: Double? = null,
|
||||
val body: MessageBody? = null,
|
||||
) {
|
||||
/** Flags are IMAP wire format, so unread is the absence of \Seen. */
|
||||
val unread: Boolean get() = "\\Seen" !in flags
|
||||
val sender: String get() = fromName?.takeIf { it.isNotBlank() } ?: fromAddr ?: "Unknown sender"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class OutboxItem(
|
||||
val id: String,
|
||||
@SerialName("account_id") val accountId: String,
|
||||
val status: String,
|
||||
@SerialName("to_addrs") val toAddrs: List<String> = emptyList(),
|
||||
@SerialName("cc_addrs") val ccAddrs: List<String> = emptyList(),
|
||||
@SerialName("bcc_addrs") val bccAddrs: List<String> = emptyList(),
|
||||
val subject: String = "",
|
||||
@SerialName("text_body") val textBody: String = "",
|
||||
@SerialName("last_error") val lastError: String? = null,
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ComposeRequest(
|
||||
@SerialName("account_id") val accountId: String?,
|
||||
val to: List<String>,
|
||||
val cc: List<String>,
|
||||
val bcc: List<String>,
|
||||
val subject: String,
|
||||
@SerialName("text_body") val textBody: String,
|
||||
@SerialName("reply_to_message_id") val replyToMessageId: String? = null,
|
||||
val send: Boolean,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DraftUpdate(
|
||||
val to: List<String>,
|
||||
val cc: List<String>,
|
||||
val bcc: List<String>,
|
||||
val subject: String,
|
||||
@SerialName("text_body") val textBody: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class LiveEvent(val id: Long, val kind: String, val data: JsonObject)
|
||||
|
||||
@Serializable
|
||||
data class EventPage(val events: List<LiveEvent>, val cursor: Long, val reset: Boolean, val more: Boolean)
|
||||
|
||||
@Serializable
|
||||
data class PushInfo(@SerialName("vapid_public_key") val vapidPublicKey: String)
|
||||
|
||||
@Serializable
|
||||
data class Device(
|
||||
val id: String,
|
||||
val name: String? = null,
|
||||
val endpoint: String? = null,
|
||||
@SerialName("last_push_at") val lastPushAt: String? = null,
|
||||
@SerialName("last_error") val lastError: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class DeviceRequest(val endpoint: String, val p256dh: String?, val auth: String?, val name: String?)
|
||||
|
||||
@Serializable
|
||||
data class PushOutcome(val delivered: Boolean, val status: Int? = null, val error: String? = null)
|
||||
|
||||
/** Which slice of the mailbox a list shows — the server's `view` parameter. */
|
||||
sealed interface MailView {
|
||||
val key: String
|
||||
|
||||
data object Inbox : MailView { override val key = "inbox" }
|
||||
data object All : MailView { override val key = "all" }
|
||||
data object Sent : MailView { override val key = "sent" }
|
||||
data object Junk : MailView { override val key = "junk" }
|
||||
data object Trash : MailView { override val key = "trash" }
|
||||
data class InFolder(val id: String) : MailView { override val key = "folder:$id" }
|
||||
data class Tagged(val id: String) : MailView { override val key = "tag:$id" }
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package pl.mtps.tern.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.longPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import pl.mtps.tern.ui.theme.ThemeMode
|
||||
|
||||
private val Context.store: DataStore<Preferences> by preferencesDataStore("tern")
|
||||
|
||||
/** Where the app is signed in, and as whom. */
|
||||
data class Session(val serverUrl: String, val token: String, val username: String)
|
||||
|
||||
/** Small persistent state: the session, sync cursor, push registration, UI prefs. */
|
||||
class Settings(private val context: Context) {
|
||||
private object Keys {
|
||||
val server = stringPreferencesKey("server_url")
|
||||
val token = stringPreferencesKey("token_sealed")
|
||||
val username = stringPreferencesKey("username")
|
||||
val cursor = longPreferencesKey("event_cursor")
|
||||
val deviceId = stringPreferencesKey("device_id")
|
||||
val pushEndpoint = stringPreferencesKey("push_endpoint")
|
||||
val pushWanted = booleanPreferencesKey("push_wanted")
|
||||
val onboarded = booleanPreferencesKey("onboarded")
|
||||
val theme = stringPreferencesKey("theme")
|
||||
val dynamicColor = booleanPreferencesKey("dynamic_color")
|
||||
}
|
||||
|
||||
val session: Flow<Session?> = context.store.data.map { p ->
|
||||
val server = p[Keys.server] ?: return@map null
|
||||
val token = p[Keys.token]?.let(TokenCipher::decrypt) ?: return@map null
|
||||
Session(server, token, p[Keys.username] ?: "")
|
||||
}
|
||||
|
||||
suspend fun currentSession(): Session? = session.first()
|
||||
|
||||
suspend fun signIn(serverUrl: String, token: String, username: String) = context.store.edit {
|
||||
it[Keys.server] = serverUrl
|
||||
it[Keys.token] = TokenCipher.encrypt(token)
|
||||
it[Keys.username] = username
|
||||
it.remove(Keys.cursor)
|
||||
}
|
||||
|
||||
/** Keeps the server address, so signing back in only needs the password. */
|
||||
suspend fun signOut() = context.store.edit {
|
||||
listOf(Keys.token, Keys.cursor, Keys.deviceId, Keys.pushEndpoint, Keys.pushWanted, Keys.onboarded)
|
||||
.forEach { k -> it.remove(k) }
|
||||
}
|
||||
|
||||
val lastServer: Flow<String?> = context.store.data.map { it[Keys.server] }
|
||||
val lastUsername: Flow<String?> = context.store.data.map { it[Keys.username] }
|
||||
|
||||
suspend fun cursor(): Long? = context.store.data.first()[Keys.cursor]
|
||||
suspend fun setCursor(c: Long) = context.store.edit { it[Keys.cursor] = c }
|
||||
|
||||
/** The push registration this install has with the server. */
|
||||
suspend fun device(): Pair<String, String>? {
|
||||
val p = context.store.data.first()
|
||||
return p[Keys.deviceId]?.let { id -> id to (p[Keys.pushEndpoint] ?: "") }
|
||||
}
|
||||
suspend fun setDevice(id: String?, endpoint: String?) = context.store.edit {
|
||||
if (id == null) it.remove(Keys.deviceId) else it[Keys.deviceId] = id
|
||||
if (endpoint == null) it.remove(Keys.pushEndpoint) else it[Keys.pushEndpoint] = endpoint
|
||||
}
|
||||
|
||||
/** Whether the reader turned push notifications on. */
|
||||
val pushWanted: Flow<Boolean> = context.store.data.map { it[Keys.pushWanted] ?: false }
|
||||
suspend fun setPushWanted(on: Boolean) = context.store.edit { it[Keys.pushWanted] = on }
|
||||
|
||||
/** First-run flow finished (account + notifications step, §6). */
|
||||
val onboarded: Flow<Boolean> = context.store.data.map { it[Keys.onboarded] ?: false }
|
||||
suspend fun setOnboarded() = context.store.edit { it[Keys.onboarded] = true }
|
||||
|
||||
val theme: Flow<ThemeMode> = context.store.data.map { p ->
|
||||
p[Keys.theme]?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() } ?: ThemeMode.SYSTEM
|
||||
}
|
||||
suspend fun setTheme(mode: ThemeMode) = context.store.edit { it[Keys.theme] = mode.name }
|
||||
|
||||
val dynamicColor: Flow<Boolean> = context.store.data.map { it[Keys.dynamicColor] ?: true }
|
||||
suspend fun setDynamicColor(on: Boolean) = context.store.edit { it[Keys.dynamicColor] = on }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package pl.mtps.tern.data
|
||||
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/**
|
||||
* Encrypts the session token with a key that lives in the Android Keystore
|
||||
* and never leaves it, so the token isn't sitting in plain text in the
|
||||
* app's files (android-client-spec.md §7). The app sandbox is the first
|
||||
* line; this is the second.
|
||||
*/
|
||||
object TokenCipher {
|
||||
private const val ALIAS = "tern-session"
|
||||
private const val KEYSTORE = "AndroidKeyStore"
|
||||
|
||||
private fun key(): SecretKey {
|
||||
val ks = KeyStore.getInstance(KEYSTORE).apply { load(null) }
|
||||
(ks.getEntry(ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE).apply {
|
||||
init(
|
||||
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.build(),
|
||||
)
|
||||
}.generateKey()
|
||||
}
|
||||
|
||||
fun encrypt(plain: String): String {
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, key()) }
|
||||
val sealed = cipher.iv + cipher.doFinal(plain.toByteArray())
|
||||
return Base64.encodeToString(sealed, Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
/** Null if the value can't be decrypted (e.g. the key was wiped). */
|
||||
fun decrypt(stored: String): String? = runCatching {
|
||||
val bytes = Base64.decode(stored, Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes, 0, 12))
|
||||
String(cipher.doFinal(bytes, 12, bytes.size - 12))
|
||||
}.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package pl.mtps.tern.data.db
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Database
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.Transaction
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
// The local cache (server spec §6, android spec §7). It mirrors what the
|
||||
// server last said rather than modelling mail itself: rows hold the API's
|
||||
// JSON, keyed and ordered for the queries the UI makes. The server stays
|
||||
// the source of truth; the cache makes the app open instantly and readable
|
||||
// offline. It lives in the app's private storage, and allowBackup is off.
|
||||
|
||||
/** One row of a thread list, for one view (inbox, a folder, …). */
|
||||
@Entity(tableName = "threads", primaryKeys = ["viewKey", "threadId"])
|
||||
data class CachedThread(val viewKey: String, val threadId: String, val position: Int, val json: String)
|
||||
|
||||
/** One message of a conversation, with its body. */
|
||||
@Entity(tableName = "messages", primaryKeys = ["id"])
|
||||
data class CachedMessage(val id: String, val threadId: String, val position: Int, val json: String)
|
||||
|
||||
/** Small lists — folders, tags, accounts, outbox — as JSON by name. */
|
||||
@Entity(tableName = "meta", primaryKeys = ["key"])
|
||||
data class CachedMeta(val key: String, val json: String)
|
||||
|
||||
@Dao
|
||||
interface CacheDao {
|
||||
@Query("SELECT * FROM threads WHERE viewKey = :view ORDER BY position")
|
||||
fun threads(view: String): Flow<List<CachedThread>>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM threads WHERE viewKey = :view")
|
||||
suspend fun threadCount(view: String): Int
|
||||
|
||||
@Query("DELETE FROM threads WHERE viewKey = :view")
|
||||
suspend fun clearView(view: String)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun putThreads(rows: List<CachedThread>)
|
||||
|
||||
/** Replaces a view's first page; older pages are re-fetched on scroll. */
|
||||
@Transaction
|
||||
suspend fun replaceView(view: String, rows: List<CachedThread>) {
|
||||
clearView(view)
|
||||
putThreads(rows)
|
||||
}
|
||||
|
||||
@Query("DELETE FROM threads WHERE threadId = :threadId")
|
||||
suspend fun dropThreadEverywhere(threadId: String)
|
||||
|
||||
@Query("SELECT * FROM messages WHERE threadId = :threadId ORDER BY position")
|
||||
fun messages(threadId: String): Flow<List<CachedMessage>>
|
||||
|
||||
@Query("DELETE FROM messages WHERE threadId = :threadId")
|
||||
suspend fun clearMessages(threadId: String)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun putMessages(rows: List<CachedMessage>)
|
||||
|
||||
@Transaction
|
||||
suspend fun replaceMessages(threadId: String, rows: List<CachedMessage>) {
|
||||
clearMessages(threadId)
|
||||
putMessages(rows)
|
||||
}
|
||||
|
||||
@Query("SELECT * FROM meta WHERE `key` = :key")
|
||||
fun meta(key: String): Flow<CachedMeta?>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun putMeta(row: CachedMeta)
|
||||
|
||||
@Query("DELETE FROM threads")
|
||||
suspend fun clearThreads()
|
||||
|
||||
@Query("DELETE FROM messages")
|
||||
suspend fun clearAllMessages()
|
||||
|
||||
@Query("DELETE FROM meta")
|
||||
suspend fun clearMeta()
|
||||
|
||||
@Transaction
|
||||
suspend fun clearAll() {
|
||||
clearThreads()
|
||||
clearAllMessages()
|
||||
clearMeta()
|
||||
}
|
||||
}
|
||||
|
||||
@Database(entities = [CachedThread::class, CachedMessage::class, CachedMeta::class], version = 1)
|
||||
abstract class TernDatabase : RoomDatabase() {
|
||||
abstract fun cache(): CacheDao
|
||||
|
||||
companion object {
|
||||
fun open(context: Context): TernDatabase =
|
||||
Room.databaseBuilder(context, TernDatabase::class.java, "tern-cache.db")
|
||||
// It's a cache: after a schema change, rebuilding from the
|
||||
// server is always correct.
|
||||
.fallbackToDestructiveMigration(dropAllTables = true)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package pl.mtps.tern.notify
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import pl.mtps.tern.sync.ActionWorker
|
||||
import pl.mtps.tern.tern
|
||||
|
||||
/**
|
||||
* Archive / Mark read buttons on a notification. The notification goes
|
||||
* away at once; the server call runs as work so it survives a flaky
|
||||
* connection instead of being lost with this short-lived receiver.
|
||||
*/
|
||||
class NotificationActionReceiver : BroadcastReceiver() {
|
||||
companion object {
|
||||
const val ARCHIVE = "pl.mtps.tern.action.ARCHIVE"
|
||||
const val READ = "pl.mtps.tern.action.READ"
|
||||
}
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val threadId = intent.getStringExtra(Notifier.EXTRA_THREAD) ?: return
|
||||
val action = when (intent.action) {
|
||||
ARCHIVE -> ActionWorker.ARCHIVE
|
||||
READ -> ActionWorker.READ
|
||||
else -> return
|
||||
}
|
||||
context.tern.notifier.cancel(threadId)
|
||||
ActionWorker.enqueue(context, threadId, action)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package pl.mtps.tern.notify
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.text.Html
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.app.Person
|
||||
import androidx.core.content.ContextCompat
|
||||
import kotlinx.coroutines.flow.first
|
||||
import pl.mtps.tern.MainActivity
|
||||
import pl.mtps.tern.R
|
||||
import pl.mtps.tern.data.Message
|
||||
import pl.mtps.tern.data.NewMail
|
||||
import pl.mtps.tern.tern
|
||||
|
||||
/**
|
||||
* New-mail notifications (android-client-spec.md §5): one conversation-style
|
||||
* notification per thread, so a busy thread updates in place instead of
|
||||
* flooding the shade, with Archive and Mark read acting on the server.
|
||||
*/
|
||||
class Notifier(private val context: Context) {
|
||||
private val manager = NotificationManagerCompat.from(context)
|
||||
|
||||
companion object {
|
||||
const val CHANNEL_MAIL = "mail"
|
||||
private const val CHANNEL_SYNC = "sync"
|
||||
private const val CHANNEL_ACCOUNT = "account"
|
||||
private const val GROUP = "pl.mtps.tern.MAIL"
|
||||
/** Per-thread notifications use the thread id as their tag and this id. */
|
||||
private const val THREAD_ID = 1
|
||||
private const val SUMMARY_ID = 2
|
||||
private const val SIGNED_OUT_ID = 3
|
||||
const val EXTRA_THREAD = "pl.mtps.tern.THREAD"
|
||||
}
|
||||
|
||||
fun createChannels() {
|
||||
val nm = context.getSystemService(NotificationManager::class.java)
|
||||
nm.createNotificationChannels(
|
||||
listOf(
|
||||
NotificationChannel(CHANNEL_MAIL, context.getString(R.string.channel_mail), NotificationManager.IMPORTANCE_HIGH),
|
||||
NotificationChannel(CHANNEL_SYNC, context.getString(R.string.channel_sync), NotificationManager.IMPORTANCE_MIN),
|
||||
NotificationChannel(CHANNEL_ACCOUNT, context.getString(R.string.channel_account), NotificationManager.IMPORTANCE_DEFAULT),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun allowed(): Boolean =
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED &&
|
||||
manager.areNotificationsEnabled()
|
||||
|
||||
private fun openThread(threadId: String?): PendingIntent {
|
||||
val intent = Intent(context, MainActivity::class.java)
|
||||
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.apply { threadId?.let { putExtra(EXTRA_THREAD, it) } }
|
||||
return PendingIntent.getActivity(
|
||||
context, threadId.hashCode(), intent,
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
}
|
||||
|
||||
private fun action(threadId: String, action: String): PendingIntent =
|
||||
PendingIntent.getBroadcast(
|
||||
context, (threadId + action).hashCode(),
|
||||
Intent(context, NotificationActionReceiver::class.java)
|
||||
.setAction(action)
|
||||
.putExtra(EXTRA_THREAD, threadId),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
/** Raises or updates one notification per thread with new notifying mail. */
|
||||
@SuppressLint("MissingPermission") // checked in allowed()
|
||||
suspend fun show(newMail: List<NewMail>) {
|
||||
if (newMail.isEmpty() || !allowed()) return
|
||||
val repo = context.tern.repository
|
||||
val me = Person.Builder().setName(context.getString(R.string.you)).build()
|
||||
|
||||
for ((threadId, mails) in newMail.groupBy { it.threadId }) {
|
||||
// Fetch the conversation for text to show; it's cached for when
|
||||
// the notification is tapped, too.
|
||||
val messages = runCatching { repo.refreshThread(threadId) }.getOrElse { emptyList() }
|
||||
val byId = messages.associateBy { it.id }
|
||||
|
||||
val existing = manager.activeNotifications.firstOrNull { it.tag == threadId && it.id == THREAD_ID }
|
||||
val style = existing?.notification
|
||||
?.let { NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(it) }
|
||||
?: NotificationCompat.MessagingStyle(me)
|
||||
for (mail in mails) {
|
||||
val m = byId[mail.messageId]
|
||||
val sender = Person.Builder().setName(m?.sender ?: mail.from).setKey(m?.fromAddr ?: mail.from).build()
|
||||
style.addMessage(snippet(m) ?: mail.subject, sentAtMillis(m), sender)
|
||||
}
|
||||
val subject = mails.last().subject
|
||||
style.conversationTitle = subject
|
||||
style.isGroupConversation = style.messages.map { it.person?.key }.distinct().size > 1
|
||||
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_MAIL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setStyle(style)
|
||||
.setContentTitle(mails.last().from)
|
||||
.setContentText(subject)
|
||||
.setCategory(NotificationCompat.CATEGORY_EMAIL)
|
||||
.setGroup(GROUP)
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(openThread(threadId))
|
||||
.addAction(0, context.getString(R.string.action_archive), action(threadId, NotificationActionReceiver.ARCHIVE))
|
||||
.addAction(0, context.getString(R.string.action_mark_read), action(threadId, NotificationActionReceiver.READ))
|
||||
.setOnlyAlertOnce(false)
|
||||
.build()
|
||||
manager.notify(threadId, THREAD_ID, notification)
|
||||
}
|
||||
updateSummary()
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops notifications for conversations that no longer need attention —
|
||||
* read, archived or deleted elsewhere (the web app, another phone).
|
||||
*/
|
||||
suspend fun reconcile(touched: Set<String>, everything: Boolean) {
|
||||
val repo = context.tern.repository
|
||||
for (n in manager.activeNotifications.filter { it.id == THREAD_ID }) {
|
||||
val threadId = n.tag ?: continue
|
||||
if (!everything && threadId !in touched) continue
|
||||
val messages = runCatching { repo.refreshThread(threadId) }.getOrNull()
|
||||
?: repo.messages(threadId).first()
|
||||
if (messages.none { it.unread && it.deletedAt == null }) manager.cancel(threadId, THREAD_ID)
|
||||
}
|
||||
updateSummary()
|
||||
}
|
||||
|
||||
fun cancel(threadId: String) {
|
||||
manager.cancel(threadId, THREAD_ID)
|
||||
updateSummary()
|
||||
}
|
||||
|
||||
fun cancelAll() = manager.cancelAll()
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun updateSummary() {
|
||||
val threads = manager.activeNotifications.filter { it.id == THREAD_ID && it.tag != null }
|
||||
if (threads.size < 2 || !allowed()) {
|
||||
manager.cancel(SUMMARY_ID)
|
||||
return
|
||||
}
|
||||
val inbox = NotificationCompat.InboxStyle()
|
||||
threads.forEach { sbn ->
|
||||
val extras = sbn.notification.extras
|
||||
inbox.addLine("${extras.getCharSequence(Notification.EXTRA_TITLE)}: ${extras.getCharSequence(Notification.EXTRA_TEXT)}")
|
||||
}
|
||||
val text = context.resources.getQuantityString(R.plurals.new_conversations, threads.size, threads.size)
|
||||
manager.notify(
|
||||
SUMMARY_ID,
|
||||
NotificationCompat.Builder(context, CHANNEL_MAIL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(text)
|
||||
.setStyle(inbox.setSummaryText(text))
|
||||
.setGroup(GROUP)
|
||||
.setGroupSummary(true)
|
||||
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN)
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(openThread(null))
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
fun showSignedOut() {
|
||||
if (!allowed()) return
|
||||
manager.notify(
|
||||
SIGNED_OUT_ID,
|
||||
NotificationCompat.Builder(context, CHANNEL_ACCOUNT)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.signed_out_title))
|
||||
.setContentText(context.getString(R.string.signed_out_text))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(openThread(null))
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
fun syncingNotification(): Notification =
|
||||
NotificationCompat.Builder(context, CHANNEL_SYNC)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.syncing))
|
||||
.setPriority(NotificationCompat.PRIORITY_MIN)
|
||||
.build()
|
||||
|
||||
private fun snippet(m: Message?): String? {
|
||||
val body = m?.body ?: return null
|
||||
val text = body.textBody?.takeIf { it.isNotBlank() }
|
||||
?: body.htmlBody?.let { Html.fromHtml(it, Html.FROM_HTML_MODE_COMPACT).toString() }
|
||||
?: return null
|
||||
val lines = text.lineSequence()
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() && !it.startsWith(">") }
|
||||
.joinToString(" ")
|
||||
return lines.take(300).ifBlank { null }
|
||||
}
|
||||
|
||||
private fun sentAtMillis(m: Message?): Long =
|
||||
m?.sentAt?.let { runCatching { java.time.OffsetDateTime.parse(it).toInstant().toEpochMilli() }.getOrNull() }
|
||||
?: System.currentTimeMillis()
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package pl.mtps.tern.push
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import org.unifiedpush.android.connector.UnifiedPush
|
||||
import pl.mtps.tern.sync.DeviceWorker
|
||||
import pl.mtps.tern.tern
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
|
||||
/** Push registration state for the settings screen, as last reported by the distributor. */
|
||||
object PushState {
|
||||
sealed interface Status {
|
||||
data object Off : Status
|
||||
data object Registering : Status
|
||||
data object Registered : Status
|
||||
data object NoDistributor : Status
|
||||
data class Failed(val reason: String) : Status
|
||||
}
|
||||
|
||||
private val state = MutableStateFlow<Status>(Status.Off)
|
||||
val status: StateFlow<Status> = state
|
||||
fun set(s: Status) { state.value = s }
|
||||
}
|
||||
|
||||
/**
|
||||
* Turning UnifiedPush on and off. Tern never talks to a push server itself:
|
||||
* the distributor app (e.g. ntfy) holds the connection, and hands Tern an
|
||||
* endpoint that the Tern server pushes to.
|
||||
*/
|
||||
object Push {
|
||||
/** Distributor apps installed on this phone (package names). */
|
||||
fun distributors(context: Context): List<String> = UnifiedPush.getDistributors(context)
|
||||
|
||||
fun savedDistributor(context: Context): String? = UnifiedPush.getSavedDistributor(context)
|
||||
|
||||
/**
|
||||
* Registers with a distributor: the one given, else the saved or the
|
||||
* system default one (which may ask the user to pick). The server's
|
||||
* VAPID key goes along for distributors that require it.
|
||||
*/
|
||||
suspend fun enable(activity: Activity, distributor: String? = null) {
|
||||
val app = activity.tern
|
||||
if (distributors(activity).isEmpty()) {
|
||||
PushState.set(PushState.Status.NoDistributor)
|
||||
return
|
||||
}
|
||||
PushState.set(PushState.Status.Registering)
|
||||
val vapid = runCatching { app.repository.api().pushInfo().vapidPublicKey }.getOrNull()
|
||||
val ok = if (distributor != null) {
|
||||
UnifiedPush.saveDistributor(activity, distributor)
|
||||
true
|
||||
} else {
|
||||
suspendCoroutine { cont -> UnifiedPush.tryUseCurrentOrDefaultDistributor(activity) { cont.resume(it) } }
|
||||
}
|
||||
if (!ok) {
|
||||
PushState.set(PushState.Status.Failed("no distributor chosen"))
|
||||
return
|
||||
}
|
||||
app.settings.setPushWanted(true)
|
||||
UnifiedPush.register(activity, vapid = vapid)
|
||||
}
|
||||
|
||||
suspend fun disable(context: Context) {
|
||||
context.tern.settings.setPushWanted(false)
|
||||
UnifiedPush.unregister(context)
|
||||
DeviceWorker.unregister(context)
|
||||
PushState.set(PushState.Status.Off)
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-registers on app start while push is wanted: distributors ask apps
|
||||
* to, and it heals a registration lost to a distributor reinstall.
|
||||
*/
|
||||
suspend fun refresh(context: Context) {
|
||||
val app = context.tern
|
||||
if (savedDistributor(context) == null) return
|
||||
val vapid = runCatching { app.repository.api().pushInfo().vapidPublicKey }.getOrNull()
|
||||
UnifiedPush.register(context, vapid = vapid)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package pl.mtps.tern.push
|
||||
|
||||
import org.unifiedpush.android.connector.FailedReason
|
||||
import org.unifiedpush.android.connector.PushService
|
||||
import org.unifiedpush.android.connector.data.PushEndpoint
|
||||
import org.unifiedpush.android.connector.data.PushMessage
|
||||
import pl.mtps.tern.sync.DeviceWorker
|
||||
import pl.mtps.tern.sync.SyncWorker
|
||||
|
||||
/**
|
||||
* Receives UnifiedPush events from the distributor (android-client-spec.md
|
||||
* §5). Everything here only schedules work: messages are content-free
|
||||
* wake-ups, so the real work is a pull-sync over the authenticated API.
|
||||
*/
|
||||
class TernPushService : PushService() {
|
||||
override fun onNewEndpoint(endpoint: PushEndpoint, instance: String) {
|
||||
PushState.set(PushState.Status.Registered)
|
||||
DeviceWorker.register(this, endpoint.url, endpoint.pubKeySet?.pubKey, endpoint.pubKeySet?.auth)
|
||||
}
|
||||
|
||||
override fun onMessage(message: PushMessage, instance: String) {
|
||||
SyncWorker.enqueue(this)
|
||||
}
|
||||
|
||||
override fun onRegistrationFailed(reason: FailedReason, instance: String) {
|
||||
PushState.set(PushState.Status.Failed(reason.name))
|
||||
}
|
||||
|
||||
override fun onUnregistered(instance: String) {
|
||||
PushState.set(PushState.Status.Off)
|
||||
DeviceWorker.unregister(this)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package pl.mtps.tern.sync
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import androidx.work.BackoffPolicy
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.ForegroundInfo
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.OutOfQuotaPolicy
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkerParameters
|
||||
import androidx.work.workDataOf
|
||||
import pl.mtps.tern.data.Actions
|
||||
import pl.mtps.tern.data.ApiException
|
||||
import pl.mtps.tern.data.DeviceRequest
|
||||
import pl.mtps.tern.data.NotSignedIn
|
||||
import pl.mtps.tern.tern
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
// Background work runs through WorkManager (android-client-spec.md §9),
|
||||
// which fits Doze and App Standby instead of fighting them.
|
||||
|
||||
private val online = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
|
||||
|
||||
/** Maps a failure to WorkManager's retry-or-give-up. */
|
||||
private suspend fun CoroutineWorker.outcome(context: Context, block: suspend () -> Unit): androidx.work.ListenableWorker.Result =
|
||||
try {
|
||||
block()
|
||||
androidx.work.ListenableWorker.Result.success()
|
||||
} catch (e: NotSignedIn) {
|
||||
androidx.work.ListenableWorker.Result.success()
|
||||
} catch (e: ApiException) {
|
||||
if (e.unauthorized) {
|
||||
context.tern.notifier.showSignedOut()
|
||||
androidx.work.ListenableWorker.Result.success()
|
||||
} else if (e.status >= 500) androidx.work.ListenableWorker.Result.retry()
|
||||
else androidx.work.ListenableWorker.Result.failure()
|
||||
} catch (e: IOException) {
|
||||
androidx.work.ListenableWorker.Result.retry()
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls changes from the server and raises notifications for mail that
|
||||
* should notify. Triggered by a UnifiedPush message — the push carries no
|
||||
* content, only "sync now" (§5).
|
||||
*/
|
||||
class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
|
||||
override suspend fun doWork() = outcome(applicationContext) {
|
||||
val app = applicationContext.tern
|
||||
val result = app.repository.sync()
|
||||
app.notifier.show(result.newMail)
|
||||
app.notifier.reconcile(result.touchedThreads, result.reset)
|
||||
}
|
||||
|
||||
// Expedited work needs this below Android 12; it's never shown on 12+.
|
||||
override suspend fun getForegroundInfo(): ForegroundInfo {
|
||||
val n = applicationContext.tern.notifier.syncingNotification()
|
||||
return if (Build.VERSION.SDK_INT >= 29) {
|
||||
ForegroundInfo(SYNC_NOTIFICATION_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||
} else ForegroundInfo(SYNC_NOTIFICATION_ID, n)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val SYNC_NOTIFICATION_ID = 0x7e51
|
||||
|
||||
fun enqueue(context: Context) {
|
||||
val request = OneTimeWorkRequestBuilder<SyncWorker>()
|
||||
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
|
||||
.setConstraints(online)
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
// A push while a sync is running queues exactly one more after it.
|
||||
WorkManager.getInstance(context).enqueueUniqueWork("sync", ExistingWorkPolicy.APPEND_OR_REPLACE, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Archive / mark read from the notification shade (§5), retried until the server has it. */
|
||||
class ActionWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
|
||||
override suspend fun doWork() = outcome(applicationContext) {
|
||||
val thread = inputData.getString(KEY_THREAD) ?: return@outcome
|
||||
val repo = applicationContext.tern.repository
|
||||
when (inputData.getString(KEY_ACTION)) {
|
||||
ARCHIVE -> repo.api().act(thread, listOf(Actions.archive))
|
||||
READ -> repo.api().markRead(thread)
|
||||
}
|
||||
runCatching { repo.sync() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ARCHIVE = "archive"
|
||||
const val READ = "read"
|
||||
private const val KEY_THREAD = "thread"
|
||||
private const val KEY_ACTION = "action"
|
||||
|
||||
fun enqueue(context: Context, threadId: String, action: String) {
|
||||
val request = OneTimeWorkRequestBuilder<ActionWorker>()
|
||||
.setInputData(workDataOf(KEY_THREAD to threadId, KEY_ACTION to action))
|
||||
.setConstraints(online)
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
WorkManager.getInstance(context).enqueue(request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the server where to push (or to stop). Endpoints come from the
|
||||
* UnifiedPush distributor and can change at any time, so this runs from the
|
||||
* push service's callbacks as well as from settings.
|
||||
*/
|
||||
class DeviceWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
|
||||
override suspend fun doWork() = outcome(applicationContext) {
|
||||
val app = applicationContext.tern
|
||||
val api = app.repository.api()
|
||||
val previous = app.settings.device()
|
||||
val endpoint = inputData.getString(KEY_ENDPOINT)
|
||||
if (endpoint == null) {
|
||||
previous?.let { (id, _) -> runCatching { api.deleteDevice(id) } }
|
||||
app.settings.setDevice(null, null)
|
||||
return@outcome
|
||||
}
|
||||
val device = api.registerDevice(
|
||||
DeviceRequest(endpoint, inputData.getString(KEY_P256DH), inputData.getString(KEY_AUTH), Build.MODEL),
|
||||
)
|
||||
// A rotated endpoint is a new registration; drop the old one.
|
||||
previous?.let { (id, _) -> if (id != device.id) runCatching { api.deleteDevice(id) } }
|
||||
app.settings.setDevice(device.id, endpoint)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val KEY_ENDPOINT = "endpoint"
|
||||
private const val KEY_P256DH = "p256dh"
|
||||
private const val KEY_AUTH = "auth"
|
||||
|
||||
fun register(context: Context, endpoint: String, p256dh: String?, auth: String?) =
|
||||
enqueue(context, workDataOf(KEY_ENDPOINT to endpoint, KEY_P256DH to p256dh, KEY_AUTH to auth))
|
||||
|
||||
fun unregister(context: Context) = enqueue(context, workDataOf())
|
||||
|
||||
private fun enqueue(context: Context, data: androidx.work.Data) {
|
||||
val request = OneTimeWorkRequestBuilder<DeviceWorker>()
|
||||
.setInputData(data)
|
||||
.setConstraints(online)
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
// The latest registration wins over any still pending.
|
||||
WorkManager.getInstance(context).enqueueUniqueWork("device", ExistingWorkPolicy.REPLACE, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExposedDropdownMenuAnchorType
|
||||
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import pl.mtps.tern.R
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ComposeScreen(vm: MailViewModel, seed: ComposeSeed, onDone: () -> Unit) {
|
||||
val accounts by vm.accounts.collectAsStateWithLifecycle()
|
||||
var to by rememberSaveable { mutableStateOf(seed.to.joinToString(", ")) }
|
||||
var cc by rememberSaveable { mutableStateOf(seed.cc.joinToString(", ")) }
|
||||
var bcc by rememberSaveable { mutableStateOf(seed.bcc.joinToString(", ")) }
|
||||
var showCc by rememberSaveable { mutableStateOf(seed.cc.isNotEmpty() || seed.bcc.isNotEmpty()) }
|
||||
var subject by rememberSaveable { mutableStateOf(seed.subject) }
|
||||
var body by rememberSaveable { mutableStateOf(seed.body) }
|
||||
var accountId by rememberSaveable { mutableStateOf(seed.accountId ?: accounts.firstOrNull()?.id) }
|
||||
var accountMenu by remember { mutableStateOf(false) }
|
||||
var confirmDiscard by remember { mutableStateOf(false) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
|
||||
val changed = to != seed.to.joinToString(", ") || cc != seed.cc.joinToString(", ") ||
|
||||
subject != seed.subject || body != seed.body
|
||||
val isReply = seed.replyToMessageId != null
|
||||
|
||||
fun submit(send: Boolean) {
|
||||
busy = true
|
||||
vm.send(
|
||||
seed, parseRecipients(to), parseRecipients(cc), parseRecipients(bcc), subject, body,
|
||||
// A reply goes out from the account that received the original,
|
||||
// decided server-side, unless the reader picked one.
|
||||
accountId = if (isReply && accountId == seed.accountId) null else accountId,
|
||||
send = send,
|
||||
done = onDone,
|
||||
)
|
||||
busy = false
|
||||
}
|
||||
|
||||
fun close() = if (changed) confirmDiscard = true else onDone()
|
||||
BackHandler { close() }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(if (isReply) R.string.reply else R.string.compose)) },
|
||||
navigationIcon = { IconButton(onClick = ::close) { Icon(Icons.Filled.Close, stringResource(R.string.close)) } },
|
||||
actions = {
|
||||
IconButton(onClick = { submit(send = true) }, enabled = !busy && parseRecipients(to + "," + cc + "," + bcc).isNotEmpty()) {
|
||||
Icon(Icons.AutoMirrored.Filled.Send, stringResource(R.string.send))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.padding(padding).imePadding().fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
|
||||
) {
|
||||
if (accounts.size > 1 && !isReply) {
|
||||
ExposedDropdownMenuBox(accountMenu, { accountMenu = it }) {
|
||||
OutlinedTextField(
|
||||
accounts.find { it.id == accountId }?.let { it.emailAddress ?: it.username } ?: "",
|
||||
{}, readOnly = true, label = { Text(stringResource(R.string.from)) },
|
||||
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable),
|
||||
)
|
||||
ExposedDropdownMenu(accountMenu, { accountMenu = false }) {
|
||||
accounts.forEach { a ->
|
||||
DropdownMenuItem({ Text(a.emailAddress ?: a.username) }, { accountId = a.id; accountMenu = false })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
OutlinedTextField(
|
||||
to, { to = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.to)) },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
|
||||
trailingIcon = { if (!showCc) TextButton({ showCc = true }) { Text(stringResource(R.string.cc_bcc)) } },
|
||||
)
|
||||
if (showCc) {
|
||||
OutlinedTextField(cc, { cc = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.cc)) },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email))
|
||||
OutlinedTextField(bcc, { bcc = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.bcc)) },
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email))
|
||||
}
|
||||
OutlinedTextField(subject, { subject = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.subject)) })
|
||||
OutlinedTextField(
|
||||
body, { body = it }, Modifier.fillMaxWidth().heightIn(min = 240.dp).padding(vertical = 8.dp),
|
||||
label = { Text(stringResource(R.string.message)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (confirmDiscard) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmDiscard = false },
|
||||
title = { Text(stringResource(R.string.save_draft_q)) },
|
||||
confirmButton = { TextButton({ confirmDiscard = false; submit(send = false) }) { Text(stringResource(R.string.save_draft)) } },
|
||||
dismissButton = { TextButton({ confirmDiscard = false; onDone() }) { Text(stringResource(R.string.discard)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.time.format.FormatStyle
|
||||
|
||||
private fun parse(iso: String?) =
|
||||
iso?.let { runCatching { OffsetDateTime.parse(it).atZoneSameInstant(ZoneId.systemDefault()) }.getOrNull() }
|
||||
|
||||
/** List dates: time today, day and month this year, full date otherwise. */
|
||||
fun formatShort(iso: String?): String {
|
||||
val t = parse(iso) ?: return ""
|
||||
val today = LocalDate.now()
|
||||
return when {
|
||||
t.toLocalDate() == today -> t.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))
|
||||
t.year == today.year -> t.format(DateTimeFormatter.ofPattern("d MMM"))
|
||||
else -> t.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))
|
||||
}
|
||||
}
|
||||
|
||||
fun formatFull(iso: String?): String =
|
||||
parse(iso)?.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT)) ?: "an unknown date"
|
||||
@@ -0,0 +1,85 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import pl.mtps.tern.R
|
||||
|
||||
private val REMOTE_CONTENT = Regex("""(src|background)\s*=\s*["']?\s*(https?:)?//""", RegexOption.IGNORE_CASE)
|
||||
|
||||
/**
|
||||
* Untrusted HTML mail, shown locked down (server spec §5): no JavaScript,
|
||||
* no file or content access, and no network — so remote images and
|
||||
* tracking pixels stay blocked until the reader allows them for this
|
||||
* message. Links open in the browser rather than inside the app.
|
||||
*/
|
||||
@Composable
|
||||
fun HtmlBody(messageId: String, html: String, modifier: Modifier = Modifier) {
|
||||
var imagesAllowed by rememberSaveable(messageId) { mutableStateOf(false) }
|
||||
val hasRemote = REMOTE_CONTENT.containsMatchIn(html)
|
||||
|
||||
Column(modifier.fillMaxWidth()) {
|
||||
if (hasRemote && !imagesAllowed) {
|
||||
TextButton(onClick = { imagesAllowed = true }) { Text(stringResource(R.string.show_images)) }
|
||||
}
|
||||
// Mail HTML assumes a light page, so it gets one even in dark mode.
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(Color.White).padding(4.dp),
|
||||
factory = { context ->
|
||||
WebView(context).apply {
|
||||
settings.javaScriptEnabled = false
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
settings.setGeolocationEnabled(false)
|
||||
settings.blockNetworkLoads = true
|
||||
settings.loadsImagesAutomatically = true
|
||||
setBackgroundColor(android.graphics.Color.WHITE)
|
||||
isVerticalScrollBarEnabled = false
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
|
||||
runCatching {
|
||||
view.context.startActivity(Intent(Intent.ACTION_VIEW, request.url).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
update = { web ->
|
||||
val key = "$messageId:$imagesAllowed"
|
||||
if (web.tag != key) {
|
||||
web.tag = key
|
||||
web.settings.blockNetworkLoads = !imagesAllowed
|
||||
web.loadDataWithBaseURL(null, html, "text/html", "utf-8", null)
|
||||
}
|
||||
},
|
||||
)
|
||||
if (!hasRemote) return@Column
|
||||
Text(
|
||||
stringResource(if (imagesAllowed) R.string.images_shown else R.string.images_blocked),
|
||||
Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.Label
|
||||
import androidx.compose.material.icons.automirrored.outlined.Send
|
||||
import androidx.compose.material.icons.outlined.AllInbox
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Folder
|
||||
import androidx.compose.material.icons.outlined.Inbox
|
||||
import androidx.compose.material.icons.outlined.Outbox
|
||||
import androidx.compose.material.icons.outlined.Report
|
||||
import androidx.compose.material.icons.outlined.Settings
|
||||
import androidx.compose.material3.Badge
|
||||
import androidx.compose.material3.DrawerState
|
||||
import androidx.compose.material3.DrawerValue
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalDrawerSheet
|
||||
import androidx.compose.material3.ModalNavigationDrawer
|
||||
import androidx.compose.material3.NavigationDrawerItem
|
||||
import androidx.compose.material3.NavigationDrawerItemDefaults
|
||||
import androidx.compose.material3.PermanentDrawerSheet
|
||||
import androidx.compose.material3.PermanentNavigationDrawer
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.adaptive.ExperimentalMaterial3AdaptiveApi
|
||||
import androidx.compose.material3.adaptive.currentWindowAdaptiveInfo
|
||||
import androidx.compose.material3.adaptive.layout.AnimatedPane
|
||||
import androidx.compose.material3.adaptive.layout.ListDetailPaneScaffoldRole
|
||||
import androidx.compose.material3.adaptive.layout.PaneAdaptedValue
|
||||
import androidx.compose.material3.adaptive.navigation.NavigableListDetailPaneScaffold
|
||||
import androidx.compose.material3.adaptive.navigation.rememberListDetailPaneScaffoldNavigator
|
||||
import androidx.compose.material3.rememberDrawerState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.window.core.layout.WindowSizeClass
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.mtps.tern.R
|
||||
import pl.mtps.tern.data.Folder
|
||||
import pl.mtps.tern.data.MailView
|
||||
import pl.mtps.tern.data.Tag
|
||||
|
||||
/** How often the open app checks for changes, on top of push (§9). */
|
||||
private const val FOREGROUND_SYNC_MS = 30_000L
|
||||
|
||||
/**
|
||||
* List–detail from the start (android-client-spec.md §4): one pane on
|
||||
* phones, list and conversation side by side on tablets and unfolded
|
||||
* foldables. The drawer is modal on narrow screens, permanent on wide ones.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3AdaptiveApi::class, ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun MailScreen(
|
||||
vm: MailViewModel,
|
||||
openThread: String?,
|
||||
onOpenThreadHandled: () -> Unit,
|
||||
onCompose: (ComposeSeed) -> Unit,
|
||||
onOutbox: () -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
) {
|
||||
val navigator = rememberListDetailPaneScaffoldNavigator<String>()
|
||||
val scope = rememberCoroutineScope()
|
||||
val drawerState = rememberDrawerState(DrawerValue.Closed)
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
val message by vm.message.collectAsStateWithLifecycle()
|
||||
val wide = currentWindowAdaptiveInfo().windowSizeClass
|
||||
.isWidthAtLeastBreakpoint(WindowSizeClass.WIDTH_DP_EXPANDED_LOWER_BOUND)
|
||||
|
||||
fun openThreadPane(id: String) {
|
||||
vm.open(id)
|
||||
scope.launch { navigator.navigateTo(ListDetailPaneScaffoldRole.Detail, id) }
|
||||
}
|
||||
|
||||
// A tapped notification opens its conversation.
|
||||
LaunchedEffect(openThread) {
|
||||
openThread?.let {
|
||||
// The conversation pane doesn't depend on the list's view, so the
|
||||
// reader's view stays as it was.
|
||||
openThreadPane(it)
|
||||
onOpenThreadHandled()
|
||||
}
|
||||
}
|
||||
|
||||
// Live-ish while open: a delta sync now and every 30 s, stopping in the
|
||||
// background — push covers that.
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
LaunchedEffect(lifecycle) {
|
||||
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
while (true) {
|
||||
vm.sync()
|
||||
delay(FOREGROUND_SYNC_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(message) {
|
||||
message?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
vm.messageShown()
|
||||
}
|
||||
}
|
||||
|
||||
val content = @Composable {
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
NavigableListDetailPaneScaffold(
|
||||
navigator = navigator,
|
||||
listPane = {
|
||||
AnimatedPane {
|
||||
ThreadListPane(
|
||||
vm = vm,
|
||||
selectedId = navigator.currentDestination?.contentKey,
|
||||
showMenu = !wide,
|
||||
onMenu = { scope.launch { drawerState.open() } },
|
||||
onOpen = ::openThreadPane,
|
||||
onCompose = { onCompose(ComposeSeed(accountId = vm.accounts.value.firstOrNull()?.id)) },
|
||||
)
|
||||
}
|
||||
},
|
||||
detailPane = {
|
||||
AnimatedPane {
|
||||
val id = navigator.currentDestination?.contentKey
|
||||
if (id == null) {
|
||||
EmptyDetail()
|
||||
} else {
|
||||
ThreadPane(
|
||||
vm = vm,
|
||||
threadId = id,
|
||||
showBack = navigator.scaffoldValue[ListDetailPaneScaffoldRole.List] == PaneAdaptedValue.Hidden,
|
||||
onBack = { scope.launch { navigator.navigateBack() } },
|
||||
onCompose = onCompose,
|
||||
onLeft = {
|
||||
// The conversation left this view: back to the list.
|
||||
scope.launch { navigator.navigateBack() }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
SnackbarHost(snackbar, Modifier.align(Alignment.BottomCenter).padding(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
val drawer = @Composable { permanent: Boolean ->
|
||||
Drawer(vm, permanent, drawerState, onOutbox = onOutbox, onSettings = onSettings, onPicked = {
|
||||
scope.launch {
|
||||
drawerState.close()
|
||||
// A different view: close any open conversation first.
|
||||
while (navigator.canNavigateBack()) navigator.navigateBack()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (wide) {
|
||||
PermanentNavigationDrawer(drawerContent = { drawer(true) }, content = content)
|
||||
} else {
|
||||
ModalNavigationDrawer(drawerContent = { drawer(false) }, drawerState = drawerState, content = content)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmptyDetail() {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.select_conversation), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Drawer(
|
||||
vm: MailViewModel,
|
||||
permanent: Boolean,
|
||||
drawerState: DrawerState,
|
||||
onOutbox: () -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
onPicked: () -> Unit,
|
||||
) {
|
||||
val view by vm.view.collectAsStateWithLifecycle()
|
||||
val folders by vm.folders.collectAsStateWithLifecycle()
|
||||
val tags by vm.tags.collectAsStateWithLifecycle()
|
||||
val outbox by vm.outbox.collectAsStateWithLifecycle()
|
||||
|
||||
val items = @Composable {
|
||||
Text(
|
||||
stringResource(R.string.app_name),
|
||||
Modifier.padding(horizontal = 28.dp, vertical = 20.dp),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
@Composable
|
||||
fun item(label: String, icon: ImageVector, v: MailView, badge: Int = 0, dot: Color? = null) =
|
||||
NavigationDrawerItem(
|
||||
label = { Text(label) },
|
||||
icon = {
|
||||
if (dot != null) Box(Modifier.size(12.dp).background(dot, CircleShape))
|
||||
else Icon(icon, contentDescription = null)
|
||||
},
|
||||
badge = { if (badge > 0) Badge { Text("$badge") } },
|
||||
selected = view == v,
|
||||
onClick = { vm.selectView(v); onPicked() },
|
||||
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding),
|
||||
)
|
||||
|
||||
item(stringResource(R.string.view_inbox), Icons.Outlined.Inbox, MailView.Inbox)
|
||||
item(stringResource(R.string.view_all), Icons.Outlined.AllInbox, MailView.All)
|
||||
item(stringResource(R.string.view_sent), Icons.AutoMirrored.Outlined.Send, MailView.Sent)
|
||||
NavigationDrawerItem(
|
||||
label = { Text(stringResource(R.string.outbox)) },
|
||||
icon = { Icon(Icons.Outlined.Outbox, contentDescription = null) },
|
||||
badge = { if (outbox.isNotEmpty()) Badge { Text("${outbox.size}") } },
|
||||
selected = false,
|
||||
onClick = { onPicked(); onOutbox() },
|
||||
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding),
|
||||
)
|
||||
item(stringResource(R.string.view_junk), Icons.Outlined.Report, MailView.Junk)
|
||||
item(stringResource(R.string.view_trash), Icons.Outlined.Delete, MailView.Trash)
|
||||
|
||||
val userFolders = folders.filter { it.role != "junk" }
|
||||
if (userFolders.isNotEmpty()) {
|
||||
HorizontalDivider(Modifier.padding(horizontal = 28.dp, vertical = 8.dp))
|
||||
SectionLabel(stringResource(R.string.folders))
|
||||
userFolders.forEach { f: Folder -> item(f.name, Icons.Outlined.Folder, MailView.InFolder(f.id)) }
|
||||
}
|
||||
if (tags.isNotEmpty()) {
|
||||
HorizontalDivider(Modifier.padding(horizontal = 28.dp, vertical = 8.dp))
|
||||
SectionLabel(stringResource(R.string.tags))
|
||||
tags.forEach { t: Tag -> item(t.name, Icons.AutoMirrored.Outlined.Label, MailView.Tagged(t.id), dot = tagColor(t)) }
|
||||
}
|
||||
HorizontalDivider(Modifier.padding(horizontal = 28.dp, vertical = 8.dp))
|
||||
NavigationDrawerItem(
|
||||
label = { Text(stringResource(R.string.settings)) },
|
||||
icon = { Icon(Icons.Outlined.Settings, contentDescription = null) },
|
||||
selected = false,
|
||||
onClick = { onPicked(); onSettings() },
|
||||
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding),
|
||||
)
|
||||
Spacer(Modifier.padding(bottom = 16.dp))
|
||||
}
|
||||
|
||||
// The sheet fills the height; its contents scroll inside it.
|
||||
val scrolling = @Composable { Column(Modifier.verticalScroll(rememberScrollState())) { items() } }
|
||||
if (permanent) {
|
||||
PermanentDrawerSheet { scrolling() }
|
||||
} else {
|
||||
ModalDrawerSheet(drawerState = drawerState) { scrolling() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionLabel(text: String) = Row(Modifier.padding(horizontal = 28.dp, vertical = 8.dp)) {
|
||||
Text(text, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
|
||||
/** Tag colours are stored as #rrggbb (the server enforces the format). */
|
||||
fun tagColor(t: Tag): Color? =
|
||||
t.color?.removePrefix("#")?.toLongOrNull(16)?.let { Color(0xFF000000 or it) }
|
||||
@@ -0,0 +1,215 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import android.app.Application
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import pl.mtps.tern.data.Account
|
||||
import pl.mtps.tern.data.ApiException
|
||||
import pl.mtps.tern.data.ComposeRequest
|
||||
import pl.mtps.tern.data.DraftUpdate
|
||||
import pl.mtps.tern.data.Folder
|
||||
import pl.mtps.tern.data.MailView
|
||||
import pl.mtps.tern.data.Message
|
||||
import pl.mtps.tern.data.NotSignedIn
|
||||
import pl.mtps.tern.data.OutboxItem
|
||||
import pl.mtps.tern.data.Tag
|
||||
import pl.mtps.tern.data.ThreadSummary
|
||||
import pl.mtps.tern.tern
|
||||
import java.io.IOException
|
||||
|
||||
/** Mail state for the signed-in UI; the cache is the source it renders from. */
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class MailViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val repo = app.tern.repository
|
||||
private val notifier = app.tern.notifier
|
||||
|
||||
private val _view = MutableStateFlow<MailView>(MailView.Inbox)
|
||||
val view: StateFlow<MailView> = _view.asStateFlow()
|
||||
|
||||
val threads: StateFlow<List<ThreadSummary>> =
|
||||
_view.flatMapLatest { repo.threads(it) }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
val folders: StateFlow<List<Folder>> = repo.folders.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
val tags: StateFlow<List<Tag>> = repo.tags.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
val accounts: StateFlow<List<Account>> = repo.accounts.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
val outbox: StateFlow<List<OutboxItem>> = repo.outbox.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
|
||||
|
||||
private val _refreshing = MutableStateFlow(false)
|
||||
val refreshing: StateFlow<Boolean> = _refreshing.asStateFlow()
|
||||
private val _nextCursor = MutableStateFlow<String?>(null)
|
||||
val hasMore: StateFlow<Boolean> get() = _hasMore
|
||||
private val _hasMore = MutableStateFlow(false)
|
||||
private var loadingMore = false
|
||||
|
||||
/** One-off messages for a snackbar. */
|
||||
private val _message = MutableStateFlow<String?>(null)
|
||||
val message: StateFlow<String?> = _message.asStateFlow()
|
||||
fun messageShown() { _message.value = null }
|
||||
|
||||
init {
|
||||
refresh()
|
||||
viewModelScope.launch { guard { repo.refreshMeta() } }
|
||||
viewModelScope.launch { guard { repo.refreshOutbox() } }
|
||||
}
|
||||
|
||||
private suspend fun guard(block: suspend () -> Unit) {
|
||||
try {
|
||||
block()
|
||||
} catch (e: NotSignedIn) {
|
||||
// The root screen switches to sign-in on its own.
|
||||
} catch (e: ApiException) {
|
||||
if (e.unauthorized) repo.signOut() else _message.value = e.message
|
||||
} catch (e: IOException) {
|
||||
_message.value = "Can't reach the server — showing what's saved on this phone."
|
||||
}
|
||||
}
|
||||
|
||||
fun selectView(v: MailView) {
|
||||
if (v == _view.value) return
|
||||
_view.value = v
|
||||
_nextCursor.value = null
|
||||
_hasMore.value = false
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
viewModelScope.launch {
|
||||
_refreshing.value = true
|
||||
guard {
|
||||
val next = repo.refresh(_view.value)
|
||||
_nextCursor.value = next
|
||||
_hasMore.value = next != null
|
||||
}
|
||||
_refreshing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Pulls in changes (delta sync) — on resume and periodically while open. */
|
||||
fun sync() {
|
||||
viewModelScope.launch {
|
||||
guard {
|
||||
val result = repo.sync()
|
||||
if (result.touchedThreads.isNotEmpty() || result.reset) {
|
||||
if (_view.value != MailView.Inbox) repo.refresh(_view.value)
|
||||
}
|
||||
notifier.reconcile(result.touchedThreads, result.reset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadMore() {
|
||||
val cursor = _nextCursor.value ?: return
|
||||
if (loadingMore) return
|
||||
loadingMore = true
|
||||
viewModelScope.launch {
|
||||
guard {
|
||||
val next = repo.loadMore(_view.value, cursor)
|
||||
_nextCursor.value = next
|
||||
_hasMore.value = next != null
|
||||
}
|
||||
loadingMore = false
|
||||
}
|
||||
}
|
||||
|
||||
fun messages(threadId: String) = repo.messages(threadId)
|
||||
|
||||
/** Opening a conversation reads it (and clears its notification). */
|
||||
fun open(threadId: String) {
|
||||
notifier.cancel(threadId)
|
||||
viewModelScope.launch {
|
||||
guard {
|
||||
val messages = repo.refreshThread(threadId)
|
||||
if (messages.any { it.unread && it.deletedAt == null }) {
|
||||
repo.markRead(threadId)
|
||||
repo.refresh(_view.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun act(threadId: String, actions: List<JsonObject>, leavesView: Boolean, confirmation: String? = null) {
|
||||
viewModelScope.launch {
|
||||
guard {
|
||||
repo.act(threadId, actions, _view.value, leavesView)
|
||||
confirmation?.let { _message.value = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- compose ------------------------------------------------------------
|
||||
|
||||
fun send(seed: ComposeSeed, to: List<String>, cc: List<String>, bcc: List<String>, subject: String, body: String, accountId: String?, send: Boolean, done: () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
guard {
|
||||
if (seed.draftId != null) {
|
||||
repo.saveDraft(seed.draftId, DraftUpdate(to, cc, bcc, subject, body), send)
|
||||
} else {
|
||||
repo.compose(ComposeRequest(accountId, to, cc, bcc, subject, body, seed.replyToMessageId, send))
|
||||
}
|
||||
_message.value = if (send) "Sending…" else "Draft saved"
|
||||
done()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteOutbox(id: String) = viewModelScope.launch { guard { repo.deleteOutbox(id) } }
|
||||
fun refreshOutbox() = viewModelScope.launch { guard { repo.refreshOutbox() } }
|
||||
}
|
||||
|
||||
/** What the compose screen opens with. */
|
||||
data class ComposeSeed(
|
||||
val to: List<String> = emptyList(),
|
||||
val cc: List<String> = emptyList(),
|
||||
val bcc: List<String> = emptyList(),
|
||||
val subject: String = "",
|
||||
val body: String = "",
|
||||
val replyToMessageId: String? = null,
|
||||
val accountId: String? = null,
|
||||
/** Reopening a draft or a failed message. */
|
||||
val draftId: String? = null,
|
||||
)
|
||||
|
||||
private val RE = Regex("^re:", RegexOption.IGNORE_CASE)
|
||||
|
||||
/** Same rules as the web app's reply.ts, so both clients reply alike. */
|
||||
fun replySeed(m: Message, ownAddresses: Collection<String>, all: Boolean): ComposeSeed {
|
||||
val own = ownAddresses.map { it.lowercase() }.toSet()
|
||||
fun notOwn(a: String) = a.lowercase() !in own
|
||||
fun dedupe(list: List<String>) = list.distinctBy { it.lowercase() }
|
||||
val fromSelf = m.source == "sent" || (m.fromAddr?.lowercase() in own)
|
||||
|
||||
var to: List<String>
|
||||
var cc: List<String> = emptyList()
|
||||
if (fromSelf) {
|
||||
to = m.toAddrs
|
||||
if (all) cc = m.ccAddrs
|
||||
} else {
|
||||
to = listOfNotNull(m.fromAddr)
|
||||
if (all) {
|
||||
to = to + m.toAddrs
|
||||
cc = m.ccAddrs
|
||||
}
|
||||
}
|
||||
to = dedupe(to.filter(::notOwn))
|
||||
cc = dedupe(cc.filter(::notOwn)).filter { a -> to.none { it.equals(a, ignoreCase = true) } }
|
||||
|
||||
val subject = (m.subject ?: "").trim().let { if (RE.containsMatchIn(it)) it else "Re: $it" }
|
||||
val quoted = m.body?.textBody?.trimEnd()?.takeIf { it.isNotEmpty() }?.let { text ->
|
||||
val who = m.fromName?.takeIf { it.isNotBlank() } ?: m.fromAddr ?: "someone"
|
||||
val lines = text.lines().joinToString("\n") { if (it.startsWith(">")) ">$it" else "> $it" }
|
||||
"\n\nOn ${formatFull(m.sentAt)}, $who wrote:\n$lines\n"
|
||||
} ?: ""
|
||||
return ComposeSeed(to = to, cc = cc, subject = subject, body = quoted, replyToMessageId = m.id)
|
||||
}
|
||||
|
||||
/** Splits a typed recipient field on commas, semicolons and whitespace. */
|
||||
fun parseRecipients(input: String): List<String> =
|
||||
input.split(Regex("[,;\\s]+")).map { it.trim() }.filter { it.isNotEmpty() }
|
||||
@@ -0,0 +1,195 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.mtps.tern.R
|
||||
import pl.mtps.tern.data.NewAccount
|
||||
import pl.mtps.tern.push.Push
|
||||
import pl.mtps.tern.tern
|
||||
|
||||
/**
|
||||
* First run after sign-in (§6): add a mail account if the server has none,
|
||||
* then offer notifications — the moment the permission request makes sense.
|
||||
*/
|
||||
@Composable
|
||||
fun OnboardingScreen() {
|
||||
val app = LocalContext.current.tern
|
||||
val scope = rememberCoroutineScope()
|
||||
var step by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
if (step == null) {
|
||||
step = runCatching { app.repository.refreshMeta(); app.repository.api().accounts() }
|
||||
.map { if (it.isEmpty()) "account" else "notifications" }
|
||||
.getOrDefault("account")
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier.fillMaxSize().safeDrawingPadding().imePadding().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Column(Modifier.widthIn(max = 520.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
when (step) {
|
||||
"account" -> AccountForm(onAdded = { step = "notifications" }, onSkip = { step = "notifications" })
|
||||
"notifications" -> NotificationsStep(onDone = { scope.launch { app.settings.setOnboarded() } })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AccountForm(onAdded: () -> Unit, onSkip: () -> Unit) {
|
||||
val app = LocalContext.current.tern
|
||||
val scope = rememberCoroutineScope()
|
||||
var email by rememberSaveable { mutableStateOf("") }
|
||||
var displayName by rememberSaveable { mutableStateOf("") }
|
||||
var imapHost by rememberSaveable { mutableStateOf("") }
|
||||
var imapPort by rememberSaveable { mutableStateOf("993") }
|
||||
var smtpHost by rememberSaveable { mutableStateOf("") }
|
||||
var smtpPort by rememberSaveable { mutableStateOf("587") }
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var password by rememberSaveable { mutableStateOf("") }
|
||||
var loginEdited by rememberSaveable { mutableStateOf(false) }
|
||||
var hostsEdited by rememberSaveable { mutableStateOf(false) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
Text(stringResource(R.string.add_account_title), style = MaterialTheme.typography.headlineSmall)
|
||||
Text(stringResource(R.string.add_account_intro), style = MaterialTheme.typography.bodyMedium)
|
||||
|
||||
@Composable
|
||||
fun field(label: Int, value: String, set: (String) -> Unit, type: KeyboardType = KeyboardType.Text, secret: Boolean = false) =
|
||||
OutlinedTextField(
|
||||
value, set, Modifier.fillMaxWidth(),
|
||||
label = { Text(stringResource(label)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = type),
|
||||
visualTransformation = if (secret) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None,
|
||||
)
|
||||
|
||||
field(R.string.email_address, email, {
|
||||
email = it
|
||||
// Login and hosts usually follow from the address, until edited.
|
||||
val domain = it.substringAfter('@', "")
|
||||
if (!loginEdited) username = it
|
||||
if (!hostsEdited) {
|
||||
imapHost = if (domain.isNotEmpty()) "mail.$domain" else ""
|
||||
smtpHost = imapHost
|
||||
}
|
||||
}, KeyboardType.Email)
|
||||
field(R.string.display_name, displayName, { displayName = it })
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Column(Modifier.weight(3f)) { field(R.string.imap_host, imapHost, { imapHost = it; hostsEdited = true }, KeyboardType.Uri) }
|
||||
Column(Modifier.weight(1f)) { field(R.string.port, imapPort, { imapPort = it }, KeyboardType.Number) }
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Column(Modifier.weight(3f)) { field(R.string.smtp_host, smtpHost, { smtpHost = it; hostsEdited = true }, KeyboardType.Uri) }
|
||||
Column(Modifier.weight(1f)) { field(R.string.port, smtpPort, { smtpPort = it }, KeyboardType.Number) }
|
||||
}
|
||||
field(R.string.login, username, { username = it; loginEdited = true })
|
||||
field(R.string.password, password, { password = it }, KeyboardType.Password, secret = true)
|
||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
Button(
|
||||
onClick = {
|
||||
busy = true
|
||||
error = null
|
||||
scope.launch {
|
||||
try {
|
||||
app.repository.addAccount(
|
||||
NewAccount(
|
||||
name = email.substringAfter('@').ifBlank { email },
|
||||
imapHost = imapHost.trim(), imapPort = imapPort.toIntOrNull() ?: 993,
|
||||
smtpHost = smtpHost.trim(), smtpPort = smtpPort.toIntOrNull() ?: 587,
|
||||
username = username.trim(), password = password,
|
||||
emailAddress = email.trim().ifBlank { null },
|
||||
displayName = displayName.trim().ifBlank { null },
|
||||
),
|
||||
)
|
||||
onAdded()
|
||||
} catch (e: Exception) {
|
||||
error = e.message
|
||||
} finally {
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = !busy && email.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank() && password.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text(stringResource(R.string.add_account)) }
|
||||
TextButton(onClick = onSkip, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.skip_account)) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NotificationsStep(onDone: () -> Unit) {
|
||||
val enable = rememberEnableNotifications(onResult = { onDone() })
|
||||
Text(stringResource(R.string.notifications_title), style = MaterialTheme.typography.headlineSmall)
|
||||
Text(stringResource(R.string.notifications_intro), style = MaterialTheme.typography.bodyMedium)
|
||||
Button(onClick = enable, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.turn_on_notifications)) }
|
||||
TextButton(onClick = onDone, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.not_now)) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an action that asks for the notification permission (Android 13+)
|
||||
* and then registers with the UnifiedPush distributor. Asked only when the
|
||||
* reader chooses to turn notifications on (§5), never on launch.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberEnableNotifications(onResult: (Boolean) -> Unit): () -> Unit {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
fun register() = scope.launch {
|
||||
Push.enable(context as Activity)
|
||||
onResult(true)
|
||||
}
|
||||
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) register() else onResult(false)
|
||||
}
|
||||
return {
|
||||
if (Build.VERSION.SDK_INT >= 33 &&
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
register()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import pl.mtps.tern.R
|
||||
|
||||
/** Drafts, queued and failed mail (server spec §3.3). */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun OutboxScreen(vm: MailViewModel, onBack: () -> Unit, onOpen: (ComposeSeed) -> Unit) {
|
||||
val items by vm.outbox.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(Unit) { vm.refreshOutbox() }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.outbox)) },
|
||||
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.back)) } },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
if (items.isEmpty()) {
|
||||
Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.outbox_empty), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.padding(padding).fillMaxSize()) {
|
||||
items(items, key = { it.id }) { item ->
|
||||
val editable = item.status == "draft" || item.status == "failed"
|
||||
Row(
|
||||
Modifier.fillMaxWidth()
|
||||
.clickable(enabled = editable) {
|
||||
onOpen(
|
||||
ComposeSeed(
|
||||
to = item.toAddrs, cc = item.ccAddrs, bcc = item.bccAddrs,
|
||||
subject = item.subject, body = item.textBody,
|
||||
accountId = item.accountId, draftId = item.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(item.subject.ifBlank { stringResource(R.string.no_subject) }, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
stringResource(R.string.to_line, (item.toAddrs + item.ccAddrs).joinToString(", ")),
|
||||
style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
item.lastError?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error, maxLines = 2) }
|
||||
}
|
||||
AssistChip(onClick = {}, label = { Text(statusLabel(item.status)) })
|
||||
if (editable) {
|
||||
IconButton(onClick = { vm.deleteOutbox(item.id) }) { Icon(Icons.Outlined.Delete, stringResource(R.string.delete)) }
|
||||
}
|
||||
}
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun statusLabel(status: String) = stringResource(
|
||||
when (status) {
|
||||
"draft" -> R.string.status_draft
|
||||
"pending" -> R.string.status_pending
|
||||
"sending" -> R.string.status_sending
|
||||
"sent" -> R.string.status_sent
|
||||
else -> R.string.status_failed
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,231 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.provider.Settings as SystemSettings
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.mtps.tern.BuildConfigInfo
|
||||
import pl.mtps.tern.R
|
||||
import pl.mtps.tern.data.Device
|
||||
import pl.mtps.tern.push.Push
|
||||
import pl.mtps.tern.push.PushState
|
||||
import pl.mtps.tern.tern
|
||||
import pl.mtps.tern.ui.theme.ThemeMode
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(onBack: () -> Unit) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.settings)) },
|
||||
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.back)) } },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
NotificationSettings()
|
||||
HorizontalDivider()
|
||||
AppearanceSettings()
|
||||
HorizontalDivider()
|
||||
AccountSettings()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Heading(text: String) = Text(text, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary)
|
||||
|
||||
/**
|
||||
* Push setup and diagnostics. Push has three moving parts (the distributor
|
||||
* app, its push server, and this server reaching it), so this shows where
|
||||
* a registration stands and can send a test notification end to end.
|
||||
*/
|
||||
@Composable
|
||||
private fun NotificationSettings() {
|
||||
val context = LocalContext.current
|
||||
val app = context.tern
|
||||
val scope = rememberCoroutineScope()
|
||||
val wanted by app.settings.pushWanted.collectAsState(false)
|
||||
val status by PushState.status.collectAsStateWithLifecycle()
|
||||
var device by remember { mutableStateOf<Device?>(null) }
|
||||
var testResult by remember { mutableStateOf<String?>(null) }
|
||||
var refreshKey by remember { mutableStateOf(0) }
|
||||
val distributors = remember(refreshKey) { Push.distributors(context) }
|
||||
val saved = remember(refreshKey, status) { Push.savedDistributor(context) }
|
||||
val permitted = NotificationManagerCompat.from(context).areNotificationsEnabled()
|
||||
|
||||
LaunchedEffect(wanted, status, refreshKey) {
|
||||
device = runCatching {
|
||||
val id = app.settings.device()?.first ?: return@runCatching null
|
||||
app.repository.api().devices().find { it.id == id }
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
val enable = rememberEnableNotifications { refreshKey++ }
|
||||
|
||||
Heading(stringResource(R.string.notifications))
|
||||
Text(stringResource(R.string.notifications_explainer), style = MaterialTheme.typography.bodySmall)
|
||||
|
||||
val summary = when {
|
||||
!permitted && wanted -> stringResource(R.string.push_blocked)
|
||||
status is PushState.Status.NoDistributor || (wanted && distributors.isEmpty()) -> stringResource(R.string.push_no_distributor)
|
||||
status is PushState.Status.Failed -> stringResource(R.string.push_failed, (status as PushState.Status.Failed).reason)
|
||||
wanted && device != null -> stringResource(R.string.push_on, appLabel(context, saved) ?: saved ?: "?")
|
||||
wanted -> stringResource(R.string.push_registering)
|
||||
else -> stringResource(R.string.push_off)
|
||||
}
|
||||
Text(summary, style = MaterialTheme.typography.bodyMedium)
|
||||
device?.lastError?.let { Text(stringResource(R.string.last_push_error, it), color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (!wanted) {
|
||||
Button(onClick = enable) { Text(stringResource(R.string.turn_on_notifications)) }
|
||||
} else {
|
||||
OutlinedButton(onClick = { scope.launch { Push.disable(context); refreshKey++ } }) { Text(stringResource(R.string.turn_off)) }
|
||||
device?.let { d ->
|
||||
Button(onClick = {
|
||||
testResult = null
|
||||
scope.launch {
|
||||
testResult = runCatching { app.repository.api().testDevice(d.id) }.fold(
|
||||
{ if (it.delivered) context.getString(R.string.test_sent) else context.getString(R.string.test_failed, it.error ?: "${it.status}") },
|
||||
{ context.getString(R.string.test_failed, it.message ?: "") },
|
||||
)
|
||||
}
|
||||
}) { Text(stringResource(R.string.send_test)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
testResult?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
|
||||
// More than one distributor installed: let the reader choose.
|
||||
if (wanted && distributors.size > 1) {
|
||||
Text(stringResource(R.string.distributor), style = MaterialTheme.typography.labelLarge)
|
||||
distributors.forEach { pkg ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().selectable(pkg == saved, role = Role.RadioButton) {
|
||||
scope.launch { Push.enable(context as Activity, pkg); refreshKey++ }
|
||||
},
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(pkg == saved, null)
|
||||
Text(appLabel(context, pkg) ?: pkg, Modifier.padding(start = 8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (wanted) {
|
||||
Text(
|
||||
stringResource(R.string.system_notification_settings),
|
||||
Modifier.clickable {
|
||||
context.startActivity(
|
||||
Intent(SystemSettings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(SystemSettings.EXTRA_APP_PACKAGE, context.packageName),
|
||||
)
|
||||
}.padding(vertical = 4.dp),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun appLabel(context: android.content.Context, pkg: String?): String? = pkg?.let {
|
||||
runCatching {
|
||||
val pm = context.packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(it, 0)).toString()
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AppearanceSettings() {
|
||||
val app = LocalContext.current.tern
|
||||
val scope = rememberCoroutineScope()
|
||||
val theme by app.settings.theme.collectAsState(ThemeMode.SYSTEM)
|
||||
val dynamic by app.settings.dynamicColor.collectAsState(true)
|
||||
|
||||
Heading(stringResource(R.string.appearance))
|
||||
listOf(ThemeMode.SYSTEM to R.string.theme_system, ThemeMode.LIGHT to R.string.theme_light, ThemeMode.DARK to R.string.theme_dark)
|
||||
.forEach { (mode, label) ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().selectable(theme == mode, role = Role.RadioButton) { scope.launch { app.settings.setTheme(mode) } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(theme == mode, null)
|
||||
Text(stringResource(label), Modifier.padding(start = 8.dp))
|
||||
}
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.dynamic_color))
|
||||
Text(stringResource(R.string.dynamic_color_explainer), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Switch(dynamic, { scope.launch { app.settings.setDynamicColor(it) } })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AccountSettings() {
|
||||
val context = LocalContext.current
|
||||
val app = context.tern
|
||||
val scope = rememberCoroutineScope()
|
||||
val session by app.settings.session.collectAsState(null)
|
||||
|
||||
Heading(stringResource(R.string.account))
|
||||
session?.let { Text(stringResource(R.string.signed_in_as, it.username, it.serverUrl), style = MaterialTheme.typography.bodyMedium) }
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch {
|
||||
// Stop pushes to this phone before the session goes away.
|
||||
runCatching {
|
||||
app.settings.device()?.first?.let { app.repository.api().deleteDevice(it) }
|
||||
}
|
||||
Push.disable(context)
|
||||
app.notifier.cancelAll()
|
||||
app.repository.signOut()
|
||||
}
|
||||
}) { Text(stringResource(R.string.sign_out)) }
|
||||
Text(stringResource(R.string.version, BuildConfigInfo.versionName(context)), style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import pl.mtps.tern.R
|
||||
import pl.mtps.tern.tern
|
||||
|
||||
/** First-run step one (§6): connect to the Tern server. */
|
||||
@Composable
|
||||
fun SignInScreen() {
|
||||
val app = LocalContext.current.tern
|
||||
val scope = rememberCoroutineScope()
|
||||
var server by rememberSaveable { mutableStateOf("") }
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var password by rememberSaveable { mutableStateOf("") }
|
||||
var register by rememberSaveable { mutableStateOf(false) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
// Signing back in after a sign-out only needs the password.
|
||||
LaunchedEffect(Unit) {
|
||||
if (server.isEmpty()) server = app.settings.lastServer.first() ?: ""
|
||||
if (username.isEmpty()) username = app.settings.lastUsername.first() ?: ""
|
||||
}
|
||||
|
||||
fun submit() {
|
||||
busy = true
|
||||
error = null
|
||||
scope.launch {
|
||||
try {
|
||||
app.repository.signIn(server, username, password, register)
|
||||
} catch (e: Exception) {
|
||||
error = when {
|
||||
e is pl.mtps.tern.data.ApiException && e.unauthorized -> "Wrong username or password."
|
||||
e is IllegalArgumentException -> e.message
|
||||
else -> e.message ?: "Couldn't connect."
|
||||
}
|
||||
} finally {
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier.fillMaxSize().safeDrawingPadding().imePadding().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Column(Modifier.widthIn(max = 480.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.displaySmall, color = MaterialTheme.colorScheme.primary)
|
||||
Text(stringResource(R.string.sign_in_intro), style = MaterialTheme.typography.bodyLarge)
|
||||
OutlinedTextField(
|
||||
server, { server = it }, Modifier.fillMaxWidth(),
|
||||
label = { Text(stringResource(R.string.server_address)) },
|
||||
placeholder = { Text("mail.example.org") },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next),
|
||||
)
|
||||
OutlinedTextField(
|
||||
username, { username = it }, Modifier.fillMaxWidth(),
|
||||
label = { Text(stringResource(R.string.username)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
)
|
||||
OutlinedTextField(
|
||||
password, { password = it }, Modifier.fillMaxWidth(),
|
||||
label = { Text(stringResource(R.string.password)) },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done),
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Switch(register, { register = it })
|
||||
Text(stringResource(R.string.create_user), Modifier.padding(start = 12.dp))
|
||||
}
|
||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
Button(
|
||||
onClick = ::submit,
|
||||
enabled = !busy && server.isNotBlank() && username.isNotBlank() && password.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (busy) CircularProgressIndicator(Modifier.padding(end = 8.dp).widthIn(max = 18.dp), strokeWidth = 2.dp)
|
||||
Text(stringResource(if (register) R.string.create_and_sign_in else R.string.sign_in))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import pl.mtps.tern.tern
|
||||
|
||||
private enum class Root { Loading, SignedOut, Onboarding, Ready }
|
||||
|
||||
/** Screens that open over the mail UI, which stays composed underneath. */
|
||||
sealed interface Overlay {
|
||||
data class Compose(val seed: ComposeSeed) : Overlay
|
||||
data object Outbox : Overlay
|
||||
data object Settings : Overlay
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun TernApp(openThread: String?, onOpenThreadHandled: () -> Unit) {
|
||||
val app = LocalContext.current.tern
|
||||
val root by remember {
|
||||
combine(app.settings.session, app.settings.onboarded) { session, onboarded ->
|
||||
when {
|
||||
session == null -> Root.SignedOut
|
||||
!onboarded -> Root.Onboarding
|
||||
else -> Root.Ready
|
||||
}
|
||||
}
|
||||
}.collectAsState(Root.Loading)
|
||||
|
||||
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
|
||||
when (root) {
|
||||
Root.Loading -> {}
|
||||
Root.SignedOut -> SignInScreen()
|
||||
Root.Onboarding -> OnboardingScreen()
|
||||
Root.Ready -> SignedIn(openThread, onOpenThreadHandled)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SignedIn(openThread: String?, onOpenThreadHandled: () -> Unit) {
|
||||
val vm: MailViewModel = viewModel()
|
||||
val overlays = remember { mutableStateListOf<Overlay>() }
|
||||
fun push(o: Overlay) = overlays.add(o)
|
||||
fun pop() { if (overlays.isNotEmpty()) overlays.removeAt(overlays.lastIndex) }
|
||||
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
MailScreen(
|
||||
vm = vm,
|
||||
openThread = openThread,
|
||||
onOpenThreadHandled = onOpenThreadHandled,
|
||||
onCompose = { push(Overlay.Compose(it)) },
|
||||
onOutbox = { push(Overlay.Outbox) },
|
||||
onSettings = { push(Overlay.Settings) },
|
||||
)
|
||||
overlays.lastOrNull()?.let { top ->
|
||||
BackHandler { pop() }
|
||||
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
|
||||
when (top) {
|
||||
is Overlay.Compose -> ComposeScreen(vm, top.seed, onDone = ::pop)
|
||||
Overlay.Outbox -> OutboxScreen(vm, onBack = ::pop, onOpen = { push(Overlay.Compose(it)) })
|
||||
Overlay.Settings -> SettingsScreen(onBack = ::pop)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Menu
|
||||
import androidx.compose.material.icons.outlined.Archive
|
||||
import androidx.compose.material.icons.outlined.AttachFile
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Edit
|
||||
import androidx.compose.material.icons.outlined.RestoreFromTrash
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SwipeToDismissBox
|
||||
import androidx.compose.material3.SwipeToDismissBoxValue
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.material3.rememberSwipeToDismissBoxState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.CustomAccessibilityAction
|
||||
import androidx.compose.ui.semantics.customActions
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import pl.mtps.tern.R
|
||||
import pl.mtps.tern.data.Actions
|
||||
import pl.mtps.tern.data.MailView
|
||||
import pl.mtps.tern.data.Tag
|
||||
import pl.mtps.tern.data.ThreadSummary
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ThreadListPane(
|
||||
vm: MailViewModel,
|
||||
selectedId: String?,
|
||||
showMenu: Boolean,
|
||||
onMenu: () -> Unit,
|
||||
onOpen: (String) -> Unit,
|
||||
onCompose: () -> Unit,
|
||||
) {
|
||||
val view by vm.view.collectAsStateWithLifecycle()
|
||||
val threads by vm.threads.collectAsStateWithLifecycle()
|
||||
val tags by vm.tags.collectAsStateWithLifecycle()
|
||||
val folders by vm.folders.collectAsStateWithLifecycle()
|
||||
val refreshing by vm.refreshing.collectAsStateWithLifecycle()
|
||||
val hasMore by vm.hasMore.collectAsStateWithLifecycle()
|
||||
|
||||
val title = when (val v = view) {
|
||||
MailView.Inbox -> stringResource(R.string.view_inbox)
|
||||
MailView.All -> stringResource(R.string.view_all)
|
||||
MailView.Sent -> stringResource(R.string.view_sent)
|
||||
MailView.Junk -> stringResource(R.string.view_junk)
|
||||
MailView.Trash -> stringResource(R.string.view_trash)
|
||||
is MailView.InFolder -> folders.find { it.id == v.id }?.name ?: stringResource(R.string.folder)
|
||||
is MailView.Tagged -> tags.find { it.id == v.id }?.name ?: stringResource(R.string.tag)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(title) },
|
||||
navigationIcon = {
|
||||
if (showMenu) IconButton(onClick = onMenu) { Icon(Icons.Filled.Menu, stringResource(R.string.open_menu)) }
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onCompose,
|
||||
icon = { Icon(Icons.Outlined.Edit, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.compose)) },
|
||||
containerColor = MaterialTheme.colorScheme.tertiaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onTertiaryContainer,
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
PullToRefreshBox(isRefreshing = refreshing, onRefresh = vm::refresh, modifier = Modifier.padding(padding).fillMaxSize()) {
|
||||
if (threads.isEmpty() && !refreshing) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(if (view == MailView.Inbox) R.string.inbox_zero else R.string.nothing_here),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(threads, key = { it.threadId }) { t ->
|
||||
SwipeableRow(t, view, tags, selected = t.threadId == selectedId, onOpen = { onOpen(t.threadId) }, vm = vm)
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f))
|
||||
}
|
||||
if (hasMore) {
|
||||
item(key = "more") {
|
||||
LaunchedEffect(threads.size) { vm.loadMore() }
|
||||
Box(Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator(Modifier.size(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Swipe right to archive, left to delete (restore, in Trash). The whole
|
||||
* row is the swipe target, never a screen edge, so it can't collide with
|
||||
* the system back gesture (§3).
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun SwipeableRow(
|
||||
t: ThreadSummary,
|
||||
view: MailView,
|
||||
tags: List<Tag>,
|
||||
selected: Boolean,
|
||||
onOpen: () -> Unit,
|
||||
vm: MailViewModel,
|
||||
) {
|
||||
val inTrash = view == MailView.Trash
|
||||
val archiveLabel = stringResource(R.string.archive)
|
||||
val deleteLabel = stringResource(R.string.delete)
|
||||
val restoreLabel = stringResource(R.string.restore)
|
||||
val archived = stringResource(R.string.archived)
|
||||
val deleted = stringResource(R.string.moved_to_trash)
|
||||
val restored = stringResource(R.string.restored)
|
||||
// All mail keeps archived conversations; every other view loses them.
|
||||
fun archive() = vm.act(t.threadId, listOf(Actions.archive), leavesView = view != MailView.All, confirmation = archived)
|
||||
fun delete() = vm.act(t.threadId, listOf(Actions.delete), leavesView = true, confirmation = deleted)
|
||||
fun restore() = vm.act(t.threadId, listOf(Actions.restore), leavesView = true, confirmation = restored)
|
||||
|
||||
val state = rememberSwipeToDismissBoxState()
|
||||
val scope = rememberCoroutineScope()
|
||||
SwipeToDismissBox(
|
||||
state = state,
|
||||
enableDismissFromStartToEnd = !inTrash,
|
||||
onDismiss = { value ->
|
||||
when (value) {
|
||||
SwipeToDismissBoxValue.StartToEnd -> archive()
|
||||
SwipeToDismissBoxValue.EndToStart -> if (inTrash) restore() else delete()
|
||||
SwipeToDismissBoxValue.Settled -> {}
|
||||
}
|
||||
// If the row stays in this view, it slides back into place.
|
||||
scope.launch { state.reset() }
|
||||
},
|
||||
backgroundContent = {
|
||||
val (icon, color, alignment) = when (state.dismissDirection) {
|
||||
SwipeToDismissBoxValue.StartToEnd -> Triple(Icons.Outlined.Archive, MaterialTheme.colorScheme.secondaryContainer, Alignment.CenterStart)
|
||||
SwipeToDismissBoxValue.EndToStart ->
|
||||
if (inTrash) Triple(Icons.Outlined.RestoreFromTrash, MaterialTheme.colorScheme.secondaryContainer, Alignment.CenterEnd)
|
||||
else Triple(Icons.Outlined.Delete, MaterialTheme.colorScheme.errorContainer, Alignment.CenterEnd)
|
||||
SwipeToDismissBoxValue.Settled -> Triple(null, Color.Transparent, Alignment.Center)
|
||||
}
|
||||
Box(Modifier.fillMaxSize().background(color).padding(horizontal = 24.dp), contentAlignment = alignment) {
|
||||
icon?.let { Icon(it, contentDescription = null) }
|
||||
}
|
||||
},
|
||||
// Screen readers can't swipe: the same actions, as accessibility actions (§8).
|
||||
modifier = Modifier.semantics {
|
||||
customActions = buildList {
|
||||
if (inTrash) add(CustomAccessibilityAction(restoreLabel) { restore(); true })
|
||||
else {
|
||||
add(CustomAccessibilityAction(archiveLabel) { archive(); true })
|
||||
add(CustomAccessibilityAction(deleteLabel) { delete(); true })
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
ThreadRow(t, tags, selected, onOpen)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ThreadRow(t: ThreadSummary, tags: List<Tag>, selected: Boolean, onOpen: () -> Unit) {
|
||||
val unread = t.unreadCount > 0
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(if (selected) colors.secondaryContainer else colors.surface)
|
||||
.clickable(onClick = onOpen)
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
// Unread marker: the accent colour, used sparingly (branding §1).
|
||||
Box(Modifier.padding(top = 6.dp, end = 10.dp).size(8.dp).background(if (unread) colors.tertiary else Color.Transparent, CircleShape))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
t.lastFrom ?: stringResource(R.string.unknown_sender),
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = if (unread) FontWeight.Bold else FontWeight.Normal,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (t.messageCount > 1) {
|
||||
Text("${t.messageCount}", style = MaterialTheme.typography.labelSmall, color = colors.onSurfaceVariant)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
Text(formatShort(t.lastMessageAt), style = MaterialTheme.typography.labelSmall, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text(
|
||||
t.subject?.takeIf { it.isNotBlank() } ?: stringResource(R.string.no_subject),
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = if (unread) FontWeight.SemiBold else FontWeight.Normal,
|
||||
color = if (unread) colors.onSurface else colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (t.hasAttachments) Icon(Icons.Outlined.AttachFile, stringResource(R.string.has_attachments), Modifier.size(16.dp))
|
||||
t.tagIds.mapNotNull { id -> tags.find { it.id == id } }.forEach { tag ->
|
||||
Box(Modifier.size(10.dp).background(tagColor(tag) ?: colors.primary, CircleShape))
|
||||
}
|
||||
}
|
||||
t.purgesAt?.let {
|
||||
Text(
|
||||
stringResource(R.string.deleted_for_good, formatShort(it)),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = colors.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package pl.mtps.tern.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Reply
|
||||
import androidx.compose.material.icons.automirrored.filled.ReplyAll
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.outlined.Archive
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.MarkEmailUnread
|
||||
import androidx.compose.material.icons.outlined.RestoreFromTrash
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import pl.mtps.tern.R
|
||||
import pl.mtps.tern.data.Actions
|
||||
import pl.mtps.tern.data.MailView
|
||||
import pl.mtps.tern.data.Message
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ThreadPane(
|
||||
vm: MailViewModel,
|
||||
threadId: String,
|
||||
showBack: Boolean,
|
||||
onBack: () -> Unit,
|
||||
onCompose: (ComposeSeed) -> Unit,
|
||||
onLeft: () -> Unit,
|
||||
) {
|
||||
val view by vm.view.collectAsStateWithLifecycle()
|
||||
val all by remember(threadId) { vm.messages(threadId) }.collectAsState(emptyList())
|
||||
val threads by vm.threads.collectAsStateWithLifecycle()
|
||||
val folders by vm.folders.collectAsStateWithLifecycle()
|
||||
val tags by vm.tags.collectAsStateWithLifecycle()
|
||||
val accounts by vm.accounts.collectAsStateWithLifecycle()
|
||||
val inTrash = view == MailView.Trash
|
||||
// A rule may have trashed one message of a thread: outside Trash it's
|
||||
// hidden, in Trash only the trashed ones show (as on the web).
|
||||
val messages = all.filter { (it.deletedAt != null) == inTrash }
|
||||
val summary = threads.find { it.threadId == threadId }
|
||||
val own = accounts.flatMap { listOfNotNull(it.emailAddress, it.username.takeIf { u -> '@' in u }) }
|
||||
|
||||
val expanded = remember(threadId) { mutableStateMapOf<String, Boolean>() }
|
||||
LaunchedEffect(messages.lastOrNull()?.id) {
|
||||
// The newest message opens; earlier ones stay collapsed until tapped.
|
||||
messages.lastOrNull()?.let { expanded.putIfAbsent(it.id, true) }
|
||||
}
|
||||
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var moveDialog by remember { mutableStateOf(false) }
|
||||
var tagDialog by remember { mutableStateOf(false) }
|
||||
|
||||
fun act(actions: List<JsonObject>, leaves: Boolean, confirmation: String? = null) {
|
||||
vm.act(threadId, actions, leavesView = leaves, confirmation = confirmation)
|
||||
if (leaves) onLeft()
|
||||
}
|
||||
|
||||
val archived = stringResource(R.string.archived)
|
||||
val trashed = stringResource(R.string.moved_to_trash)
|
||||
val restored = stringResource(R.string.restored)
|
||||
val reported = stringResource(R.string.reported_spam)
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = {},
|
||||
navigationIcon = {
|
||||
if (showBack) IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.back)) }
|
||||
},
|
||||
actions = {
|
||||
if (inTrash) {
|
||||
IconButton(onClick = { act(listOf(Actions.restore), true, restored) }) {
|
||||
Icon(Icons.Outlined.RestoreFromTrash, stringResource(R.string.restore))
|
||||
}
|
||||
} else {
|
||||
IconButton(onClick = { act(listOf(Actions.archive), true, archived) }) {
|
||||
Icon(Icons.Outlined.Archive, stringResource(R.string.archive))
|
||||
}
|
||||
IconButton(onClick = { act(listOf(Actions.delete), true, trashed) }) {
|
||||
Icon(Icons.Outlined.Delete, stringResource(R.string.delete))
|
||||
}
|
||||
}
|
||||
IconButton(onClick = { act(listOf(Actions.markUnread), false); onBack() }) {
|
||||
Icon(Icons.Outlined.MarkEmailUnread, stringResource(R.string.mark_unread))
|
||||
}
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, stringResource(R.string.more)) }
|
||||
DropdownMenu(menu, { menu = false }) {
|
||||
if (!inTrash) {
|
||||
if (view == MailView.Junk) {
|
||||
DropdownMenuItem({ Text(stringResource(R.string.not_spam)) }, { menu = false; act(listOf(Actions.move(null)), true) })
|
||||
} else {
|
||||
DropdownMenuItem({ Text(stringResource(R.string.report_spam)) }, { menu = false; act(listOf(Actions.junk), true, reported) })
|
||||
}
|
||||
}
|
||||
DropdownMenuItem({ Text(stringResource(R.string.move_to)) }, { menu = false; moveDialog = true })
|
||||
if (tags.isNotEmpty()) DropdownMenuItem({ Text(stringResource(R.string.tags)) }, { menu = false; tagDialog = true })
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
LazyColumn(Modifier.padding(padding).fillMaxSize(), contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = 24.dp)) {
|
||||
item {
|
||||
Text(
|
||||
messages.firstOrNull()?.subject?.takeIf { it.isNotBlank() } ?: summary?.subject ?: stringResource(R.string.no_subject),
|
||||
Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
)
|
||||
summary?.tagIds?.mapNotNull { id -> tags.find { it.id == id } }?.takeIf { it.isNotEmpty() }?.let { ts ->
|
||||
Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ts.forEach { AssistChip(onClick = {}, label = { Text(it.name) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
items(messages, key = { it.id }) { m ->
|
||||
MessageCard(m, expanded[m.id] == true, onToggle = { expanded[m.id] = expanded[m.id] != true })
|
||||
HorizontalDivider(Modifier.padding(horizontal = 16.dp), color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
|
||||
}
|
||||
messages.lastOrNull()?.let { newest ->
|
||||
item {
|
||||
Row(Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedButton(onClick = { onCompose(replySeed(newest, own, all = false)) }) {
|
||||
Icon(Icons.AutoMirrored.Filled.Reply, contentDescription = null)
|
||||
Text(stringResource(R.string.reply), Modifier.padding(start = 8.dp))
|
||||
}
|
||||
OutlinedButton(onClick = { onCompose(replySeed(newest, own, all = true)) }) {
|
||||
Icon(Icons.AutoMirrored.Filled.ReplyAll, contentDescription = null)
|
||||
Text(stringResource(R.string.reply_all), Modifier.padding(start = 8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (moveDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { moveDialog = false },
|
||||
title = { Text(stringResource(R.string.move_to)) },
|
||||
text = {
|
||||
Column {
|
||||
TextButton({ moveDialog = false; act(listOf(Actions.move(null)), view != MailView.Inbox) }) { Text(stringResource(R.string.view_inbox)) }
|
||||
folders.filter { it.role != "junk" }.forEach { f ->
|
||||
TextButton({ moveDialog = false; act(listOf(Actions.move(f.id)), view != MailView.InFolder(f.id)) }) { Text(f.name) }
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {},
|
||||
dismissButton = { TextButton({ moveDialog = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
if (tagDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { tagDialog = false },
|
||||
title = { Text(stringResource(R.string.tags)) },
|
||||
text = {
|
||||
Column {
|
||||
tags.forEach { t ->
|
||||
val on = summary?.tagIds?.contains(t.id) == true
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { act(listOf(if (on) Actions.untag(t.id) else Actions.tag(t.id)), view == MailView.Tagged(t.id) && on) },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(on, null)
|
||||
Text(t.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton({ tagDialog = false }) { Text(stringResource(R.string.done)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MessageCard(m: Message, expanded: Boolean, onToggle: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.fillMaxWidth().clickable(onClick = onToggle).padding(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
m.sender,
|
||||
Modifier.weight(1f),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = if (m.unread) FontWeight.Bold else FontWeight.Medium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(formatShort(m.sentAt ?: m.createdAt), style = MaterialTheme.typography.labelSmall, color = colors.onSurfaceVariant)
|
||||
}
|
||||
if (expanded) {
|
||||
val to = (m.toAddrs + m.ccAddrs).joinToString(", ")
|
||||
if (to.isNotEmpty()) {
|
||||
Text(stringResource(R.string.to_line, to), style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant)
|
||||
}
|
||||
m.spamScore?.let {
|
||||
Text(stringResource(R.string.spam_score, it), style = MaterialTheme.typography.labelSmall, color = colors.error)
|
||||
}
|
||||
} else {
|
||||
Text(
|
||||
preview(m),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (expanded) {
|
||||
val body = m.body
|
||||
when {
|
||||
body == null -> Text(stringResource(R.string.body_not_downloaded), Modifier.padding(16.dp), color = colors.onSurfaceVariant)
|
||||
body.htmlBody != null -> HtmlBody(m.id, body.htmlBody, Modifier.padding(horizontal = 8.dp))
|
||||
else -> SelectionContainer {
|
||||
Text(body.textBody.orEmpty(), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun preview(m: Message): String =
|
||||
m.body?.textBody?.lineSequence()?.map { it.trim() }?.filter { it.isNotEmpty() && !it.startsWith(">") }?.joinToString(" ")?.take(160)
|
||||
?: ""
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Status-bar icon: the wing mark from the launcher icon, one colour. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M12,6.1 L22,17.9 L16.5,17.9 L12,12.5 L7.5,17.9 L2,17.9 Z" />
|
||||
</vector>
|
||||
@@ -1,3 +1,137 @@
|
||||
<resources>
|
||||
<string name="app_name">Tern</string>
|
||||
|
||||
<!-- Sign-in and first run -->
|
||||
<string name="sign_in_intro">Sign in to your Tern server.</string>
|
||||
<string name="server_address">Server address</string>
|
||||
<string name="username">Username</string>
|
||||
<string name="password">Password</string>
|
||||
<string name="create_user">Create a new user on this server</string>
|
||||
<string name="sign_in">Sign in</string>
|
||||
<string name="create_and_sign_in">Create user and sign in</string>
|
||||
<string name="add_account_title">Add a mail account</string>
|
||||
<string name="add_account_intro">Tern syncs mail from your IMAP server and sends through its SMTP server. The password is stored encrypted on your Tern server, never on this phone.</string>
|
||||
<string name="email_address">Email address</string>
|
||||
<string name="display_name">Your name (optional)</string>
|
||||
<string name="imap_host">IMAP server</string>
|
||||
<string name="smtp_host">SMTP server</string>
|
||||
<string name="port">Port</string>
|
||||
<string name="login">Login</string>
|
||||
<string name="add_account">Add account</string>
|
||||
<string name="skip_account">Skip — I\'ll add accounts in the web app</string>
|
||||
<string name="notifications_title">Get notified about new mail?</string>
|
||||
<string name="notifications_intro">Tern uses UnifiedPush, so no Google services are involved: a distributor app such as ntfy wakes Tern when mail arrives, and Tern then fetches it from your server. The push itself carries no mail content. Your rules decide which mail notifies.</string>
|
||||
<string name="turn_on_notifications">Turn on notifications</string>
|
||||
<string name="not_now">Not now</string>
|
||||
|
||||
<!-- Mailboxes -->
|
||||
<string name="view_inbox">Inbox</string>
|
||||
<string name="view_all">All mail</string>
|
||||
<string name="view_sent">Sent</string>
|
||||
<string name="view_junk">Junk</string>
|
||||
<string name="view_trash">Trash</string>
|
||||
<string name="outbox">Outbox</string>
|
||||
<string name="folders">Folders</string>
|
||||
<string name="folder">Folder</string>
|
||||
<string name="tags">Tags</string>
|
||||
<string name="tag">Tag</string>
|
||||
<string name="settings">Settings</string>
|
||||
<string name="open_menu">Open mailboxes</string>
|
||||
<string name="compose">Compose</string>
|
||||
<string name="inbox_zero">Inbox zero.</string>
|
||||
<string name="nothing_here">Nothing here.</string>
|
||||
<string name="select_conversation">Select a conversation to read it.</string>
|
||||
<string name="unknown_sender">Unknown sender</string>
|
||||
<string name="no_subject">(no subject)</string>
|
||||
<string name="has_attachments">Has attachments</string>
|
||||
<string name="deleted_for_good">Deleted for good on %1$s</string>
|
||||
|
||||
<!-- Actions -->
|
||||
<string name="archive">Archive</string>
|
||||
<string name="delete">Delete</string>
|
||||
<string name="restore">Restore</string>
|
||||
<string name="mark_unread">Mark unread</string>
|
||||
<string name="more">More options</string>
|
||||
<string name="report_spam">Report spam</string>
|
||||
<string name="not_spam">Not spam</string>
|
||||
<string name="move_to">Move to…</string>
|
||||
<string name="archived">Archived</string>
|
||||
<string name="moved_to_trash">Moved to Trash</string>
|
||||
<string name="restored">Restored</string>
|
||||
<string name="reported_spam">Moved to Junk</string>
|
||||
<string name="back">Back</string>
|
||||
<string name="cancel">Cancel</string>
|
||||
<string name="done">Done</string>
|
||||
<string name="close">Close</string>
|
||||
|
||||
<!-- Reading -->
|
||||
<string name="to_line">To: %1$s</string>
|
||||
<string name="spam_score">Spam score %1$.1f</string>
|
||||
<string name="body_not_downloaded">This message\'s body hasn\'t been downloaded yet.</string>
|
||||
<string name="show_images">Show remote images</string>
|
||||
<string name="images_blocked">Remote images are blocked — they can tell the sender you opened this.</string>
|
||||
<string name="images_shown">Remote images shown for this message.</string>
|
||||
<string name="reply">Reply</string>
|
||||
<string name="reply_all">Reply all</string>
|
||||
|
||||
<!-- Compose and outbox -->
|
||||
<string name="from">From</string>
|
||||
<string name="to">To</string>
|
||||
<string name="cc">Cc</string>
|
||||
<string name="bcc">Bcc</string>
|
||||
<string name="cc_bcc">Cc/Bcc</string>
|
||||
<string name="subject">Subject</string>
|
||||
<string name="message">Message</string>
|
||||
<string name="send">Send</string>
|
||||
<string name="save_draft_q">Save this as a draft?</string>
|
||||
<string name="save_draft">Save draft</string>
|
||||
<string name="discard">Discard</string>
|
||||
<string name="outbox_empty">Nothing waiting to be sent.</string>
|
||||
<string name="status_draft">Draft</string>
|
||||
<string name="status_pending">Queued</string>
|
||||
<string name="status_sending">Sending</string>
|
||||
<string name="status_sent">Sent</string>
|
||||
<string name="status_failed">Failed</string>
|
||||
|
||||
<!-- Settings -->
|
||||
<string name="notifications">Notifications</string>
|
||||
<string name="notifications_explainer">Pushed through UnifiedPush by your distributor app (e.g. ntfy). Rules on the server decide which mail notifies.</string>
|
||||
<string name="push_off">Off.</string>
|
||||
<string name="push_registering">Registering with the distributor…</string>
|
||||
<string name="push_on">On, through %1$s.</string>
|
||||
<string name="push_blocked">Notifications are blocked for Tern in Android\'s settings.</string>
|
||||
<string name="push_no_distributor">No UnifiedPush distributor is installed. Install one — ntfy from F-Droid, for example — then turn notifications on here.</string>
|
||||
<string name="push_failed">The distributor refused the registration (%1$s).</string>
|
||||
<string name="last_push_error">Last push failed: %1$s</string>
|
||||
<string name="turn_off">Turn off</string>
|
||||
<string name="send_test">Send a test push</string>
|
||||
<string name="test_sent">Delivered to the push server. The phone should sync within a few seconds.</string>
|
||||
<string name="test_failed">Not delivered: %1$s</string>
|
||||
<string name="distributor">Distributor</string>
|
||||
<string name="system_notification_settings">Sound, vibration and more in Android settings</string>
|
||||
<string name="appearance">Appearance</string>
|
||||
<string name="theme_system">Follow system</string>
|
||||
<string name="theme_light">Light</string>
|
||||
<string name="theme_dark">Dark</string>
|
||||
<string name="dynamic_color">Colours from wallpaper</string>
|
||||
<string name="dynamic_color_explainer">Material You. Off uses Tern\'s own palette.</string>
|
||||
<string name="account">Account</string>
|
||||
<string name="signed_in_as">Signed in as %1$s on %2$s</string>
|
||||
<string name="sign_out">Sign out</string>
|
||||
<string name="version">Version %1$s</string>
|
||||
|
||||
<!-- Notifications -->
|
||||
<string name="channel_mail">New mail</string>
|
||||
<string name="channel_sync">Syncing</string>
|
||||
<string name="channel_account">Account</string>
|
||||
<string name="you">You</string>
|
||||
<string name="action_archive">Archive</string>
|
||||
<string name="action_mark_read">Mark read</string>
|
||||
<plurals name="new_conversations">
|
||||
<item quantity="one">%d conversation with new mail</item>
|
||||
<item quantity="other">%d conversations with new mail</item>
|
||||
</plurals>
|
||||
<string name="signed_out_title">Signed out of Tern</string>
|
||||
<string name="signed_out_text">Sign in again to keep getting new mail.</string>
|
||||
<string name="syncing">Checking for new mail</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The mail cache and session never leave the device: no cloud backup, no
|
||||
device-to-device transfer (§7). -->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="root" />
|
||||
<exclude domain="file" />
|
||||
<exclude domain="database" />
|
||||
<exclude domain="sharedpref" />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- HTTPS only. User-installed CAs are trusted as well as system ones, so a
|
||||
self-hosted server behind a private CA works once that CA is installed
|
||||
on the phone (Settings → Security → Encryption & credentials). -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false">
|
||||
<trust-anchors>
|
||||
<certificates src="system" />
|
||||
<certificates src="user" />
|
||||
</trust-anchors>
|
||||
</base-config>
|
||||
</network-security-config>
|
||||
@@ -0,0 +1,58 @@
|
||||
package pl.mtps.tern
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import pl.mtps.tern.data.Api
|
||||
import pl.mtps.tern.data.Message
|
||||
import pl.mtps.tern.data.MessageBody
|
||||
import pl.mtps.tern.ui.parseRecipients
|
||||
import pl.mtps.tern.ui.replySeed
|
||||
|
||||
class ReplyTest {
|
||||
private val me = listOf("alice@example.com")
|
||||
private fun msg(from: String?, to: List<String>, cc: List<String> = emptyList(), source: String = "imap", subject: String = "Plans") =
|
||||
Message(
|
||||
id = "m1", threadId = "t1", accountId = "a1", subject = subject,
|
||||
fromAddr = from, fromName = "Bob", toAddrs = to, ccAddrs = cc,
|
||||
sentAt = "2026-09-23T10:00:00Z", source = source,
|
||||
body = MessageBody(textBody = "Line one\n> quoted"),
|
||||
)
|
||||
|
||||
@Test fun replyGoesToSenderAndQuotes() {
|
||||
val s = replySeed(msg("bob@example.com", listOf("alice@example.com", "carol@example.com")), me, all = false)
|
||||
assertEquals(listOf("bob@example.com"), s.to)
|
||||
assertEquals(emptyList<String>(), s.cc)
|
||||
assertEquals("Re: Plans", s.subject)
|
||||
assertTrue(s.body.contains("> Line one"))
|
||||
assertTrue("already-quoted lines get one more level", s.body.contains(">> quoted"))
|
||||
assertEquals("m1", s.replyToMessageId)
|
||||
}
|
||||
|
||||
@Test fun replyAllDropsOwnAddressesAndDuplicates() {
|
||||
val s = replySeed(
|
||||
msg("bob@example.com", listOf("Alice@Example.com", "carol@example.com"), cc = listOf("dave@example.com", "BOB@example.com")),
|
||||
me, all = true,
|
||||
)
|
||||
assertEquals(listOf("bob@example.com", "carol@example.com"), s.to)
|
||||
assertEquals(listOf("dave@example.com"), s.cc)
|
||||
}
|
||||
|
||||
@Test fun replyingToOwnSentMailWritesToItsRecipients() {
|
||||
val s = replySeed(msg("alice@example.com", listOf("carol@example.com"), source = "sent"), me, all = false)
|
||||
assertEquals(listOf("carol@example.com"), s.to)
|
||||
}
|
||||
|
||||
@Test fun subjectsAlreadyInReplyKeepOnePrefix() {
|
||||
assertEquals("RE: Plans", replySeed(msg("b@x.org", me, subject = "RE: Plans"), me, false).subject)
|
||||
}
|
||||
|
||||
@Test fun recipientsSplitOnCommasSemicolonsAndSpace() {
|
||||
assertEquals(listOf("a@x.org", "b@x.org", "c@x.org"), parseRecipients(" a@x.org, b@x.org;c@x.org "))
|
||||
}
|
||||
|
||||
@Test fun serverAddressesAreNormalised() {
|
||||
assertEquals("https://mail.example.org/", Api.normalizeServerUrl("mail.example.org/").toString())
|
||||
assertEquals("http://10.0.2.2:8080/", Api.normalizeServerUrl(" http://10.0.2.2:8080 ").toString())
|
||||
}
|
||||
}
|
||||
+7
-5
@@ -1,7 +1,9 @@
|
||||
plugins {
|
||||
id("com.android.application") version "8.7.0" apply false
|
||||
id("org.jetbrains.kotlin.android") version "2.0.21" apply false
|
||||
// Kotlin 2.0+ moved the Compose compiler out of AGP into its own plugin,
|
||||
// versioned alongside Kotlin itself.
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
|
||||
// AGP 9 compiles Kotlin itself ("built-in Kotlin"), so the
|
||||
// org.jetbrains.kotlin.android plugin is no longer applied; the
|
||||
// compiler plugins below still are.
|
||||
id("com.android.application") version "9.4.1" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.4.20" apply false
|
||||
id("org.jetbrains.kotlin.plugin.serialization") version "2.4.20" apply false
|
||||
id("com.google.devtools.ksp") version "2.3.12" apply false
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
Reference in new issue
Block a user