commit
Make this the standalone mail server repository
The server moves from email/ to the root, and the Android app leaves for doughmination/apps (email/), where it keeps its history. /download now looks for the APK on that repository's inbox-latest release first, falling back to this one's old latest release. CI drops its path filters and also builds and dry-runs the deploy. Co-Authored-By: Claude Opus 5.5 <[email protected]>
diff --git a/email/.dev.vars.example b/.dev.vars.example
similarity index 100%
rename from email/.dev.vars.example
rename to .dev.vars.example
diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
deleted file mode 100644
index 9a688cd..0000000
--- a/.github/workflows/android.yml
+++ /dev/null
@@ -1,110 +0,0 @@
-name: Build APK
-
-# Only changes under app/ rebuild the APK; tags always do.
-on:
- push:
- branches: [main]
- tags: ["v*"]
- paths: ["app/**", ".github/workflows/android.yml"]
- pull_request:
- paths: ["app/**", ".github/workflows/android.yml"]
- workflow_dispatch:
-
-permissions:
- contents: write
-
-# Builds from main replace the same release, so let them finish in order.
-concurrency:
- group: build-${{ github.ref }}
- cancel-in-progress: false
-
-jobs:
- build:
- runs-on: ubuntu-latest
- env:
- HAS_SIGNING_KEY: ${{ secrets.KEYSTORE_BASE64 != '' }}
- defaults:
- run:
- working-directory: app
- steps:
- - uses: actions/checkout@v4
-
- - uses: actions/setup-java@v4
- with:
- distribution: temurin
- java-version: 21
-
- - uses: gradle/actions/setup-gradle@v4
-
- # Releases must be signed with the app's key, or they can't install over
- # earlier builds; say so rather than quietly skipping the release.
- - name: Require signing key
- if: github.event_name != 'pull_request' && env.HAS_SIGNING_KEY != 'true'
- run: |
- echo "::error::KEYSTORE_BASE64 and KEYSTORE_PASSWORD aren't set on this repository, so no release can be built. See app/README.md (CI)."
- exit 1
-
- # The keystore is stored base64-encoded in secrets. Pull requests from
- # forks don't get secrets, so they build unsigned.
- - name: Restore signing key
- if: env.HAS_SIGNING_KEY == 'true'
- env:
- KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
- KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
- run: |
- echo "$KEYSTORE_BASE64" | base64 -d > inbox.jks
- printf 'storeFile=inbox.jks\nstorePassword=%s\nkeyAlias=inbox\nkeyPassword=%s\n' \
- "$KEYSTORE_PASSWORD" "$KEYSTORE_PASSWORD" > keystore.properties
-
- # Notifications need the Firebase config. Commit app/app/google-services.json
- # (it isn't secret) or store it base64'd in this secret; without either the
- # APK builds with notifications off.
- - name: Restore Firebase config
- env:
- GOOGLE_SERVICES_JSON: ${{ secrets.GOOGLE_SERVICES_JSON }}
- if: env.GOOGLE_SERVICES_JSON != ''
- run: echo "$GOOGLE_SERVICES_JSON" | base64 -d > app/google-services.json
-
- # Tags are named by version (v1.2.0 builds 1.2.0); everything else is 1.0.<run>.
- - name: Version
- env:
- TAG: ${{ startsWith(github.ref, 'refs/tags/v') && github.ref_name || '' }}
- run: |
- version=${TAG#v}
- echo "VERSION_NAME=${version:-1.0.$GITHUB_RUN_NUMBER}" >> "$GITHUB_ENV"
-
- - name: Build
- env:
- VERSION_CODE: ${{ github.run_number }}
- run: ./gradlew assembleRelease --console=plain
-
- - name: Rename APK
- run: |
- src=$(ls app/build/outputs/apk/release/*.apk)
- mv "$src" "inbox-$VERSION_NAME.apk"
- echo "APK=inbox-$VERSION_NAME.apk" >> "$GITHUB_ENV"
-
- - uses: actions/upload-artifact@v4
- with:
- name: inbox-${{ env.VERSION_NAME }}
- path: app/${{ env.APK }}
-
- - name: Publish release
- if: startsWith(github.ref, 'refs/tags/v')
- env:
- GH_TOKEN: ${{ github.token }}
- run: gh release create "$GITHUB_REF_NAME" "$APK" --generate-notes
-
- # A rolling "latest" release that always holds the newest build from main.
- # The site's /download link redirects to its APK, whatever it's named.
- - name: Publish rolling latest
- if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && env.HAS_SIGNING_KEY == 'true'
- env:
- GH_TOKEN: ${{ github.token }}
- run: |
- gh release delete latest --cleanup-tag --yes || true
- gh release create latest "$APK" \
- --target "$GITHUB_SHA" \
- --title "Latest build ($VERSION_NAME)" \
- --notes "Built from ${GITHUB_SHA::7} on main. Installs over any earlier build." \
- --latest
diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml
index dd74e97..57eccb2 100644
--- a/.github/workflows/server.yml
+++ b/.github/workflows/server.yml
@@ -3,19 +3,18 @@ name: Server
on:
push:
branches: [main]
- paths: ["email/**", ".github/workflows/server.yml"]
pull_request:
- paths: ["email/**", ".github/workflows/server.yml"]
jobs:
check:
runs-on: ubuntu-latest
- defaults:
- run:
- working-directory: email
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
- run: bun install --frozen-lockfile
- run: bun run typecheck
- run: bun run test
+ # Builds the Worker and the web app as `npm run deploy` would, then
+ # checks the bundle without uploading anything.
+ - run: bun run build
+ - run: bunx wrangler deploy --dry-run
diff --git a/.gitignore b/.gitignore
index af56f61..a408ec5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,7 @@
+node_modules/
+.wrangler/
+.dev.vars
+dist/
+*.log
.DS_Store
.idea/
diff --git a/email/LICENCE.md b/LICENCE.md
similarity index 100%
rename from email/LICENCE.md
rename to LICENCE.md
diff --git a/README.md b/README.md
index cce9aa2..6d464d2 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,108 @@
# Inbox
-A multi-domain mailbox on Cloudflare Workers, and its Android app.
+A multi-domain mailbox on Cloudflare Workers. Mail comes in and goes out through
+[Resend](https://resend.com), people sign in through the SSO, and every user gets
+`<username>@<domain>` on each domain that's switched on. There's no config file:
+domains, aliases and admins are managed from the Admin page.
-- [`email/`](email/): the Worker (Hono API on D1 + R2, mail through Resend) and
- the Svelte web app it serves. See its README for setup and deploys.
-- [`app/`](app/): the Android app.
+## How it fits together
-CI lives in `.github/workflows/`: `server.yml` typechecks and tests `email/`,
-`android.yml` builds the APK. Each only runs when its own folder changes.
+```
+src/
+ shared/types.ts API shapes, used by both sides
+ worker/ Hono API (only /api, /auth, /webhook reach the Worker)
+ lib/routing.ts who owns which address: pure, unit-tested
+ services/ D1, R2, Resend, SSO, push
+ routes/ HTTP handlers
+ web/ Svelte 5 app, served as static assets
+ components/EmailFrame.svelte the only place email HTML is rendered
+migrations/ D1 schema
+test/ vitest, running inside workerd with local D1 + R2
+```
+
+- **D1** (`DB`) holds users, domains, aliases, threads, messages, sessions.
+- **R2** (`BUCKET`) holds attachment bytes under `inbox/`. It's the same bucket the
+ old proxy used.
+- **Domains** are synced from Resend into D1 (`services/domains.ts`), never typed in.
+- **Routing**: on an active domain, mail to `x@domain` goes to the alias `x` if
+ there is one, otherwise to user `x`, otherwise to that domain's catch-all,
+ otherwise nowhere. You can send from exactly the addresses whose mail reaches
+ you. An email addressed to several users is stored once in each mailbox.
+- **Email rendering**: email HTML goes in a sandboxed `srcdoc` iframe with no
+ script, its own CSP, and remote content blocked until you click to load it.
+ That keeps an email's fonts and styles inside the frame. Attachments are only
+ ever shown inline when they're plain images.
+- **Sign-in**: the SSO, with sessions in D1 keyed by a hash of the cookie's
+ token. The SSO account (`sub`) is the identity, so someone renamed there keeps
+ their mailbox here. Role names like `postmaster` and `abuse` can't be signed up
+ for; hand them out as aliases. `ADMIN_USERS` makes a new account an admin only
+ while there's no admin yet.
+- **Android app**: lives in [doughmination/apps](https://github.com/doughmination/apps)
+ (`email/`). It signs in through the same flow in a browser tab, started with
+ `/auth/login?app=<PKCE challenge>`. The callback redirects to
+ `gay.doughmination.mail://auth?code=...`, the app swaps that code and its
+ verifier at `POST /auth/app/token` for a session token, and sends it as
+ `Authorization: Bearer`. Its `Models.kt` mirrors `src/shared/types.ts` by
+ hand, so API shape changes need a matching app change there.
+- **`/download`** redirects to the newest APK on the app's rolling
+ `inbox-latest` release in doughmination/apps, falling back to this
+ repository's old `latest` release.
+
+## Setup
+
+```sh
+npm install
+cp .dev.vars.example .dev.vars # fill in the secrets
+npx wrangler d1 create email-db-v2 # put the id in wrangler.jsonc
+npm run db:migrate:local
+npm run dev # http://localhost:5173
+```
+
+Local sign-in needs `http://localhost:5173/auth/callback` registered as a redirect
+URI on the SSO client.
+
+`ADMIN_USERS` in `wrangler.jsonc` lists people who are always admins. Anyone the
+SSO lets in becomes a user on first sign-in.
+
+## Deploying
+
+```sh
+npm run db:migrate:remote
+npx wrangler secret put RESEND_API_KEY # also RESEND_WEBHOOK_SECRET,
+ # OIDC_CLIENT_SECRET, VAPID_PRIVATE_KEY
+npx wrangler secret put FCM_SERVICE_ACCOUNT < service-account.json # Android notifications
+npm run deploy
+```
+
+`FCM_SERVICE_ACCOUNT` is the Firebase project's service account key (Firebase
+console > Project settings > Service accounts > Generate new private key). New
+mail is pushed to browsers through Web Push and to the Android app through
+FCM; without the key, the app just gets no notifications.
+
+Then:
+
+1. In Resend, point a webhook at `https://<host>/webhook/inbound` for
+ `email.received`, plus `domain.created`, `domain.updated` and `domain.deleted`.
+2. That's it for domains. They come from your Resend account: every domain there
+ is switched on automatically, and it routes mail once receiving is on in
+ Resend. The list re-syncs on those webhooks, daily, and whenever Admin →
+ Domains is opened. That page is where you switch one off or pick a catch-all.
+
+## Demo
+
+`/demo` (e.g. https://mail.doughmination.gay/demo) is the same app with made-up
+mail and no sign-in. Under that path the API is swapped for an in-memory fake
+(`src/web/lib/demo.ts`), so nothing touches the Worker, D1, R2 or Resend, and no
+real email comes in or goes out. Sending moves a message to Sent, mail to one of
+the demo's own addresses lands in its inbox, anyone else gets a pretend reply a
+few seconds later, and reloading starts over. Locally it's at
+http://localhost:5173/demo.
+
+## Scripts
+
+| | |
+|---|---|
+| `npm run dev` | Vite + the Worker in workerd, with hot reload |
+| `npm run typecheck` | Worker and tests (`tsc`), and the app (`svelte-check`) |
+| `npm test` | vitest inside workerd |
+| `npm run types` | regenerate `worker-configuration.d.ts` after changing `wrangler.jsonc` |
diff --git a/app/.gitignore b/app/.gitignore
deleted file mode 100644
index 71fdeac..0000000
--- a/app/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-.gradle/
-build/
-local.properties
-*.jks
-keystore.properties
-inbox.apk
diff --git a/app/README.md b/app/README.md
deleted file mode 100644
index b976361..0000000
--- a/app/README.md
+++ /dev/null
@@ -1,79 +0,0 @@
-# Inbox for Android
-
-A native Android app (Kotlin, Jetpack Compose) for [Inbox](../email). It talks
-to the same Worker API as the web app.
-
-```
-app/src/main/java/gay/doughmination/mail/
- MainActivity.kt sign-in redirects and links to the site land here
- InboxApp.kt the app-wide Api, Auth, Live and token store
- data/
- Api.kt /api and /auth calls, bearer-signed
- Auth.kt sign-in through the SSO in a browser tab (code + PKCE)
- TokenStore.kt session token, encrypted with an Android Keystore key
- Live.kt the /api/live WebSocket while the app is open
- Models.kt mirrors email/src/shared/types.ts
- ui/
- MailViewModel.kt state and actions for every screen
- ThreadListScreen folders, swipe actions, long-press menu
- ThreadScreen a conversation
- EmailView.kt the only place email HTML is rendered
- ComposeScreen new mail, replies, forwards, drafts
-```
-
-- **Sign-in** opens `/auth/login?app=<challenge>` in a Custom Tab. The server
- redirects to `gay.doughmination.mail://auth?code=...` and the app swaps the code
- and its PKCE verifier for a session token, sent as `Authorization: Bearer`.
-- **Email HTML** renders in a WebView with JavaScript off. Links open in the
- browser, and remote content is blocked until you tap "Load remote images".
-- **Notifications**: when Resend's webhook delivers mail, the Worker sends a
- Firebase Cloud Messaging data message to each signed-in install, and
- `Push.kt` shows it; a tap opens the thread. The app registers its FCM token
- after sign-in and removes it on sign-out.
-- **Admin** stays on the web; the drawer links to it.
-- Links to `mail.doughmination.gay/inbox/...` open in the app, which needs the
- site's `/.well-known/assetlinks.json` to list this app's signing key.
-
-## Building
-
-Needs JDK 17–21 (Gradle 8.11 doesn't run on newer JDKs) and the Android SDK
-(platform 35).
-
-```sh
-echo "sdk.dir=/opt/android-sdk" > local.properties
-./gradlew assembleDebug # app/build/outputs/apk/debug/app-debug.apk
-./gradlew assembleRelease # app/build/outputs/apk/release/app-release.apk
-```
-
-`-PinboxUrl=http://10.0.2.2:5173` points a build at `npm run dev` from the
-emulator. Signing in locally needs `/auth/*` to reach that server too.
-
-Notifications need Firebase: put the project's `google-services.json` at
-`app/google-services.json` (next to `app/build.gradle.kts`). Without it the app
-still builds, with notifications off and Settings saying so.
-
-Signing reads `keystore.properties` (gitignored):
-
-```properties
-storeFile=inbox.jks
-storePassword=...
-keyAlias=inbox
-keyPassword=...
-```
-
-Keep `inbox.jks` backed up. An APK signed with a different key can't be
-installed over this one, and the fingerprint in `assetlinks.json` would need
-changing too.
-
-## CI
-
-`.github/workflows/android.yml` (at the repo root) builds whenever `app/`
-changes and uploads the APK, named by version (`inbox-1.0.6.apk`), as an
-artifact. Each build from `main` replaces the rolling `latest` release, which
-the site's `/download` link redirects to, and pushing a `v1.2.0` tag attaches
-`inbox-1.2.0.apk` to a GitHub release of its own. It signs with two repository secrets:
-
-- `KEYSTORE_BASE64`: `base64 -w0 inbox.jks`
-- `KEYSTORE_PASSWORD`: the keystore password
-- `GOOGLE_SERVICES_JSON` (optional): `base64 -w0 google-services.json`, if you'd
- rather not commit the file
diff --git a/app/app/build.gradle.kts b/app/app/build.gradle.kts
deleted file mode 100644
index 1b301e6..0000000
--- a/app/app/build.gradle.kts
+++ /dev/null
@@ -1,97 +0,0 @@
-import java.util.Properties
-
-plugins {
- id("com.android.application")
- id("org.jetbrains.kotlin.android")
- id("org.jetbrains.kotlin.plugin.compose")
- id("org.jetbrains.kotlin.plugin.serialization")
-}
-
-// Firebase (notifications) is switched on by dropping the project's
-// google-services.json next to this file. Without it the app builds and runs,
-// just without notifications.
-if (file("google-services.json").exists()) apply(plugin = "com.google.gms.google-services")
-
-// Signing details live in keystore.properties (not committed). Without it the
-// release build is left unsigned.
-val keystoreProps = Properties().apply {
- val f = rootProject.file("keystore.properties")
- if (f.exists()) f.inputStream().use { load(it) }
-}
-
-// The server the app talks to; -PinboxUrl=http://10.0.2.2:5173 points a
-// build at a local `npm run dev` from the emulator.
-val inboxUrl = (findProperty("inboxUrl") as String?) ?: "https://mail.doughmination.gay"
-
-android {
- namespace = "gay.doughmination.mail"
- compileSdk = 35
-
- defaultConfig {
- applicationId = "gay.doughmination.mail"
- minSdk = 26
- targetSdk = 35
- // CI passes the run number so every build installs over the last one.
- versionCode = (System.getenv("VERSION_CODE") ?: "1").toInt()
- versionName = System.getenv("VERSION_NAME") ?: "1.0"
- buildConfigField("String", "INBOX_URL", "\"$inboxUrl\"")
- }
-
- signingConfigs {
- if (keystoreProps.isNotEmpty()) {
- create("release") {
- storeFile = rootProject.file(keystoreProps.getProperty("storeFile"))
- storePassword = keystoreProps.getProperty("storePassword")
- keyAlias = keystoreProps.getProperty("keyAlias")
- keyPassword = keystoreProps.getProperty("keyPassword")
- }
- }
- }
-
- buildTypes {
- release {
- isMinifyEnabled = false
- signingConfig = signingConfigs.findByName("release")
- }
- }
-
- buildFeatures {
- compose = true
- buildConfig = true
- }
-
- compileOptions {
- sourceCompatibility = JavaVersion.VERSION_17
- targetCompatibility = JavaVersion.VERSION_17
- }
-
- kotlinOptions {
- jvmTarget = "17"
- }
-}
-
-dependencies {
- val composeBom = platform("androidx.compose:compose-bom:2024.12.01")
- implementation(composeBom)
- implementation("androidx.compose.material3:material3")
- implementation("androidx.compose.material:material-icons-extended")
- implementation("androidx.compose.ui:ui")
- implementation("androidx.compose.ui:ui-tooling-preview")
- debugImplementation("androidx.compose.ui:ui-tooling")
-
- implementation("androidx.core:core-ktx:1.15.0")
- implementation("androidx.core:core-splashscreen:1.0.1")
- implementation("androidx.activity:activity-compose:1.9.3")
- implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
- implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7")
- implementation("androidx.lifecycle:lifecycle-process:2.8.7")
- implementation("androidx.browser:browser:1.8.0")
-
- implementation(platform("com.google.firebase:firebase-bom:33.7.0"))
- implementation("com.google.firebase:firebase-messaging")
- implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.9.0")
-
- implementation("com.squareup.okhttp3:okhttp:4.12.0")
- implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
- implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
-}
diff --git a/app/app/google-services.json b/app/app/google-services.json
deleted file mode 100644
index 2eaa797..0000000
--- a/app/app/google-services.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "project_info": {
- "project_number": "724257369909",
- "project_id": "email-notifs-294de",
- "storage_bucket": "email-notifs-294de.firebasestorage.app"
- },
- "client": [
- {
- "client_info": {
- "mobilesdk_app_id": "1:724257369909:android:0cf5e52bafc7dad504a67c",
- "android_client_info": {
- "package_name": "gay.doughmination.mail"
- }
- },
- "oauth_client": [],
- "api_key": [
- {
- "current_key": "AIzaSyBoHevnGfBzztHtVN0QWQxkYUY1-Xjb2ao"
- }
- ],
- "services": {
- "appinvite_service": {
- "other_platform_oauth_client": []
- }
- }
- }
- ],
- "configuration_version": "1"
-}
\ No newline at end of file
diff --git a/app/app/src/main/AndroidManifest.xml b/app/app/src/main/AndroidManifest.xml
deleted file mode 100644
index 13aed03..0000000
--- a/app/app/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,65 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android">
-
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
-
- <!-- Custom Tabs for signing in: lets us find a browser that supports them. -->
- <queries>
- <intent>
- <action android:name="android.support.customtabs.action.CustomTabsService" />
- </intent>
- </queries>
-
- <application
- android:name=".InboxApp"
- android:allowBackup="false"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/Theme.Inbox">
-
- <activity
- android:name=".MainActivity"
- android:exported="true"
- android:launchMode="singleTask"
- android:theme="@style/Theme.Inbox.Starting"
- android:windowSoftInputMode="adjustResize">
-
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
-
- <!-- Where the server sends the browser tab after SSO sign-in. -->
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- <data android:scheme="gay.doughmination.mail" android:host="auth" />
- </intent-filter>
-
- <!-- Links to mail open in the app. Only these paths: claiming
- /auth would pull the sign-in redirect out of the browser tab. -->
- <intent-filter android:autoVerify="true">
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- <data android:scheme="https" android:host="mail.doughmination.gay" />
- <data android:pathPrefix="/inbox" />
- <data android:pathPrefix="/starred" />
- <data android:pathPrefix="/sent" />
- <data android:pathPrefix="/drafts" />
- <data android:pathPrefix="/bin" />
- </intent-filter>
- </activity>
-
- <!-- New-mail notifications from the Worker, through Firebase. -->
- <service
- android:name=".PushService"
- android:exported="false">
- <intent-filter>
- <action android:name="com.google.firebase.MESSAGING_EVENT" />
- </intent-filter>
- </service>
- </application>
-</manifest>
diff --git a/app/app/src/main/java/gay/doughmination/mail/InboxApp.kt b/app/app/src/main/java/gay/doughmination/mail/InboxApp.kt
deleted file mode 100644
index ebb4892..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/InboxApp.kt
+++ /dev/null
@@ -1,51 +0,0 @@
-package gay.doughmination.mail
-
-import android.app.Application
-import androidx.lifecycle.DefaultLifecycleObserver
-import androidx.lifecycle.LifecycleOwner
-import androidx.lifecycle.ProcessLifecycleOwner
-import gay.doughmination.mail.data.Api
-import gay.doughmination.mail.data.Auth
-import gay.doughmination.mail.data.Live
-import gay.doughmination.mail.data.TokenStore
-import kotlinx.coroutines.MainScope
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.StateFlow
-
-/** Holds the app-wide pieces; there's one of each per process. */
-class InboxApp : Application() {
- lateinit var tokens: TokenStore
- private set
- lateinit var api: Api
- private set
- lateinit var auth: Auth
- private set
- lateinit var live: Live
- private set
-
- private val _signedIn = MutableStateFlow(false)
- val signedIn: StateFlow<Boolean> = _signedIn
-
- override fun onCreate() {
- super.onCreate()
- tokens = TokenStore(this)
- api = Api(BuildConfig.INBOX_URL, tokens) { _signedIn.value = false }
- auth = Auth(api, tokens)
- live = Live(api, MainScope())
- _signedIn.value = tokens.token != null
-
- // The live socket only runs while the app is on screen and signed in.
- ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
- override fun onStart(owner: LifecycleOwner) {
- if (_signedIn.value) live.start()
- }
-
- override fun onStop(owner: LifecycleOwner) = live.stop()
- })
- }
-
- fun setSignedIn(value: Boolean) {
- _signedIn.value = value
- if (value) live.start() else live.stop()
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/MainActivity.kt b/app/app/src/main/java/gay/doughmination/mail/MainActivity.kt
deleted file mode 100644
index fcf001d..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/MainActivity.kt
+++ /dev/null
@@ -1,67 +0,0 @@
-package gay.doughmination.mail
-
-import android.content.Intent
-import android.os.Bundle
-import android.os.SystemClock
-import android.view.animation.AccelerateInterpolator
-import androidx.activity.ComponentActivity
-import androidx.activity.compose.setContent
-import androidx.activity.enableEdgeToEdge
-import androidx.activity.viewModels
-import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
-import gay.doughmination.mail.ui.AppRoot
-import gay.doughmination.mail.ui.InboxTheme
-import gay.doughmination.mail.ui.MailViewModel
-
-class MainActivity : ComponentActivity() {
- private val vm: MailViewModel by viewModels()
-
- override fun onCreate(savedInstanceState: Bundle?) {
- // The splash stays up while the inbox loads, so it opens already full,
- // and long enough for its opening to play even when mail is quick.
- // A slow connection gets the app (and its spinner) after a few seconds.
- val shown = SystemClock.uptimeMillis()
- installSplashScreen().apply {
- setKeepOnScreenCondition {
- val elapsed = SystemClock.uptimeMillis() - shown
- (!vm.ready || elapsed < SPLASH_MIN_MS) && elapsed < SPLASH_MAX_MS
- }
- // Then it lifts off the top, uncovering the inbox.
- setOnExitAnimationListener { splash ->
- val view = splash.view
- view.animate()
- .translationY(-view.height.toFloat())
- .setInterpolator(AccelerateInterpolator(1.5f))
- .setDuration(450)
- .withEndAction(splash::remove)
- .start()
- }
- }
- enableEdgeToEdge()
- super.onCreate(savedInstanceState)
- setContent { InboxTheme { AppRoot(vm) } }
- // A recreated activity (rotation) has already handled its launch intent.
- if (savedInstanceState == null) handle(intent)
- }
-
- override fun onNewIntent(intent: Intent) {
- super.onNewIntent(intent)
- handle(intent)
- }
-
- private fun handle(intent: Intent?) {
- val data = intent?.data ?: return
- when {
- // The end of sign-in: gay.doughmination.mail://auth?code=...
- data.scheme == "gay.doughmination.mail" && data.host == "auth" ->
- data.getQueryParameter("code")?.let(vm::finishLogin)
- // A link to the site, like /inbox/<thread id>.
- data.scheme == "https" && vm.signedIn -> data.path?.let(vm::openPath)
- }
- }
-
- private companion object {
- const val SPLASH_MIN_MS = 1500L
- const val SPLASH_MAX_MS = 4000L
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/Push.kt b/app/app/src/main/java/gay/doughmination/mail/Push.kt
deleted file mode 100644
index 5e5bb23..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/Push.kt
+++ /dev/null
@@ -1,102 +0,0 @@
-package gay.doughmination.mail
-
-import android.Manifest
-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.net.Uri
-import android.os.Build
-import android.util.Log
-import androidx.core.app.NotificationCompat
-import androidx.core.app.NotificationManagerCompat
-import androidx.core.content.ContextCompat
-import com.google.firebase.FirebaseApp
-import com.google.firebase.messaging.FirebaseMessaging
-import com.google.firebase.messaging.FirebaseMessagingService
-import com.google.firebase.messaging.RemoteMessage
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.SupervisorJob
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.tasks.await
-
-/**
- * New-mail notifications. When Resend's webhook delivers an email, the Worker
- * sends a data message through Firebase to every install's FCM token; this
- * turns it into a notification that opens the thread.
- */
-object Push {
- private const val CHANNEL = "mail"
- private const val TAG = "Push"
-
- /** False when the build has no google-services.json. */
- fun available(context: Context): Boolean = FirebaseApp.getApps(context).isNotEmpty()
-
- /** Tells the server where to reach this install. Called after sign-in. */
- suspend fun register(app: InboxApp) {
- if (!available(app)) return
- runCatching { app.api.registerFcm(FirebaseMessaging.getInstance().token.await()) }
- .onFailure { Log.w(TAG, "couldn't register for notifications", it) }
- }
-
- /** Before signing out: stop this install getting the account's mail. */
- suspend fun unregister(app: InboxApp) {
- if (!available(app)) return
- runCatching {
- val messaging = FirebaseMessaging.getInstance()
- app.api.unregisterFcm(messaging.token.await())
- // A fresh token next time, so nothing old can still point here.
- messaging.deleteToken().await()
- }.onFailure { Log.w(TAG, "couldn't unregister from notifications", it) }
- }
-
- fun show(context: Context, data: Map<String, String>) {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
- ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
- ) return
-
- val manager = context.getSystemService(NotificationManager::class.java)
- if (manager.getNotificationChannel(CHANNEL) == null) {
- manager.createNotificationChannel(NotificationChannel(CHANNEL, "New mail", NotificationManager.IMPORTANCE_HIGH))
- }
-
- val tag = data["tag"] ?: data.hashCode().toString()
- // Same URLs as the site's, which MainActivity already knows how to open.
- val open = Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.INBOX_URL + (data["url"] ?: "/inbox")), context, MainActivity::class.java)
- val tap = PendingIntent.getActivity(
- context,
- tag.hashCode(),
- open,
- PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
- )
- val notification = NotificationCompat.Builder(context, CHANNEL)
- .setSmallIcon(R.drawable.ic_notification)
- .setColor(0xFFEB459E.toInt())
- .setContentTitle(data["title"] ?: "New email")
- .setContentText(data["body"].orEmpty())
- .setStyle(NotificationCompat.BigTextStyle().bigText(data["body"].orEmpty()))
- .setCategory(NotificationCompat.CATEGORY_EMAIL)
- .setContentIntent(tap)
- .setAutoCancel(true)
- .build()
- NotificationManagerCompat.from(context).notify(tag, 0, notification)
- }
-}
-
-class PushService : FirebaseMessagingService() {
- private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
-
- override fun onMessageReceived(message: RemoteMessage) {
- if (message.data.isNotEmpty()) Push.show(this, message.data)
- }
-
- /** Firebase rotated this install's token; the server needs the new one. */
- override fun onNewToken(token: String) {
- val app = application as InboxApp
- if (!app.signedIn.value) return
- scope.launch { runCatching { app.api.registerFcm(token) } }
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/data/Api.kt b/app/app/src/main/java/gay/doughmination/mail/data/Api.kt
deleted file mode 100644
index 66fc25f..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/data/Api.kt
+++ /dev/null
@@ -1,181 +0,0 @@
-package gay.doughmination.mail.data
-
-import android.content.ContentResolver
-import android.net.Uri
-import android.provider.OpenableColumns
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-import kotlinx.serialization.Serializable
-import kotlinx.serialization.encodeToString
-import kotlinx.serialization.json.Json
-import kotlinx.serialization.json.JsonObject
-import kotlinx.serialization.json.contentOrNull
-import kotlinx.serialization.json.jsonPrimitive
-import okhttp3.HttpUrl
-import okhttp3.HttpUrl.Companion.toHttpUrl
-import okhttp3.MediaType
-import okhttp3.MediaType.Companion.toMediaType
-import okhttp3.MediaType.Companion.toMediaTypeOrNull
-import okhttp3.MultipartBody
-import okhttp3.OkHttpClient
-import okhttp3.Request
-import okhttp3.RequestBody
-import okhttp3.RequestBody.Companion.toRequestBody
-import okio.BufferedSink
-import okio.source
-import java.util.concurrent.TimeUnit
-
-/** The server said no; `message` is fit to show. `draftId` is set when a failed send left a draft. */
-class ApiException(message: String, val status: Int, val draftId: String? = null) : Exception(message)
-
-/** The session is gone (expired, signed out elsewhere, account removed). */
-class SignedOutException : Exception("Signed out")
-
-/** The Worker's /api and /auth endpoints, signed in with the bearer token. */
-class Api(val baseUrl: String, private val tokens: TokenStore, private val onSignedOut: () -> Unit) {
- val http: OkHttpClient = OkHttpClient.Builder()
- .connectTimeout(15, TimeUnit.SECONDS)
- .readTimeout(60, TimeUnit.SECONDS)
- .writeTimeout(120, TimeUnit.SECONDS)
- .build()
-
- val json = Json {
- ignoreUnknownKeys = true
- encodeDefaults = true
- // An enum value this build doesn't know (a newer swipe) takes the field's default.
- coerceInputValues = true
- }
-
- private val jsonType = "application/json".toMediaType()
-
- fun url(path: String): HttpUrl = "$baseUrl$path".toHttpUrl()
-
- /** Adds the session token; for requests made outside this class (the WebView, downloads, the socket). */
- fun authorize(builder: Request.Builder): Request.Builder =
- tokens.token?.let { builder.header("Authorization", "Bearer $it") } ?: builder
-
- private suspend fun send(request: Request): String = withContext(Dispatchers.IO) {
- if (tokens.token == null) throw SignedOutException()
- http.newCall(authorize(request.newBuilder()).build()).execute().use { res ->
- val body = res.body?.string().orEmpty()
- if (res.code == 401) {
- tokens.token = null
- onSignedOut()
- throw SignedOutException()
- }
- if (!res.isSuccessful) {
- val obj = runCatching { json.decodeFromString<JsonObject>(body) }.getOrNull()
- throw ApiException(
- obj?.get("error")?.jsonPrimitive?.contentOrNull ?: "Request failed (${res.code})",
- res.code,
- obj?.get("draftId")?.jsonPrimitive?.contentOrNull,
- )
- }
- body
- }
- }
-
- private suspend inline fun <reified T> get(path: String): T =
- json.decodeFromString(send(Request.Builder().url(url(path)).build()))
-
- private suspend inline fun <reified T, reified B> call(method: String, path: String, body: B): T {
- val payload = json.encodeToString(body).toRequestBody(jsonType)
- return json.decodeFromString(send(Request.Builder().url(url(path)).method(method, payload).build()))
- }
-
- private suspend inline fun <reified T> call(method: String, path: String): T {
- val payload = if (method == "DELETE") null else "{}".toRequestBody(jsonType)
- return json.decodeFromString(send(Request.Builder().url(url(path)).method(method, payload).build()))
- }
-
- @Serializable data class Unread(val unread: Map<String, Int>)
- @Serializable data class Count(val count: Int)
- @Serializable data class Id(val id: String)
- @Serializable data class Sent(val id: String, val threadId: String)
- @Serializable private data class Read(val read: Boolean)
- @Serializable private data class Star(val starred: Boolean)
- @Serializable private data class Name(val name: String)
- @Serializable data class PushResult(val sent: Int, val pruned: Int = 0)
- @Serializable private data class FcmToken(val token: String)
- @Serializable private data class CodeSwap(val code: String, val verifier: String)
- @Serializable private data class Token(val token: String)
-
- suspend fun me(): Me = get("/api/me")
- suspend fun unread(): Map<String, Int> = get<Unread>("/api/unread").unread
- suspend fun setName(name: String) { call<JsonObject, Name>("PATCH", "/api/me", Name(name)) }
- suspend fun setPreferences(prefs: Preferences): Preferences = call("PATCH", "/api/me/preferences", prefs)
-
- suspend fun threads(folder: ListFolder, mailbox: String?, cursor: String?): Page<ThreadSummary> {
- val q = url("/api/threads").newBuilder().addQueryParameter("folder", folder.path)
- mailbox?.let { q.addQueryParameter("mailbox", it) }
- cursor?.let { q.addQueryParameter("cursor", it) }
- return json.decodeFromString(send(Request.Builder().url(q.build()).build()))
- }
-
- /** With `bin`, only the part of the thread that's in the Bin. */
- suspend fun thread(id: String, bin: Boolean): MailThread = get("/api/threads/$id${if (bin) "?bin=1" else ""}")
- suspend fun message(id: String): Message = get("/api/messages/$id")
- suspend fun markThread(id: String, read: Boolean): Map<String, Int> =
- call<Unread, Read>("POST", "/api/threads/$id/read", Read(read)).unread
- suspend fun starThread(id: String, starred: Boolean) { call<JsonObject, Star>("POST", "/api/threads/$id/star", Star(starred)) }
- /** Moves it to the Bin; `forever` deletes what of it is already in the Bin. */
- suspend fun deleteThread(id: String, forever: Boolean = false): Int =
- call<Count>("DELETE", "/api/threads/$id${if (forever) "?forever=1" else ""}").count
- suspend fun restoreThread(id: String): Int = call<Count>("POST", "/api/threads/$id/restore").count
- suspend fun emptyBin(): Int = call<Count>("DELETE", "/api/bin").count
- /** Moves it to the Bin; `forever` deletes it outright, wherever it is. */
- suspend fun deleteMessage(id: String, forever: Boolean = false): Int =
- call<Count>("DELETE", "/api/messages/$id${if (forever) "?forever=1" else ""}").count
- suspend fun restoreMessage(id: String): Int = call<Count>("POST", "/api/messages/$id/restore").count
-
- suspend fun createDraft(input: SendRequest): String = call<Id, SendRequest>("POST", "/api/drafts", input).id
- suspend fun updateDraft(id: String, input: SendRequest): String = call<Id, SendRequest>("PUT", "/api/drafts/$id", input).id
- suspend fun send(input: SendRequest): Sent = call("POST", "/api/send", input)
-
- suspend fun registerFcm(token: String) { call<JsonObject, FcmToken>("POST", "/api/push/fcm", FcmToken(token)) }
- suspend fun unregisterFcm(token: String) { call<JsonObject, FcmToken>("POST", "/api/push/fcm/unregister", FcmToken(token)) }
- /** Sends a test notification to every device; returns how many it reached. */
- suspend fun pushTest(): Int = call<PushResult>("POST", "/api/push/test").sent
-
- fun attachmentUrl(id: String, inline: Boolean = false): String =
- "$baseUrl/api/attachments/$id${if (inline) "?inline=1" else ""}"
-
- /** Streams a picked file up as an unclaimed attachment. */
- suspend fun upload(resolver: ContentResolver, uri: Uri): AttachmentInfo {
- var name = "attachment"
- var size = -1L
- resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
- if (c.moveToFirst()) {
- c.getString(0)?.let { name = it }
- if (!c.isNull(1)) size = c.getLong(1)
- }
- }
- val type = resolver.getType(uri)?.toMediaTypeOrNull() ?: "application/octet-stream".toMediaType()
- val file = object : RequestBody() {
- override fun contentType(): MediaType = type
- override fun contentLength(): Long = size
- override fun writeTo(sink: BufferedSink) {
- resolver.openInputStream(uri)?.source()?.use { sink.writeAll(it) }
- ?: throw java.io.IOException("Couldn't read $name")
- }
- }
- val form = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", name, file).build()
- return json.decodeFromString(send(Request.Builder().url(url("/api/uploads")).post(form).build()))
- }
-
- /** Ends the session on the server. The token is dropped locally whatever happens. */
- suspend fun logout() {
- runCatching { call<JsonObject>("POST", "/auth/logout") }
- tokens.token = null
- }
-
- /** Swaps the one-time code from the sign-in redirect for a session token. */
- suspend fun exchangeCode(code: String, verifier: String): String = withContext(Dispatchers.IO) {
- val payload = json.encodeToString(CodeSwap(code, verifier)).toRequestBody(jsonType)
- http.newCall(Request.Builder().url(url("/auth/app/token")).post(payload).build()).execute().use { res ->
- val body = res.body?.string().orEmpty()
- if (!res.isSuccessful) throw ApiException("That sign-in didn't work. Try again.", res.code)
- json.decodeFromString<Token>(body).token
- }
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/data/Auth.kt b/app/app/src/main/java/gay/doughmination/mail/data/Auth.kt
deleted file mode 100644
index cd616a2..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/data/Auth.kt
+++ /dev/null
@@ -1,40 +0,0 @@
-package gay.doughmination.mail.data
-
-import android.content.Context
-import android.net.Uri
-import android.util.Base64
-import androidx.browser.customtabs.CustomTabsIntent
-import java.security.MessageDigest
-import java.security.SecureRandom
-
-/**
- * Sign-in goes through the server's own SSO flow in a browser tab:
- *
- * 1. open /auth/login?app=<challenge>, keeping the PKCE verifier here;
- * 2. the server, once the SSO is happy, redirects to
- * gay.doughmination.mail://auth?code=<one-time code>;
- * 3. MainActivity gets that and [finish] swaps code + verifier for a token.
- *
- * Only this app holds the verifier, so another app that grabs the redirect
- * can't use the code.
- */
-class Auth(private val api: Api, private val tokens: TokenStore) {
- fun start(context: Context) {
- val verifier = b64url(ByteArray(32).also { SecureRandom().nextBytes(it) })
- val challenge = b64url(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray()))
- tokens.pendingVerifier = verifier
- CustomTabsIntent.Builder()
- .setShowTitle(true)
- .build()
- .launchUrl(context, Uri.parse("${api.baseUrl}/auth/login?app=$challenge"))
- }
-
- suspend fun finish(code: String) {
- val verifier = tokens.pendingVerifier ?: throw ApiException("That sign-in has expired. Try again.", 400)
- tokens.pendingVerifier = null
- tokens.token = api.exchangeCode(code, verifier)
- }
-
- private fun b64url(bytes: ByteArray): String =
- Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/data/Live.kt b/app/app/src/main/java/gay/doughmination/mail/data/Live.kt
deleted file mode 100644
index a4eb6e0..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/data/Live.kt
+++ /dev/null
@@ -1,95 +0,0 @@
-package gay.doughmination.mail.data
-
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.flow.MutableSharedFlow
-import kotlinx.coroutines.flow.SharedFlow
-import kotlinx.coroutines.launch
-import kotlinx.serialization.Serializable
-import okhttp3.Request
-import okhttp3.Response
-import okhttp3.WebSocket
-import okhttp3.WebSocketListener
-
-/**
- * Keeps a WebSocket to /api/live open while the app is in the foreground and
- * emits when new mail lands. Reconnects with backoff; a reconnect emits too,
- * so anything missed while it was down gets picked up.
- */
-class Live(private val api: Api, private val scope: CoroutineScope) {
- /** The thread new mail landed in, or null for "something may have changed". */
- private val _events = MutableSharedFlow<String?>(extraBufferCapacity = 16)
- val events: SharedFlow<String?> = _events
-
- private var socket: WebSocket? = null
- private var pinger: Job? = null
- private var retry: Job? = null
- private var running = false
- private var backoffMs = 1_000L
- private var dropped = false
-
- @Serializable
- private data class Event(val type: String, val threadId: String? = null)
-
- fun start() {
- if (running) return
- running = true
- connect()
- }
-
- fun stop() {
- running = false
- retry?.cancel()
- pinger?.cancel()
- socket?.close(1000, null)
- socket = null
- dropped = true
- }
-
- private fun connect() {
- if (!running || socket != null) return
- val url = api.baseUrl.replaceFirst("http", "ws") + "/api/live"
- val request = api.authorize(Request.Builder().url(url)).build()
- socket = api.http.newWebSocket(request, object : WebSocketListener() {
- override fun onOpen(webSocket: WebSocket, response: Response) {
- scope.launch {
- if (socket !== webSocket) return@launch
- backoffMs = 1_000L
- // Cloudflare drops idle sockets after ~100s; the server answers without waking.
- pinger = scope.launch {
- while (true) {
- delay(30_000)
- webSocket.send("ping")
- }
- }
- if (dropped) _events.tryEmit(null)
- }
- }
-
- override fun onMessage(webSocket: WebSocket, text: String) {
- if (text == "pong") return
- val event = runCatching { api.json.decodeFromString<Event>(text) }.getOrNull() ?: return
- if (event.type == "mail") _events.tryEmit(event.threadId)
- }
-
- override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = lost(webSocket)
- override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = lost(webSocket)
- })
- }
-
- private fun lost(webSocket: WebSocket) {
- scope.launch {
- if (socket !== webSocket) return@launch
- pinger?.cancel()
- socket = null
- dropped = true
- if (!running) return@launch
- retry = scope.launch {
- delay(backoffMs)
- backoffMs = (backoffMs * 2).coerceAtMost(60_000L)
- connect()
- }
- }
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/data/Models.kt b/app/app/src/main/java/gay/doughmination/mail/data/Models.kt
deleted file mode 100644
index e29e01d..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/data/Models.kt
+++ /dev/null
@@ -1,126 +0,0 @@
-package gay.doughmination.mail.data
-
-import kotlinx.serialization.SerialName
-import kotlinx.serialization.Serializable
-
-// Mirrors email/src/shared/types.ts. Keep the two in step.
-
-@Serializable
-data class Me(
- val username: String,
- /** Display name put on outgoing mail; null sends from the bare address. */
- val name: String? = null,
- val isAdmin: Boolean,
- /** Every address this user can send from. */
- val addresses: List<String>,
- val domains: List<String>,
- /** The account's picture on the SSO (https), whether or not it's in use. */
- val picture: String? = null,
- val usePicture: Boolean = true,
- val swipeLeft: SwipeAction = SwipeAction.Bin,
- val swipeRight: SwipeAction = SwipeAction.Read,
-) {
- val preferences get() = Preferences(usePicture, swipeLeft, swipeRight)
-
- /** The picture to show for the account, or null for the default (an initial). */
- val shownPicture get() = picture?.takeIf { usePicture }
-}
-
-/** What swiping a row does. An unknown value (a newer server) reads as None. */
-@Serializable
-enum class SwipeAction(val label: String) {
- @SerialName("none") None("Nothing"),
- @SerialName("read") Read("Mark as read or unread"),
- @SerialName("star") Star("Star or unstar"),
- @SerialName("bin") Bin("Move to Bin"),
-}
-
-/** Settings that follow the user between the web and the app. */
-@Serializable
-data class Preferences(val usePicture: Boolean, val swipeLeft: SwipeAction, val swipeRight: SwipeAction)
-
-@Serializable
-data class Page<T>(val items: List<T>, val nextCursor: String? = null)
-
-@Serializable
-data class ThreadSummary(
- val id: String,
- val latestId: String,
- val mailbox: String,
- val subject: String,
- val from: String,
- val to: List<String>,
- val snippet: String,
- val lastAt: Long,
- val count: Int,
- val unread: Int,
- val hasAttachments: Boolean,
- val starred: Boolean,
-)
-
-@Serializable
-data class AttachmentInfo(
- val id: String,
- val filename: String,
- val contentType: String,
- val size: Long,
- val contentId: String? = null,
-)
-
-@Serializable
-data class Message(
- val id: String,
- val threadId: String,
- /** "inbox", "sent" or "drafts". */
- val folder: String,
- val mailbox: String,
- val from: String,
- val to: List<String>,
- val cc: List<String>,
- val bcc: List<String>,
- val subject: String,
- val snippet: String,
- /** Email HTML. Only ever render it in EmailView. */
- val html: String? = null,
- val text: String? = null,
- val sentAt: Long,
- val read: Boolean,
- val attachments: List<AttachmentInfo>,
-)
-
-@Serializable
-data class MailThread(
- val id: String,
- val subject: String,
- val starred: Boolean,
- val messages: List<Message>,
-)
-
-@Serializable
-data class SendRequest(
- val from: String,
- val to: List<String>,
- val cc: List<String>,
- val bcc: List<String>,
- val subject: String,
- /** Plain text; the server renders the HTML part from it. */
- val text: String,
- val attachmentIds: List<String>,
- /** Message being replied to; threads the new one onto it. */
- val replyTo: String? = null,
- /** Only for /send: the draft to update and send. */
- val draftId: String? = null,
-)
-
-/** What the thread list can show: a folder, Starred, or the Bin. */
-enum class ListFolder(val path: String, val label: String) {
- Inbox("inbox", "Inbox"),
- Starred("starred", "Starred"),
- Sent("sent", "Sent"),
- Drafts("drafts", "Drafts"),
- Bin("bin", "Bin");
-
- companion object {
- fun fromPath(path: String?): ListFolder? = entries.find { it.path == path }
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/data/TokenStore.kt b/app/app/src/main/java/gay/doughmination/mail/data/TokenStore.kt
deleted file mode 100644
index 8f31fc2..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/data/TokenStore.kt
+++ /dev/null
@@ -1,74 +0,0 @@
-package gay.doughmination.mail.data
-
-import android.content.Context
-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
-
-/**
- * Holds the session token, encrypted with a key that never leaves the
- * Android Keystore, so a copy of the app's files alone doesn't sign anyone in.
- * Also keeps the PKCE verifier of a sign-in in progress, which has to survive
- * the app being killed while the browser tab is open.
- */
-class TokenStore(context: Context) {
- private val prefs = context.getSharedPreferences("auth", Context.MODE_PRIVATE)
-
- @Volatile
- private var cached: String? = null
-
- var token: String?
- get() = cached ?: prefs.getString(KEY_TOKEN, null)?.let(::decrypt)?.also { cached = it }
- set(value) {
- cached = value
- prefs.edit().apply {
- if (value == null) remove(KEY_TOKEN) else putString(KEY_TOKEN, encrypt(value))
- }.apply()
- }
-
- var pendingVerifier: String?
- get() = prefs.getString(KEY_VERIFIER, null)
- set(value) = prefs.edit().apply {
- if (value == null) remove(KEY_VERIFIER) else putString(KEY_VERIFIER, value)
- }.apply()
-
- private fun key(): SecretKey {
- val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
- (store.getKey(ALIAS, null) as SecretKey?)?.let { return it }
- val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
- generator.init(
- KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
- .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
- .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
- .build(),
- )
- return generator.generateKey()
- }
-
- private fun encrypt(plain: String): String {
- val cipher = Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, key()) }
- val sealed = cipher.iv + cipher.doFinal(plain.toByteArray())
- return Base64.encodeToString(sealed, Base64.NO_WRAP)
- }
-
- /** Null when it can't be read (the key was wiped, say); that just means signed out. */
- private fun decrypt(stored: String): String? = runCatching {
- val sealed = Base64.decode(stored, Base64.NO_WRAP)
- val cipher = Cipher.getInstance(TRANSFORM)
- cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, sealed, 0, IV_BYTES))
- String(cipher.doFinal(sealed, IV_BYTES, sealed.size - IV_BYTES))
- }.getOrNull()
-
- private companion object {
- const val ALIAS = "inbox-session"
- const val TRANSFORM = "AES/GCM/NoPadding"
- const val IV_BYTES = 12
- const val KEY_TOKEN = "token"
- const val KEY_VERIFIER = "verifier"
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/AccountPicture.kt b/app/app/src/main/java/gay/doughmination/mail/ui/AccountPicture.kt
deleted file mode 100644
index 120c0d3..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/AccountPicture.kt
+++ /dev/null
@@ -1,72 +0,0 @@
-package gay.doughmination.mail.ui
-
-import android.graphics.BitmapFactory
-import androidx.compose.foundation.Image
-import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.shape.CircleShape
-import androidx.compose.material3.Text
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.produceState
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.draw.clip
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.graphics.ImageBitmap
-import androidx.compose.ui.graphics.asImageBitmap
-import androidx.compose.ui.layout.ContentScale
-import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.unit.Dp
-import androidx.compose.ui.unit.sp
-import gay.doughmination.mail.InboxApp
-import gay.doughmination.mail.data.Me
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-import okhttp3.OkHttpClient
-import okhttp3.Request
-import java.util.concurrent.ConcurrentHashMap
-
-/**
- * The signed-in account's picture: the SSO's, when there is one and Settings
- * says to use it, or the default, their initial on the accent colour. Also the
- * default while the picture loads, or if it can't be loaded. Same as the web.
- */
-@Composable
-fun AccountPicture(me: Me?, size: Dp) {
- val url = me?.shownPicture
- val http = (LocalContext.current.applicationContext as InboxApp).api.http
- val picture by produceState(url?.let { loaded[it] }, url) {
- value = url?.let { loadPicture(http, it) }
- }
- val shape = Modifier.size(size).clip(CircleShape)
- picture?.let {
- Image(it, null, shape, contentScale = ContentScale.Crop)
- return
- }
- val initial = (me?.name?.ifBlank { null } ?: me?.username ?: "?").firstOrNull { it.isLetterOrDigit() }?.uppercaseChar() ?: '?'
- Box(shape.background(Accent), contentAlignment = Alignment.Center) {
- Text(initial.toString(), color = Color.White, fontSize = (size.value * 0.42f).sp, fontWeight = FontWeight.SemiBold)
- }
-}
-
-/** Pictures already fetched this run, so the drawer doesn't flash its initial each time. */
-private val loaded = ConcurrentHashMap<String, ImageBitmap>()
-
-/** Fetches a picture without the session token (it's the SSO's, not ours), scaled down to avatar size. */
-private suspend fun loadPicture(http: OkHttpClient, url: String): ImageBitmap? = loaded[url] ?: withContext(Dispatchers.IO) {
- runCatching {
- http.newCall(Request.Builder().url(url).build()).execute().use { res ->
- if (!res.isSuccessful) return@use null
- val bytes = res.body?.bytes() ?: return@use null
- val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
- BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
- var sample = 1
- while (minOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= 256) sample *= 2
- BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
- ?.asImageBitmap()
- }
- }.getOrNull()?.also { loaded[url] = it }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt b/app/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt
deleted file mode 100644
index 2567ac3..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/AppRoot.kt
+++ /dev/null
@@ -1,132 +0,0 @@
-package gay.doughmination.mail.ui
-
-import android.Manifest
-import android.content.pm.PackageManager
-import android.os.Build
-import androidx.activity.compose.BackHandler
-import androidx.activity.compose.rememberLauncherForActivityResult
-import androidx.activity.result.contract.ActivityResultContracts
-import androidx.core.content.ContextCompat
-import gay.doughmination.mail.Push
-import androidx.compose.animation.AnimatedContent
-import androidx.compose.animation.fadeIn
-import androidx.compose.animation.fadeOut
-import androidx.compose.animation.togetherWith
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.fillMaxSize
-import androidx.compose.foundation.layout.height
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.size
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.outlined.Email
-import androidx.compose.material3.Button
-import androidx.compose.material3.CircularProgressIndicator
-import androidx.compose.material3.Icon
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.SnackbarDuration
-import androidx.compose.material3.SnackbarHost
-import androidx.compose.material3.SnackbarHostState
-import androidx.compose.material3.SnackbarResult
-import androidx.compose.material3.Text
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.CompositionLocalProvider
-import androidx.compose.runtime.LaunchedEffect
-import androidx.compose.runtime.remember
-import androidx.compose.runtime.staticCompositionLocalOf
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.text.style.TextAlign
-import androidx.compose.ui.unit.dp
-
-/** One snackbar host for every screen, so messages survive moving between them. */
-val LocalSnackbar = staticCompositionLocalOf { SnackbarHostState() }
-
-@Composable
-fun AppRoot(vm: MailViewModel) {
- val snackbar = remember { SnackbarHostState() }
- LaunchedEffect(Unit) {
- vm.snackbar.collect { s ->
- val result = snackbar.showSnackbar(
- s.text,
- actionLabel = s.action,
- withDismissAction = s.action == null,
- duration = SnackbarDuration.Short,
- )
- if (result == SnackbarResult.ActionPerformed) s.run?.invoke()
- }
- }
-
- CompositionLocalProvider(LocalSnackbar provides snackbar) {
- Box(Modifier.fillMaxSize()) {
- Backdrop()
- if (!vm.signedIn) {
- LoginScreen(vm)
- return@Box
- }
- AskForNotifications()
- BackHandler(enabled = vm.stack.size > 1) { vm.back() }
- AnimatedContent(
- targetState = vm.screen,
- transitionSpec = { fadeIn() togetherWith fadeOut() },
- label = "screen",
- ) { screen ->
- when (screen) {
- Screen.List -> ThreadListScreen(vm)
- is Screen.Thread -> ThreadScreen(vm, screen)
- Screen.Compose -> ComposeScreen(vm)
- Screen.Settings -> SettingsScreen(vm)
- }
- }
- }
- }
-}
-
-/** Android 13+ needs permission before any notification shows; asked once signed in. */
-@Composable
-private fun AskForNotifications() {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
- val context = LocalContext.current
- if (!Push.available(context)) return
- val ask = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {}
- LaunchedEffect(Unit) {
- val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
- PackageManager.PERMISSION_GRANTED
- if (!granted) ask.launch(Manifest.permission.POST_NOTIFICATIONS)
- }
-}
-
-@Composable
-private fun LoginScreen(vm: MailViewModel) {
- val context = LocalContext.current
- Column(
- Modifier.fillMaxSize().padding(32.dp),
- verticalArrangement = Arrangement.Center,
- horizontalAlignment = Alignment.CenterHorizontally,
- ) {
- Icon(Icons.Outlined.Email, null, Modifier.size(72.dp), tint = Accent)
- Spacer(Modifier.height(16.dp))
- Text("Inbox", style = MaterialTheme.typography.headlineMedium)
- Spacer(Modifier.height(8.dp))
- Text(
- "Sign in with your Doughmination account.",
- style = MaterialTheme.typography.bodyMedium,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- textAlign = TextAlign.Center,
- )
- Spacer(Modifier.height(32.dp))
- if (vm.signingIn) {
- CircularProgressIndicator()
- } else {
- Button(onClick = { vm.startLogin(context) }) { Text("Sign in") }
- }
- vm.loginError?.let {
- Spacer(Modifier.height(16.dp))
- Text(it, color = MaterialTheme.colorScheme.error, textAlign = TextAlign.Center)
- }
- }
- SnackbarHost(LocalSnackbar.current)
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/ComposeScreen.kt b/app/app/src/main/java/gay/doughmination/mail/ui/ComposeScreen.kt
deleted file mode 100644
index c43db75..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/ComposeScreen.kt
+++ /dev/null
@@ -1,182 +0,0 @@
-package gay.doughmination.mail.ui
-
-import androidx.activity.compose.rememberLauncherForActivityResult
-import androidx.activity.result.contract.ActivityResultContracts
-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.heightIn
-import androidx.compose.foundation.layout.imePadding
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.size
-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.outlined.Send
-import androidx.compose.material.icons.outlined.AttachFile
-import androidx.compose.material.icons.outlined.Close
-import androidx.compose.material.icons.outlined.MoreVert
-import androidx.compose.material3.CircularProgressIndicator
-import androidx.compose.material3.DropdownMenu
-import androidx.compose.material3.DropdownMenuItem
-import androidx.compose.material3.ExperimentalMaterial3Api
-import androidx.compose.material3.ExposedDropdownMenuBox
-import androidx.compose.material3.ExposedDropdownMenuDefaults
-import androidx.compose.material3.HorizontalDivider
-import androidx.compose.material3.Icon
-import androidx.compose.material3.IconButton
-import androidx.compose.material3.InputChip
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.MenuAnchorType
-import androidx.compose.material3.Scaffold
-import androidx.compose.material3.SnackbarHost
-import androidx.compose.material3.Text
-import androidx.compose.material3.TextButton
-import androidx.compose.material3.TextField
-import androidx.compose.material3.TextFieldDefaults
-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.setValue
-import androidx.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.text.input.ImeAction
-import androidx.compose.ui.text.input.KeyboardCapitalization
-import androidx.compose.ui.text.input.KeyboardType
-import androidx.compose.ui.unit.dp
-
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable
-fun ComposeScreen(vm: MailViewModel) {
- val d = vm.draft ?: return
- val context = LocalContext.current
- val pick = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { uris ->
- if (uris.isNotEmpty()) vm.attach(context, uris)
- }
- var showCopies by remember { mutableStateOf(d.cc.isNotBlank() || d.bcc.isNotBlank()) }
- var menu by remember { mutableStateOf(false) }
- val busy = vm.sending || vm.uploading > 0
-
- Scaffold(
- topBar = {
- TopAppBar(
- title = { Text(d.title) },
- navigationIcon = {
- IconButton(onClick = vm::closeAndSave) { Icon(Icons.Outlined.Close, "Close and save") }
- },
- actions = {
- IconButton(onClick = { pick.launch("*/*") }) { Icon(Icons.Outlined.AttachFile, "Attach") }
- if (busy) {
- CircularProgressIndicator(Modifier.padding(12.dp).size(24.dp))
- } else {
- IconButton(onClick = vm::send) { Icon(Icons.AutoMirrored.Outlined.Send, "Send", tint = Accent) }
- }
- IconButton(onClick = { menu = true }) { Icon(Icons.Outlined.MoreVert, "More") }
- DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
- DropdownMenuItem(text = { Text("Save draft") }, onClick = { menu = false; vm.closeAndSave() })
- DropdownMenuItem(
- text = { Text(if (d.draftId != null) "Delete draft" else "Discard", color = Danger) },
- onClick = { menu = false; vm.discard() },
- )
- }
- },
- )
- },
- snackbarHost = { SnackbarHost(LocalSnackbar.current) },
- ) { padding ->
- Column(
- Modifier.padding(padding).imePadding().fillMaxSize().verticalScroll(rememberScrollState()),
- ) {
- FromPicker(vm.me?.addresses.orEmpty(), d.from) { vm.draft = d.copy(from = it) }
- HorizontalDivider()
- Row(verticalAlignment = Alignment.CenterVertically) {
- Field("To", d.to, Modifier.weight(1f), KeyboardType.Email) { vm.draft = d.copy(to = it) }
- if (!showCopies) TextButton(onClick = { showCopies = true }) { Text("Cc/Bcc") }
- }
- HorizontalDivider()
- if (showCopies) {
- Field("Cc", d.cc, Modifier.fillMaxWidth(), KeyboardType.Email) { vm.draft = d.copy(cc = it) }
- HorizontalDivider()
- Field("Bcc", d.bcc, Modifier.fillMaxWidth(), KeyboardType.Email) { vm.draft = d.copy(bcc = it) }
- HorizontalDivider()
- }
- Field("Subject", d.subject, Modifier.fillMaxWidth(), KeyboardType.Text) { vm.draft = d.copy(subject = it) }
- HorizontalDivider()
-
- if (d.attachments.isNotEmpty() || vm.uploading > 0) {
- Column(Modifier.padding(horizontal = 12.dp, vertical = 6.dp)) {
- for (a in d.attachments) {
- InputChip(
- selected = false,
- onClick = { vm.removeAttachment(a) },
- label = { Text("${a.filename} · ${fmtSize(a.size)}", maxLines = 1) },
- trailingIcon = { Icon(Icons.Outlined.Close, "Remove", Modifier.size(18.dp)) },
- )
- }
- if (vm.uploading > 0) {
- Text("Uploading ${vm.uploading}…", style = MaterialTheme.typography.labelMedium, color = Muted)
- }
- }
- HorizontalDivider()
- }
-
- TextField(
- value = d.text,
- onValueChange = { vm.draft = d.copy(text = it) },
- placeholder = { Text("Write your message") },
- modifier = Modifier.fillMaxWidth().heightIn(min = 280.dp),
- colors = plainField(),
- keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
- )
- }
- }
-}
-
-@Composable
-private fun plainField() = TextFieldDefaults.colors(
- focusedContainerColor = Color.Transparent,
- unfocusedContainerColor = Color.Transparent,
- focusedIndicatorColor = Color.Transparent,
- unfocusedIndicatorColor = Color.Transparent,
-)
-
-@Composable
-private fun Field(label: String, value: String, modifier: Modifier, type: KeyboardType, onChange: (String) -> Unit) {
- TextField(
- value = value,
- onValueChange = onChange,
- modifier = modifier,
- prefix = { Text("$label ", color = Muted) },
- singleLine = type == KeyboardType.Text,
- colors = plainField(),
- keyboardOptions = KeyboardOptions(keyboardType = type, imeAction = ImeAction.Next),
- )
-}
-
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable
-private fun FromPicker(addresses: List<String>, selected: String, onPick: (String) -> Unit) {
- var open by remember { mutableStateOf(false) }
- ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it && addresses.size > 1 }) {
- TextField(
- value = selected.ifEmpty { "No address to send from" },
- onValueChange = {},
- readOnly = true,
- prefix = { Text("From ", color = Muted) },
- trailingIcon = { if (addresses.size > 1) ExposedDropdownMenuDefaults.TrailingIcon(open) },
- colors = plainField(),
- modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable),
- )
- ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) {
- for (addr in addresses) {
- DropdownMenuItem(text = { Text(addr) }, onClick = { open = false; onPick(addr) })
- }
- }
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/EmailView.kt b/app/app/src/main/java/gay/doughmination/mail/ui/EmailView.kt
deleted file mode 100644
index 4467e2d..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/EmailView.kt
+++ /dev/null
@@ -1,119 +0,0 @@
-package gay.doughmination.mail.ui
-
-import android.annotation.SuppressLint
-import android.content.Intent
-import android.graphics.Color
-import android.view.ViewGroup
-import android.webkit.WebResourceRequest
-import android.webkit.WebResourceResponse
-import android.webkit.WebView
-import android.webkit.WebViewClient
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.remember
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.viewinterop.AndroidView
-import gay.doughmination.mail.data.Api
-import gay.doughmination.mail.data.AttachmentInfo
-import okhttp3.Request
-import java.io.ByteArrayInputStream
-
-private const val BASE_STYLE =
- ":root{color-scheme:light}body{margin:0;padding:12px;background:#fff;color:#111;" +
- "font:15px/1.5 sans-serif;overflow-wrap:anywhere}" +
- "img{max-width:100%;height:auto}pre{white-space:pre-wrap}table{max-width:100%}"
-
-private val REMOTE = Regex("""(?:src|background|href)\s*=\s*["']?\s*https?:|url\(\s*["']?\s*https?:|@import""", RegexOption.IGNORE_CASE)
-
-/** Whether an email pulls anything from the internet (mostly tracking pixels). */
-fun hasRemoteContent(html: String): Boolean = REMOTE.containsMatchIn(html)
-
-/**
- * The only place email HTML is ever rendered, like EmailFrame on the web:
- *
- * - no JavaScript, no file or content access;
- * - links never load in here, they open in the browser;
- * - remote images, fonts and stylesheets stay blocked until `showRemote`,
- * by both a CSP and refusing the requests outright;
- * - cid: images load from /api/attachments with the session token.
- */
-@SuppressLint("SetJavaScriptEnabled")
-@Composable
-fun EmailView(api: Api, html: String, attachments: List<AttachmentInfo>, showRemote: Boolean, modifier: Modifier = Modifier) {
- val body = remember(html, attachments) {
- val byCid = attachments.filter { it.contentId != null }.associate { it.contentId!!.lowercase() to it.id }
- Regex("""cid:([^"'\s>)]+)""", RegexOption.IGNORE_CASE).replace(html) { m ->
- val id = byCid[m.groupValues[1].removePrefix("<").removeSuffix(">").lowercase()]
- if (id != null) api.attachmentUrl(id, inline = true) else m.value
- }
- }
- val document = remember(body, showRemote) {
- val remote = if (showRemote) " https:" else ""
- val csp = "default-src 'none'; img-src ${api.baseUrl} data:$remote; style-src 'unsafe-inline'$remote; " +
- "font-src data:$remote; media-src 'none'; form-action 'none'; base-uri 'none'"
- "<!doctype html><html><head><meta charset=\"utf-8\">" +
- "<meta http-equiv=\"Content-Security-Policy\" content=\"$csp\">" +
- "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" +
- "<meta name=\"referrer\" content=\"no-referrer\"><style>$BASE_STYLE</style></head>" +
- "<body>$body</body></html>"
- }
-
- AndroidView(
- modifier = modifier,
- factory = { context ->
- WebView(context).apply {
- layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
- setBackgroundColor(Color.WHITE)
- isVerticalScrollBarEnabled = false
- settings.apply {
- javaScriptEnabled = false
- allowFileAccess = false
- allowContentAccess = false
- domStorageEnabled = false
- setGeolocationEnabled(false)
- builtInZoomControls = true
- displayZoomControls = false
- }
- }
- },
- update = { view ->
- view.webViewClient = MailClient(api, showRemote)
- if (view.tag != document) {
- view.tag = document
- view.loadDataWithBaseURL(api.baseUrl + "/", document, "text/html", "utf-8", null)
- }
- },
- onRelease = { it.destroy() },
- )
-}
-
-private class MailClient(private val api: Api, private val showRemote: Boolean) : WebViewClient() {
- private val attachmentPrefix = api.baseUrl + "/api/attachments/"
-
- override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
- val scheme = request.url.scheme?.lowercase()
- if (scheme == "http" || scheme == "https" || scheme == "mailto") {
- runCatching {
- view.context.startActivity(Intent(Intent.ACTION_VIEW, request.url).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
- }
- }
- // Nothing ever navigates inside the email itself.
- return true
- }
-
- override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
- val url = request.url.toString()
- if (url.startsWith(attachmentPrefix)) {
- return runCatching {
- val res = api.http.newCall(api.authorize(Request.Builder().url(url)).build()).execute()
- val type = res.header("Content-Type")?.substringBefore(";") ?: "application/octet-stream"
- WebResourceResponse(type, null, res.body?.byteStream())
- }.getOrElse { blocked() }
- }
- val scheme = request.url.scheme?.lowercase()
- if (scheme == "data") return null
- if (!showRemote || scheme != "https") return blocked()
- return null
- }
-
- private fun blocked() = WebResourceResponse("text/plain", "utf-8", 403, "Blocked", emptyMap(), ByteArrayInputStream(ByteArray(0)))
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/Format.kt b/app/app/src/main/java/gay/doughmination/mail/ui/Format.kt
deleted file mode 100644
index 01a43e2..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/Format.kt
+++ /dev/null
@@ -1,46 +0,0 @@
-package gay.doughmination.mail.ui
-
-import java.text.DateFormat
-import java.util.Calendar
-import java.util.Date
-import java.util.Locale
-
-// Ported from email/src/web/lib/format.ts.
-
-fun fmtTime(ms: Long): String {
- val then = Calendar.getInstance().apply { timeInMillis = ms }
- val now = Calendar.getInstance()
- val sameYear = then.get(Calendar.YEAR) == now.get(Calendar.YEAR)
- return when {
- sameYear && then.get(Calendar.DAY_OF_YEAR) == now.get(Calendar.DAY_OF_YEAR) ->
- DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(ms))
- sameYear -> android.text.format.DateFormat.format(
- android.text.format.DateFormat.getBestDateTimePattern(Locale.getDefault(), "d MMM"),
- ms,
- ).toString()
- else -> DateFormat.getDateInstance(DateFormat.SHORT).format(Date(ms))
- }
-}
-
-fun fmtDateTime(ms: Long): String = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(ms))
-
-fun fmtSize(bytes: Long): String = when {
- bytes < 1024 -> "$bytes B"
- bytes < 1024 * 1024 -> "${bytes / 1024} KB"
- else -> String.format(Locale.getDefault(), "%.1f MB", bytes / 1024.0 / 1024.0)
-}
-
-/** "Ari <[email protected]>" -> "Ari"; a bare address stays as it is. */
-fun displayName(addr: String): String {
- val name = addr.replace(Regex("<[^>]*>"), "").replace("\"", "").trim()
- return name.ifEmpty { addr.replace(Regex("[<>]"), "") }
-}
-
-/** "Ari <[email protected]>" -> "[email protected]". */
-fun bareAddress(addr: String): String = (Regex("<([^<>]+)>").find(addr)?.groupValues?.get(1) ?: addr).trim()
-
-fun isAddress(addr: String): Boolean = Regex("^[^\\s@<>]+@[^\\s@<>]+\\.[^\\s@<>]+$").matches(bareAddress(addr))
-
-/** Splits on , ; and newlines, except inside quotes: "Doe, Jane" <[email protected]> stays whole. */
-fun splitList(raw: String): List<String> =
- Regex("(?:\"[^\"]*\"?|[^,;\\n\"])+").findAll(raw).map { it.value.trim() }.filter { it.isNotEmpty() }.toList()
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt b/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
deleted file mode 100644
index 49f8c99..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/MailViewModel.kt
+++ /dev/null
@@ -1,646 +0,0 @@
-package gay.doughmination.mail.ui
-
-import android.app.Application
-import android.content.Context
-import android.net.Uri
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableIntStateOf
-import androidx.compose.runtime.mutableStateListOf
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.setValue
-import androidx.lifecycle.AndroidViewModel
-import androidx.lifecycle.viewModelScope
-import gay.doughmination.mail.InboxApp
-import gay.doughmination.mail.Push
-import gay.doughmination.mail.data.ApiException
-import gay.doughmination.mail.data.AttachmentInfo
-import gay.doughmination.mail.data.ListFolder
-import gay.doughmination.mail.data.MailThread
-import gay.doughmination.mail.data.Me
-import gay.doughmination.mail.data.Message
-import gay.doughmination.mail.data.Preferences
-import gay.doughmination.mail.data.SendRequest
-import gay.doughmination.mail.data.SignedOutException
-import gay.doughmination.mail.data.ThreadSummary
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.channels.Channel
-import kotlinx.coroutines.flow.receiveAsFlow
-import kotlinx.coroutines.launch
-import java.io.IOException
-
-sealed interface Screen {
- data object List : Screen
- data class Thread(val id: String, val bin: Boolean) : Screen
- data object Compose : Screen
- data object Settings : Screen
-}
-
-/** The composer's contents. Recipients stay as typed until they're sent or saved. */
-data class Draft(
- val title: String,
- val draftId: String? = null,
- val replyTo: String? = null,
- val from: String,
- val to: String = "",
- val cc: String = "",
- val bcc: String = "",
- val subject: String = "",
- val text: String = "",
- val attachments: List<AttachmentInfo> = emptyList(),
-) {
- val isBlank get() = draftId == null && to.isBlank() && cc.isBlank() && bcc.isBlank() &&
- subject.isBlank() && text.isBlank() && attachments.isEmpty()
-}
-
-data class Snack(val text: String, val action: String? = null, val run: (() -> Unit)? = null)
-
-class MailViewModel(application: Application) : AndroidViewModel(application) {
- private val inbox = application as InboxApp
- private val api = inbox.api
-
- var signedIn by mutableStateOf(inbox.signedIn.value)
- private set
- var signingIn by mutableStateOf(false)
- private set
- /** False until the first page of mail is in (or failed), so the splash can wait for it. */
- var ready by mutableStateOf(!inbox.signedIn.value)
- private set
- var loginError by mutableStateOf<String?>(null)
- private set
-
- var me by mutableStateOf<Me?>(null)
- private set
- /** Unread inbox mail per receiving address. */
- var unread by mutableStateOf<Map<String, Int>>(emptyMap())
- private set
-
- var folder by mutableStateOf(ListFolder.Inbox)
- private set
- /** One address, "@domain" for a whole domain, or null for everything. */
- var mailbox by mutableStateOf<String?>(null)
- private set
- val threads = mutableStateListOf<ThreadSummary>()
- var nextCursor by mutableStateOf<String?>(null)
- private set
- var loading by mutableStateOf(false)
- private set
- var refreshing by mutableStateOf(false)
- private set
- var listError by mutableStateOf<String?>(null)
- private set
-
- val stack = mutableStateListOf<Screen>(Screen.List)
- val screen: Screen get() = stack.last()
-
- var thread by mutableStateOf<MailThread?>(null)
- private set
- var threadError by mutableStateOf<String?>(null)
- private set
- /** Bumped when the open thread should reload. */
- var threadVersion by mutableIntStateOf(0)
- private set
-
- var draft by mutableStateOf<Draft?>(null)
- var uploading by mutableIntStateOf(0)
- private set
- var sending by mutableStateOf(false)
- private set
-
- private val snacks = Channel<Snack>(Channel.BUFFERED)
- val snackbar = snacks.receiveAsFlow()
-
- private var listJob: Job? = null
-
- init {
- viewModelScope.launch {
- inbox.signedIn.collect { value ->
- signedIn = value
- if (value) loadSession() else signedOutReset()
- }
- }
- viewModelScope.launch {
- inbox.live.events.collect { threadId ->
- refreshUnread()
- reload(quiet = true)
- val open = screen
- if (open is Screen.Thread && (threadId == null || threadId == open.id)) threadVersion++
- }
- }
- }
-
- // ---- errors
-
- private fun fail(e: Throwable) {
- val text = when (e) {
- is SignedOutException -> return
- is kotlinx.coroutines.CancellationException -> throw e
- is ApiException -> e.message ?: "Something went wrong."
- is IOException -> "Couldn't reach the server."
- else -> e.message ?: "Something went wrong."
- }
- snacks.trySend(Snack(text))
- }
-
- private fun say(text: String, action: String? = null, run: (() -> Unit)? = null) {
- snacks.trySend(Snack(text, action, run))
- }
-
- // ---- signing in and out
-
- fun startLogin(context: Context) {
- loginError = null
- runCatching { inbox.auth.start(context) }.onFailure { loginError = "No browser to sign in with." }
- }
-
- fun finishLogin(code: String) = viewModelScope.launch {
- signingIn = true
- loginError = null
- try {
- inbox.auth.finish(code)
- inbox.setSignedIn(true)
- } catch (e: Exception) {
- loginError = (e as? ApiException)?.message ?: "Couldn't reach the server."
- } finally {
- signingIn = false
- }
- }
-
- fun signOut() = viewModelScope.launch {
- Push.unregister(inbox)
- api.logout()
- inbox.setSignedIn(false)
- }
-
- private fun signedOutReset() {
- inbox.live.stop()
- ready = true
- me = null
- unread = emptyMap()
- threads.clear()
- nextCursor = null
- thread = null
- draft = null
- stack.clear()
- stack.add(Screen.List)
- }
-
- private fun loadSession() = viewModelScope.launch {
- try {
- me = api.me()
- refreshUnread()
- } catch (e: Exception) {
- fail(e)
- }
- reload()
- Push.register(inbox)
- }
-
- private suspend fun refreshUnread() {
- runCatching { api.unread() }.onSuccess { unread = it }
- }
-
- // ---- the list
-
- fun show(folder: ListFolder, mailbox: String? = this.mailbox) {
- this.folder = folder
- this.mailbox = mailbox
- stack.clear()
- stack.add(Screen.List)
- threads.clear()
- nextCursor = null
- reload()
- }
-
- /** Fetches the first page again. `quiet` keeps the spinner off (live updates). */
- fun reload(quiet: Boolean = false, pulled: Boolean = false) {
- listJob?.cancel()
- listJob = viewModelScope.launch {
- if (pulled) refreshing = true else if (!quiet) loading = true
- try {
- val page = api.threads(folder, mailbox, null)
- threads.clear()
- threads.addAll(page.items)
- nextCursor = page.nextCursor
- listError = null
- ready = true
- if (pulled) refreshUnread()
- } catch (e: Exception) {
- if (e is kotlinx.coroutines.CancellationException) throw e
- if (threads.isEmpty()) listError = "Couldn't load your mail." else fail(e)
- ready = true
- } finally {
- loading = false
- refreshing = false
- }
- }
- }
-
- fun loadMore() {
- val cursor = nextCursor ?: return
- if (loading || listJob?.isActive == true) return
- listJob = viewModelScope.launch {
- loading = true
- try {
- val page = api.threads(folder, mailbox, cursor)
- val seen = threads.map { it.id }.toSet()
- threads.addAll(page.items.filter { it.id !in seen })
- nextCursor = page.nextCursor
- } catch (e: Exception) {
- fail(e)
- } finally {
- loading = false
- }
- }
- }
-
- private fun replace(id: String, change: (ThreadSummary) -> ThreadSummary) {
- val i = threads.indexOfFirst { it.id == id }
- if (i >= 0) threads[i] = change(threads[i])
- }
-
- private fun takeOut(id: String) {
- threads.removeAll { it.id == id }
- }
-
- fun toggleRead(t: ThreadSummary) {
- val read = t.unread > 0
- replace(t.id) { it.copy(unread = if (read) 0 else 1) }
- viewModelScope.launch {
- try {
- unread = api.markThread(t.id, read)
- } catch (e: Exception) {
- fail(e)
- reload(quiet = true)
- }
- }
- }
-
- fun toggleStar(threadId: String, starred: Boolean) {
- if (folder == ListFolder.Starred && !starred) takeOut(threadId) else replace(threadId) { it.copy(starred = starred) }
- thread?.takeIf { it.id == threadId }?.let { thread = it.copy(starred = starred) }
- viewModelScope.launch {
- try {
- api.starThread(threadId, starred)
- } catch (e: Exception) {
- fail(e)
- reload(quiet = true)
- }
- }
- }
-
- fun moveToBin(threadId: String) {
- takeOut(threadId)
- if ((screen as? Screen.Thread)?.id == threadId) stack.removeAt(stack.lastIndex)
- viewModelScope.launch {
- try {
- api.deleteThread(threadId)
- refreshUnread()
- say("Moved to Bin", "Undo") { restore(threadId, undo = true) }
- } catch (e: Exception) {
- fail(e)
- reload(quiet = true)
- }
- }
- }
-
- fun restore(threadId: String, undo: Boolean = false) {
- if (!undo) takeOut(threadId)
- if ((screen as? Screen.Thread)?.id == threadId) stack.removeAt(stack.lastIndex)
- viewModelScope.launch {
- try {
- api.restoreThread(threadId)
- refreshUnread()
- if (undo) reload(quiet = true) else say("Restored")
- } catch (e: Exception) {
- fail(e)
- reload(quiet = true)
- }
- }
- }
-
- fun deleteForever(threadId: String) {
- takeOut(threadId)
- if ((screen as? Screen.Thread)?.id == threadId) stack.removeAt(stack.lastIndex)
- viewModelScope.launch {
- try {
- api.deleteThread(threadId, forever = true)
- } catch (e: Exception) {
- fail(e)
- reload(quiet = true)
- }
- }
- }
-
- fun emptyBin() = viewModelScope.launch {
- try {
- val n = api.emptyBin()
- threads.clear()
- nextCursor = null
- say(if (n == 1) "Deleted 1 message" else "Deleted $n messages")
- } catch (e: Exception) {
- fail(e)
- }
- }
-
- /** Drafts open straight in the composer; everything else in the thread view. */
- fun open(t: ThreadSummary) {
- if (folder == ListFolder.Drafts) {
- editDraft(t.latestId)
- return
- }
- replace(t.id) { it.copy(unread = 0) }
- openThread(t.id, folder == ListFolder.Bin)
- }
-
- fun openThread(id: String, bin: Boolean) {
- thread = null
- threadError = null
- stack.add(Screen.Thread(id, bin))
- }
-
- /** For links to the site: /inbox/<thread id> and the like. */
- fun openPath(path: String) {
- val parts = path.split("/").filter { it.isNotEmpty() }
- val target = ListFolder.fromPath(parts.firstOrNull()) ?: ListFolder.Inbox
- if (target != folder || mailbox != null) show(target, null)
- parts.getOrNull(1)?.let { openThread(it, target == ListFolder.Bin) }
- }
-
- // ---- the thread view
-
- fun loadThread(id: String, bin: Boolean) = viewModelScope.launch {
- try {
- val loaded = api.thread(id, bin)
- thread = loaded
- threadError = null
- if (!bin && loaded.messages.any { it.folder == "inbox" && !it.read }) {
- unread = api.markThread(id, true)
- replace(id) { it.copy(unread = 0) }
- }
- } catch (e: Exception) {
- if (e is ApiException && e.status == 404) {
- threadError = "This conversation is gone."
- } else if (thread == null) {
- threadError = "Couldn't load this conversation."
- } else {
- fail(e)
- }
- }
- }
-
- fun markUnread(threadId: String) {
- stack.removeAt(stack.lastIndex)
- replace(threadId) { it.copy(unread = 1) }
- viewModelScope.launch {
- try {
- unread = api.markThread(threadId, false)
- } catch (e: Exception) {
- fail(e)
- }
- }
- }
-
- /** In the Bin a message is deleted for good; elsewhere it moves to the Bin. */
- fun deleteMessage(m: Message, bin: Boolean) = viewModelScope.launch {
- try {
- api.deleteMessage(m.id, forever = bin || m.folder == "drafts")
- afterMessageChange(m.threadId)
- if (!bin && m.folder != "drafts") say("Moved to Bin", "Undo") { restoreMessage(m, undo = true) }
- } catch (e: Exception) {
- fail(e)
- }
- }
-
- fun restoreMessage(m: Message, undo: Boolean = false) = viewModelScope.launch {
- try {
- api.restoreMessage(m.id)
- afterMessageChange(m.threadId)
- if (!undo) say("Restored")
- } catch (e: Exception) {
- fail(e)
- }
- }
-
- private suspend fun afterMessageChange(threadId: String) {
- val open = screen as? Screen.Thread
- if (open?.id == threadId) {
- val left = runCatching { api.thread(threadId, open.bin) }.getOrNull()
- if (left == null) stack.removeAt(stack.lastIndex) else thread = left
- }
- refreshUnread()
- reload(quiet = true)
- }
-
- // ---- composing
-
- private fun defaultFrom(): String = me?.addresses?.firstOrNull() ?: ""
-
- /** The address of ours a message was sent to, so a reply goes out from it. */
- private fun ourAddress(m: Message): String =
- if (me?.addresses?.contains(m.mailbox) == true) m.mailbox else defaultFrom()
-
- private fun prefixed(prefix: String, subject: String): String =
- if (Regex("^\\s*$prefix\\s*:", RegexOption.IGNORE_CASE).containsMatchIn(subject)) subject else "$prefix: $subject"
-
- private fun quote(m: Message): String {
- val body = (m.text ?: "").lines().joinToString("\n") { "> $it" }
- return "\n\nOn ${fmtDateTime(m.sentAt)}, ${m.from} wrote:\n$body"
- }
-
- private fun openComposer(d: Draft) {
- draft = d
- stack.add(Screen.Compose)
- }
-
- fun composeNew() = openComposer(Draft(title = "New message", from = defaultFrom()))
-
- fun composeReply(m: Message) = openComposer(
- Draft(
- title = "Reply",
- replyTo = m.id,
- from = ourAddress(m),
- to = (if (m.folder != "inbox") m.to else listOf(m.from)).joinToString(", "),
- subject = prefixed("Re", m.subject),
- text = quote(m),
- ),
- )
-
- fun composeForward(m: Message) = openComposer(
- Draft(
- title = "Forward",
- from = ourAddress(m),
- subject = prefixed("Fwd", m.subject),
- text = "\n\n---------- Forwarded message ----------\nFrom: ${m.from}\nTo: ${m.to.joinToString(", ")}\n" +
- "Subject: ${m.subject}\n\n${m.text ?: ""}",
- attachments = m.attachments.filter { it.contentId == null },
- ),
- )
-
- fun composeDraft(m: Message) = openComposer(
- Draft(
- title = "Draft",
- draftId = m.id,
- from = m.from,
- to = m.to.joinToString(", "),
- cc = m.cc.joinToString(", "),
- bcc = m.bcc.joinToString(", "),
- subject = m.subject,
- text = m.text ?: "",
- attachments = m.attachments,
- ),
- )
-
- fun editDraft(messageId: String) = viewModelScope.launch {
- try {
- composeDraft(api.message(messageId))
- } catch (e: Exception) {
- fail(e)
- }
- }
-
- fun attach(context: Context, uris: List<Uri>) {
- for (uri in uris) {
- viewModelScope.launch {
- uploading++
- try {
- val info = api.upload(context.contentResolver, uri)
- draft = draft?.let { it.copy(attachments = it.attachments + info) }
- } catch (e: Exception) {
- fail(e)
- } finally {
- uploading--
- }
- }
- }
- }
-
- fun removeAttachment(a: AttachmentInfo) {
- draft = draft?.let { it.copy(attachments = it.attachments - a) }
- }
-
- private fun request(d: Draft, keep: (String) -> Boolean): SendRequest = SendRequest(
- from = d.from,
- to = splitList(d.to).filter(keep),
- cc = splitList(d.cc).filter(keep),
- bcc = splitList(d.bcc).filter(keep),
- subject = d.subject,
- text = d.text,
- attachmentIds = d.attachments.map { it.id },
- replyTo = d.replyTo,
- )
-
- fun send() {
- val d = draft ?: return
- if (uploading > 0 || sending) return
- val bad = (splitList(d.to) + splitList(d.cc) + splitList(d.bcc)).firstOrNull { !isAddress(it) }
- if (bad != null) return say("$bad isn't an email address.")
- if (splitList(d.to).isEmpty()) return say("Add at least one recipient.")
- viewModelScope.launch {
- sending = true
- try {
- api.send(request(d) { true }.copy(draftId = d.draftId))
- closeComposer()
- say("Sent")
- reload(quiet = true)
- threadVersion++
- } catch (e: Exception) {
- // The server keeps it as a draft when Resend refuses it.
- (e as? ApiException)?.draftId?.let { id -> draft = draft?.copy(draftId = id) }
- fail(e)
- } finally {
- sending = false
- }
- }
- }
-
- /** Back out of the composer: anything written is kept in Drafts. */
- fun closeAndSave() {
- val d = draft ?: return
- if (d.isBlank) return closeComposer()
- if (uploading > 0) return say("Wait for attachments to finish uploading.")
- viewModelScope.launch {
- // Half-typed addresses would be refused, so the draft keeps only the whole ones.
- val all = splitList(d.to) + splitList(d.cc) + splitList(d.bcc)
- val req = request(d, ::isAddress)
- try {
- if (d.draftId != null) api.updateDraft(d.draftId, req) else api.createDraft(req)
- closeComposer()
- val dropped = all.count { !isAddress(it) }
- say(if (dropped > 0) "Saved to Drafts, without $dropped unfinished address(es)" else "Saved to Drafts")
- reload(quiet = true)
- threadVersion++
- } catch (e: Exception) {
- fail(e)
- }
- }
- }
-
- fun discard() {
- val id = draft?.draftId
- closeComposer()
- if (id == null) return
- viewModelScope.launch {
- try {
- api.deleteMessage(id, forever = true)
- say("Draft discarded")
- reload(quiet = true)
- threadVersion++
- } catch (e: Exception) {
- fail(e)
- }
- }
- }
-
- private fun closeComposer() {
- if (screen == Screen.Compose) stack.removeAt(stack.lastIndex)
- draft = null
- }
-
- // ---- settings and navigation
-
- fun openSettings() {
- stack.add(Screen.Settings)
- }
-
- fun saveName(name: String) = viewModelScope.launch {
- try {
- api.setName(name.trim())
- me = me?.copy(name = name.trim().ifEmpty { null })
- say("Saved")
- } catch (e: Exception) {
- fail(e)
- }
- }
-
- /** Shows the change straight away, and puts it back if the server says no. */
- fun setPreferences(prefs: Preferences) = viewModelScope.launch {
- val before = me ?: return@launch
- me = before.copy(usePicture = prefs.usePicture, swipeLeft = prefs.swipeLeft, swipeRight = prefs.swipeRight)
- try {
- val saved = api.setPreferences(prefs)
- me = me?.copy(usePicture = saved.usePicture, swipeLeft = saved.swipeLeft, swipeRight = saved.swipeRight)
- } catch (e: Exception) {
- me = me?.copy(usePicture = before.usePicture, swipeLeft = before.swipeLeft, swipeRight = before.swipeRight)
- fail(e)
- }
- }
-
- fun testPush() = viewModelScope.launch {
- try {
- val n = api.pushTest()
- say(if (n == 0) "No devices have notifications on yet." else "Sent to $n device(s).")
- } catch (e: Exception) {
- fail(e)
- }
- }
-
- /** Returns false when there's nowhere to go back to. */
- fun back(): Boolean {
- when {
- screen == Screen.Compose -> closeAndSave()
- stack.size > 1 -> stack.removeAt(stack.lastIndex)
- else -> return false
- }
- return true
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt b/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
deleted file mode 100644
index d96f918..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/SettingsScreen.kt
+++ /dev/null
@@ -1,244 +0,0 @@
-package gay.doughmination.mail.ui
-
-import android.content.Intent
-import android.net.Uri
-import android.provider.Settings
-import androidx.browser.customtabs.CustomTabsIntent
-import androidx.compose.foundation.background
-import androidx.compose.foundation.border
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.ColumnScope
-import androidx.compose.foundation.layout.ExperimentalLayoutApi
-import androidx.compose.foundation.layout.FlowRow
-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.rememberScrollState
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.foundation.verticalScroll
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.automirrored.outlined.ArrowBack
-import androidx.compose.material.icons.automirrored.outlined.Logout
-import androidx.compose.material.icons.outlined.ChevronRight
-import androidx.compose.material.icons.outlined.Notifications
-import androidx.compose.material.icons.outlined.PrivacyTip
-import androidx.compose.material3.Button
-import androidx.compose.material3.ButtonDefaults
-import androidx.compose.material3.DropdownMenuItem
-import androidx.compose.material3.ExposedDropdownMenuBox
-import androidx.compose.material3.ExposedDropdownMenuDefaults
-import androidx.compose.material3.MenuAnchorType
-import androidx.compose.material3.Switch
-import androidx.compose.material3.ExperimentalMaterial3Api
-import androidx.compose.material3.Icon
-import androidx.compose.material3.IconButton
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.OutlinedButton
-import androidx.compose.material3.OutlinedTextField
-import androidx.compose.material3.Scaffold
-import androidx.compose.material3.SnackbarHost
-import androidx.compose.material3.Text
-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.compose.ui.Alignment
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.draw.clip
-import androidx.compose.ui.graphics.vector.ImageVector
-import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.unit.dp
-import gay.doughmination.mail.BuildConfig
-import gay.doughmination.mail.Push
-import gay.doughmination.mail.data.SwipeAction
-
-/** Laid out like the web's settings page: one card per topic, under a small pink heading. */
-@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
-@Composable
-fun SettingsScreen(vm: MailViewModel) {
- val me = vm.me
- val context = LocalContext.current
- var name by rememberSaveable(me?.name) { mutableStateOf(me?.name.orEmpty()) }
- val openWeb = { path: String ->
- CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(BuildConfig.INBOX_URL + path))
- }
-
- Scaffold(
- topBar = {
- TopAppBar(
- title = { Text("Settings") },
- navigationIcon = {
- IconButton(onClick = { vm.back() }) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, "Back") }
- },
- )
- },
- snackbarHost = { SnackbarHost(LocalSnackbar.current) },
- ) { padding ->
- Column(
- Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 12.dp),
- verticalArrangement = Arrangement.spacedBy(16.dp),
- ) {
- Section("Your name") {
- Note("People see this as the sender of mail you send. Leave it empty to send from just the address.")
- Row(verticalAlignment = Alignment.CenterVertically) {
- OutlinedTextField(
- value = name,
- onValueChange = { if (it.length <= 100) name = it },
- placeholder = { Text("Your name") },
- singleLine = true,
- modifier = Modifier.weight(1f),
- )
- Spacer(Modifier.width(8.dp))
- Button(onClick = { vm.saveName(name) }, enabled = name.trim() != me?.name.orEmpty()) { Text("Save") }
- }
- }
-
- Section("Profile picture") {
- val picture = me?.picture
- Row(verticalAlignment = Alignment.CenterVertically) {
- AccountPicture(me, 56.dp)
- Spacer(Modifier.width(16.dp))
- Column(Modifier.weight(1f)) {
- Text("Use your account's picture")
- Note(
- if (picture != null) "The one on your Doughmination account. Off shows your initial instead."
- else "Your Doughmination account has no picture, so your initial shows.",
- )
- }
- Spacer(Modifier.width(12.dp))
- Switch(
- checked = me?.shownPicture != null,
- onCheckedChange = { on -> me?.let { vm.setPreferences(it.preferences.copy(usePicture = on)) } },
- enabled = picture != null,
- )
- }
- }
-
- Section("Swipe actions") {
- Note(
- "What swiping a conversation in the list does, here and on the web. Read and unread only " +
- "applies to received mail, and in the Bin a swipe right always restores.",
- )
- me?.let {
- SwipePicker("Swipe right", it.swipeRight) { choice -> vm.setPreferences(it.preferences.copy(swipeRight = choice)) }
- SwipePicker("Swipe left", it.swipeLeft) { choice -> vm.setPreferences(it.preferences.copy(swipeLeft = choice)) }
- }
- }
-
- Section("Your addresses") {
- Note("You receive and can send from each of these.")
- for (addr in me?.addresses.orEmpty()) Text("• $addr")
- if (me?.addresses.isNullOrEmpty()) Text("None yet. Ask an admin to switch on a domain.")
- }
-
- Section("Notifications", Icons.Outlined.Notifications) {
- if (Push.available(context)) {
- Note("Turn new-mail notifications on or off in Android's settings for the app.")
- FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- OutlinedButton(onClick = {
- context.startActivity(
- Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
- .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName),
- )
- }) { Text("Notification settings") }
- OutlinedButton(onClick = vm::testPush) { Text("Send a test") }
- }
- } else {
- Note("This build has no Firebase setup, so notifications are off.")
- }
- }
-
- Section("Privacy and terms", Icons.Outlined.PrivacyTip) {
- Note("What's stored about you and your mail, who can see it, and the rules for using the inbox.")
- FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- OutlinedButton(onClick = { openWeb("/privacy") }) {
- Text("Privacy policy")
- Icon(Icons.Outlined.ChevronRight, null, Modifier.size(ButtonDefaults.IconSize))
- }
- OutlinedButton(onClick = { openWeb("/terms") }) {
- Text("Terms of service")
- Icon(Icons.Outlined.ChevronRight, null, Modifier.size(ButtonDefaults.IconSize))
- }
- }
- }
-
- Section("Account") {
- me?.let { Note("Signed in as ${it.username}.") }
- OutlinedButton(
- onClick = { vm.signOut() },
- colors = ButtonDefaults.outlinedButtonColors(contentColor = Danger),
- contentPadding = ButtonDefaults.ButtonWithIconContentPadding,
- ) {
- Icon(Icons.AutoMirrored.Outlined.Logout, null, Modifier.size(ButtonDefaults.IconSize))
- Spacer(Modifier.width(ButtonDefaults.IconSpacing))
- Text("Sign out")
- }
- }
-
- Text(
- "Inbox ${BuildConfig.VERSION_NAME}",
- Modifier.padding(start = 4.dp, bottom = 24.dp),
- style = MaterialTheme.typography.labelSmall,
- color = Muted,
- )
- }
- }
-}
-
-private val sectionShape = RoundedCornerShape(16.dp)
-
-/** A card like the web's settings sections: dark glass, a hairline border, an eyebrow heading. */
-@Composable
-private fun Section(title: String, icon: ImageVector? = null, content: @Composable ColumnScope.() -> Unit) {
- Column(
- Modifier
- .fillMaxWidth()
- .clip(sectionShape)
- .background(Bg.copy(alpha = 0.72f))
- .border(1.dp, Line, sectionShape)
- .padding(16.dp),
- verticalArrangement = Arrangement.spacedBy(10.dp),
- ) {
- Row(verticalAlignment = Alignment.CenterVertically) {
- if (icon != null) {
- Icon(icon, null, Modifier.size(16.dp), tint = Accent)
- Spacer(Modifier.width(6.dp))
- }
- Text(title.uppercase(), style = Eyebrow)
- }
- content()
- }
-}
-
-/** A dropdown of the swipe actions, as an outlined field. */
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable
-private fun SwipePicker(label: String, selected: SwipeAction, onPick: (SwipeAction) -> Unit) {
- var open by remember { mutableStateOf(false) }
- ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it }) {
- OutlinedTextField(
- value = selected.label,
- onValueChange = {},
- readOnly = true,
- label = { Text(label) },
- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(open) },
- modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable),
- )
- ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) {
- for (choice in SwipeAction.entries) {
- DropdownMenuItem(text = { Text(choice.label) }, onClick = { open = false; onPick(choice) })
- }
- }
- }
-}
-
-@Composable
-private fun Note(text: String) = Text(text, style = MaterialTheme.typography.bodyMedium, color = Muted)
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/Theme.kt b/app/app/src/main/java/gay/doughmination/mail/ui/Theme.kt
deleted file mode 100644
index b1eefa4..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/Theme.kt
+++ /dev/null
@@ -1,140 +0,0 @@
-package gay.doughmination.mail.ui
-
-import androidx.compose.foundation.Image
-import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.fillMaxSize
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.draw.drawBehind
-import androidx.compose.ui.geometry.Offset
-import androidx.compose.ui.graphics.Brush
-import androidx.compose.ui.layout.ContentScale
-import androidx.compose.ui.res.painterResource
-import gay.doughmination.mail.R
-import androidx.compose.material3.Typography
-import androidx.compose.material3.darkColorScheme
-import androidx.compose.runtime.Composable
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.text.TextStyle
-import androidx.compose.ui.text.font.Font
-import androidx.compose.ui.text.font.FontFamily
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.unit.sp
-
-// The site's palette (email/src/web/app.css).
-val Accent = Color(0xFFEB459E)
-val Danger = Color(0xFFFF5C7A)
-val Muted = Color(0xFFA49EAB)
-val Bg = Color(0xFF0B0A0D)
-/** A card on the backdrop, like --raised on the web. */
-val Raised = Color.White.copy(alpha = 0.05f)
-/** Hairline borders, like --line on the web. */
-val Line = Color.White.copy(alpha = 0.09f)
-/** A starred thread, like --star on the web. */
-val StarYellow = Color(0xFFF7C948)
-
-/** IBM Plex Sans, as on the web and doughmination.gay (the same files, as TTF). */
-val PlexSans = FontFamily(
- Font(R.font.ibm_plex_sans_regular, FontWeight.Normal),
- Font(R.font.ibm_plex_sans_medium, FontWeight.Medium),
- Font(R.font.ibm_plex_sans_semibold, FontWeight.SemiBold),
- Font(R.font.ibm_plex_sans_bold, FontWeight.Bold),
-)
-
-private fun TextStyle.plex() = copy(fontFamily = PlexSans)
-
-private val typography = Typography().run {
- Typography(
- displayLarge = displayLarge.plex(),
- displayMedium = displayMedium.plex(),
- displaySmall = displaySmall.plex(),
- headlineLarge = headlineLarge.plex(),
- headlineMedium = headlineMedium.plex(),
- headlineSmall = headlineSmall.plex(),
- titleLarge = titleLarge.plex(),
- titleMedium = titleMedium.plex(),
- titleSmall = titleSmall.plex(),
- bodyLarge = bodyLarge.plex(),
- bodyMedium = bodyMedium.plex(),
- bodySmall = bodySmall.plex(),
- labelLarge = labelLarge.plex(),
- labelMedium = labelMedium.plex(),
- labelSmall = labelSmall.plex(),
- )
-}
-
-/** The web's small uppercase accent label (.eyebrow), used for headings. */
-val Eyebrow = TextStyle(
- fontFamily = PlexSans,
- fontSize = 11.sp,
- fontWeight = FontWeight.SemiBold,
- letterSpacing = 1.5.sp,
- color = Accent,
-)
-
-private val colors = darkColorScheme(
- primary = Accent,
- onPrimary = Color.White,
- primaryContainer = Color(0xFF3A1A2C),
- onPrimaryContainer = Color(0xFFFFD8EA),
- secondaryContainer = Color(0xFF2A1A24),
- onSecondaryContainer = Color(0xFFFFD8EA),
- // Screens and app bars sit on the Backdrop, so these are see-through.
- // Sheets, menus and dialogs use the surfaceContainer colours and stay opaque.
- background = Color.Transparent,
- onBackground = Color(0xFFECE9EF),
- surface = Color.Transparent,
- onSurface = Color(0xFFECE9EF),
- surfaceVariant = Color(0xFF1C1A20),
- onSurfaceVariant = Muted,
- surfaceContainerLowest = Color(0xFF0B0A0D),
- surfaceContainerLow = Color(0xFF131116),
- surfaceContainer = Color(0xFF17151B),
- surfaceContainerHigh = Color(0xFF1E1B22),
- surfaceContainerHighest = Color(0xFF26222B),
- outline = Color(0xFF3A3640),
- outlineVariant = Color(0xFF26222B),
- error = Danger,
-)
-
-/**
- * The site's wallpaper behind every screen, dimmed the way the web does it:
- * the art at half strength under a dark wash and a soft pink glow.
- */
-@Composable
-fun Backdrop(modifier: Modifier = Modifier) {
- Box(modifier.fillMaxSize().background(Bg)) {
- Image(
- painterResource(R.drawable.background),
- contentDescription = null,
- contentScale = ContentScale.Crop,
- alpha = 0.5f,
- modifier = Modifier.fillMaxSize(),
- )
- Box(
- Modifier.fillMaxSize().background(
- Brush.verticalGradient(
- 0f to Bg.copy(alpha = 0.55f),
- 0.55f to Bg.copy(alpha = 0.8f),
- 1f to Bg,
- ),
- ),
- )
- Box(
- Modifier.fillMaxSize().drawBehind {
- drawRect(
- Brush.radialGradient(
- listOf(Accent.copy(alpha = 0.12f), Color.Transparent),
- center = Offset(size.width * 0.2f, size.height * 0.3f),
- radius = size.maxDimension * 0.6f,
- ),
- )
- },
- )
- }
-}
-
-@Composable
-fun InboxTheme(content: @Composable () -> Unit) =
- MaterialTheme(colorScheme = colors, typography = typography, content = content)
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt b/app/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt
deleted file mode 100644
index cd09381..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/ThreadListScreen.kt
+++ /dev/null
@@ -1,553 +0,0 @@
-package gay.doughmination.mail.ui
-
-import android.os.Build
-import android.view.HapticFeedbackConstants
-import androidx.compose.foundation.ExperimentalFoundationApi
-import androidx.compose.foundation.background
-import androidx.compose.foundation.combinedClickable
-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.navigationBarsPadding
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.layout.width
-import androidx.compose.foundation.layout.widthIn
-import androidx.compose.foundation.lazy.LazyColumn
-import androidx.compose.foundation.lazy.items
-import androidx.compose.foundation.lazy.rememberLazyListState
-import androidx.compose.foundation.shape.CircleShape
-import androidx.compose.foundation.rememberScrollState
-import androidx.compose.foundation.verticalScroll
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.automirrored.outlined.Send
-import androidx.compose.material.icons.outlined.AlternateEmail
-import androidx.compose.material.icons.outlined.AllInbox
-import androidx.compose.material.icons.outlined.AttachFile
-import androidx.compose.material.icons.outlined.Delete
-import androidx.compose.material.icons.outlined.DeleteForever
-import androidx.compose.material.icons.outlined.Drafts
-import androidx.compose.material.icons.outlined.Edit
-import androidx.compose.material.icons.outlined.Inbox
-import androidx.compose.material.icons.outlined.Language
-import androidx.compose.material.icons.outlined.MarkEmailRead
-import androidx.compose.material.icons.outlined.MarkEmailUnread
-import androidx.compose.material.icons.outlined.Menu
-import androidx.compose.material.icons.outlined.OpenInNew
-import androidx.compose.material.icons.outlined.RestoreFromTrash
-import androidx.compose.material.icons.outlined.Settings
-import androidx.compose.material.icons.outlined.Shield
-import androidx.compose.material.icons.outlined.Star
-import androidx.compose.material.icons.outlined.StarOutline
-import androidx.compose.material.icons.filled.Star
-import androidx.compose.material3.AlertDialog
-import androidx.compose.material3.Badge
-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.ListItem
-import androidx.compose.material3.ListItemDefaults
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.ModalBottomSheet
-import androidx.compose.material3.ModalDrawerSheet
-import androidx.compose.material3.ModalNavigationDrawer
-import androidx.compose.material3.NavigationDrawerItem
-import androidx.compose.material3.NavigationDrawerItemDefaults
-import androidx.compose.material3.Scaffold
-import androidx.compose.material3.SnackbarHost
-import androidx.compose.material3.SwipeToDismissBox
-import androidx.compose.material3.SwipeToDismissBoxValue
-import androidx.compose.material3.Text
-import androidx.compose.material3.TextButton
-import androidx.compose.material3.TopAppBar
-import androidx.compose.material3.pulltorefresh.PullToRefreshBox
-import androidx.compose.material3.rememberDrawerState
-import androidx.compose.material3.rememberModalBottomSheetState
-import androidx.compose.material3.rememberSwipeToDismissBoxState
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.LaunchedEffect
-import androidx.compose.runtime.derivedStateOf
-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.draw.clip
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.graphics.vector.ImageVector
-import androidx.compose.ui.platform.LocalContext
-import androidx.compose.ui.platform.LocalView
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.text.style.TextOverflow
-import androidx.compose.ui.unit.dp
-import androidx.compose.ui.unit.sp
-import androidx.browser.customtabs.CustomTabsIntent
-import android.net.Uri
-import gay.doughmination.mail.data.ListFolder
-import gay.doughmination.mail.data.SwipeAction
-import gay.doughmination.mail.data.ThreadSummary
-import kotlinx.coroutines.launch
-
-// CONFIRM only exists from Android 11.
-private val swipeHaptic =
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.VIRTUAL_KEY
-
-private val folderIcons = mapOf(
- ListFolder.Inbox to Icons.Outlined.Inbox,
- ListFolder.Starred to Icons.Outlined.StarOutline,
- ListFolder.Sent to Icons.AutoMirrored.Outlined.Send,
- ListFolder.Drafts to Icons.Outlined.Drafts,
- ListFolder.Bin to Icons.Outlined.Delete,
-)
-
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable
-fun ThreadListScreen(vm: MailViewModel) {
- val drawer = rememberDrawerState(androidx.compose.material3.DrawerValue.Closed)
- val scope = rememberCoroutineScope()
- var menuFor by remember { mutableStateOf<ThreadSummary?>(null) }
- var confirmEmpty by remember { mutableStateOf(false) }
-
- ModalNavigationDrawer(
- drawerState = drawer,
- drawerContent = {
- Drawer(vm) { scope.launch { drawer.close() } }
- },
- ) {
- Scaffold(
- topBar = {
- TopAppBar(
- title = {
- Column {
- Text(vm.folder.label)
- vm.mailbox?.let {
- Text(it, style = MaterialTheme.typography.labelMedium, color = Muted)
- }
- }
- },
- navigationIcon = {
- IconButton(onClick = { scope.launch { drawer.open() } }) {
- Icon(Icons.Outlined.Menu, "Folders")
- }
- },
- actions = {
- if (vm.folder == ListFolder.Bin && vm.threads.isNotEmpty()) {
- TextButton(onClick = { confirmEmpty = true }) { Text("Empty Bin") }
- }
- },
- )
- },
- floatingActionButton = {
- if (vm.folder != ListFolder.Bin) {
- ExtendedFloatingActionButton(
- onClick = vm::composeNew,
- icon = { Icon(Icons.Outlined.Edit, null) },
- text = { Text("Compose") },
- )
- }
- },
- snackbarHost = { SnackbarHost(LocalSnackbar.current) },
- ) { padding ->
- PullToRefreshBox(
- isRefreshing = vm.refreshing,
- onRefresh = { vm.reload(pulled = true) },
- modifier = Modifier.padding(padding).fillMaxSize(),
- ) {
- ThreadList(vm, onHold = { menuFor = it })
- }
- }
- }
-
- menuFor?.let { t ->
- ThreadMenu(vm, t) { menuFor = null }
- }
-
- if (confirmEmpty) {
- AlertDialog(
- onDismissRequest = { confirmEmpty = false },
- title = { Text("Empty the Bin?") },
- text = { Text("Everything in the Bin is deleted for good.") },
- confirmButton = {
- TextButton(onClick = {
- confirmEmpty = false
- vm.emptyBin()
- }) { Text("Delete forever", color = Danger) }
- },
- dismissButton = { TextButton(onClick = { confirmEmpty = false }) { Text("Cancel") } },
- )
- }
-}
-
-@Composable
-private fun ThreadList(vm: MailViewModel, onHold: (ThreadSummary) -> Unit) {
- val state = rememberLazyListState()
- val nearEnd by remember {
- derivedStateOf {
- val last = state.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
- last >= state.layoutInfo.totalItemsCount - 5
- }
- }
- LaunchedEffect(nearEnd, vm.nextCursor) {
- if (nearEnd && vm.nextCursor != null) vm.loadMore()
- }
-
- when {
- vm.threads.isEmpty() && vm.loading -> Centered { CircularProgressIndicator() }
- vm.threads.isEmpty() && vm.listError != null -> Centered {
- Text(vm.listError!!, color = Muted)
- TextButton(onClick = { vm.reload() }) { Text("Try again") }
- }
- vm.threads.isEmpty() -> Centered {
- Text(if (vm.folder == ListFolder.Bin) "The Bin is empty." else "Nothing here.", color = Muted)
- }
- else -> LazyColumn(state = state, modifier = Modifier.fillMaxSize()) {
- items(vm.threads, key = { it.id }) { t ->
- SwipeRow(vm, t, onHold)
- }
- if (vm.loading) {
- item { Centered(Modifier.padding(16.dp)) { CircularProgressIndicator(Modifier.size(24.dp)) } }
- }
- }
- }
-}
-
-@Composable
-private fun Centered(modifier: Modifier = Modifier.fillMaxSize(), content: @Composable () -> Unit) {
- Column(
- modifier.fillMaxWidth(),
- verticalArrangement = Arrangement.Center,
- horizontalAlignment = Alignment.CenterHorizontally,
- ) { content() }
-}
-
-/** One way to swipe a row: what it shows underneath, and what it does. */
-private class Swipe(val label: String, val icon: ImageVector, val color: Color, val dismiss: Boolean, val run: () -> Unit)
-
-/** What a swipe set up in Settings does to this row; null where it can't apply. Same as the web. */
-private fun swipeFor(choice: SwipeAction, vm: MailViewModel, t: ThreadSummary): Swipe? = when (choice) {
- // Only received mail has a read state.
- SwipeAction.Read -> if (vm.folder != ListFolder.Inbox && vm.folder != ListFolder.Starred) null else Swipe(
- if (t.unread > 0) "Read" else "Unread",
- if (t.unread > 0) Icons.Outlined.MarkEmailRead else Icons.Outlined.MarkEmailUnread,
- Accent,
- dismiss = false,
- ) { vm.toggleRead(t) }
- SwipeAction.Star -> Swipe(
- if (t.starred) "Unstar" else "Star",
- if (t.starred) Icons.Outlined.StarOutline else Icons.Filled.Star,
- Accent,
- // Unstarring takes it out of Starred.
- dismiss = vm.folder == ListFolder.Starred && t.starred,
- ) { vm.toggleStar(t.id, !t.starred) }
- SwipeAction.Bin -> Swipe("Bin", Icons.Outlined.Delete, Danger, dismiss = true) { vm.moveToBin(t.id) }
- SwipeAction.None -> null
-}
-
-/**
- * Swipes do what Settings says (toggle read and bin it, unless changed). In
- * the Bin, swiping right restores and left does nothing. Same as the web app.
- */
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable
-private fun SwipeRow(vm: MailViewModel, t: ThreadSummary, onHold: (ThreadSummary) -> Unit) {
- val inBin = vm.folder == ListFolder.Bin
- val right = if (inBin) Swipe("Restore", Icons.Outlined.RestoreFromTrash, Accent, dismiss = true) { vm.restore(t.id) }
- else swipeFor(vm.me?.swipeRight ?: SwipeAction.Read, vm, t)
- val left = if (inBin) null else swipeFor(vm.me?.swipeLeft ?: SwipeAction.Bin, vm, t)
- val view = LocalView.current
- // Material can ask more than once for one swipe; an action must only run once.
- var firedAt by remember { mutableStateOf(0L) }
- val state = rememberSwipeToDismissBoxState(
- confirmValueChange = { value ->
- val now = System.currentTimeMillis()
- if (value != SwipeToDismissBoxValue.Settled && now - firedAt < 600) return@rememberSwipeToDismissBoxState false
- if (value != SwipeToDismissBoxValue.Settled) firedAt = now
- val swipe = when (value) {
- SwipeToDismissBoxValue.StartToEnd -> right
- SwipeToDismissBoxValue.EndToStart -> left
- SwipeToDismissBoxValue.Settled -> return@rememberSwipeToDismissBoxState true
- } ?: return@rememberSwipeToDismissBoxState false
- view.performHapticFeedback(swipeHaptic)
- swipe.run()
- // Not dismissed: the row springs back, showing its new state.
- swipe.dismiss
- },
- positionalThreshold = { it * 0.35f },
- )
-
- SwipeToDismissBox(
- state = state,
- enableDismissFromStartToEnd = right != null,
- enableDismissFromEndToStart = left != null,
- backgroundContent = {
- val direction = state.dismissDirection
- val swipe = when (direction) {
- SwipeToDismissBoxValue.StartToEnd -> right
- SwipeToDismissBoxValue.EndToStart -> left
- SwipeToDismissBoxValue.Settled -> null
- }
- Row(
- Modifier.fillMaxSize().background(swipe?.color ?: Color.Transparent).padding(horizontal = 24.dp),
- horizontalArrangement = if (direction == SwipeToDismissBoxValue.EndToStart) Arrangement.End else Arrangement.Start,
- verticalAlignment = Alignment.CenterVertically,
- ) {
- if (swipe != null) {
- Icon(swipe.icon, null, tint = Color.White)
- Spacer(Modifier.width(8.dp))
- Text(swipe.label, color = Color.White, fontWeight = FontWeight.SemiBold)
- }
- }
- },
- ) {
- val moving = state.dismissDirection != SwipeToDismissBoxValue.Settled
- ThreadRow(vm, t, opaque = moving, onClick = { vm.open(t) }, onLongClick = {
- view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
- onHold(t)
- })
- }
-}
-
-@OptIn(ExperimentalFoundationApi::class)
-@Composable
-private fun ThreadRow(vm: MailViewModel, t: ThreadSummary, opaque: Boolean, onClick: () -> Unit, onLongClick: () -> Unit) {
- val unread = t.unread > 0
- // The Bin and Starred mix folders; whoever it's from reads best there.
- val fromSide = vm.folder != ListFolder.Sent && vm.folder != ListFolder.Drafts
- val who = if (fromSide) displayName(t.from)
- else "To: " + (t.to.joinToString(", ") { displayName(it) }.ifEmpty { "(nobody yet)" })
- // Laid out like the web's rows on a phone, sizes and all.
- Row(
- Modifier
- .fillMaxWidth()
- // Opaque only while it's being swiped, so the wallpaper shows through at rest.
- .background(if (opaque) Bg else Color.Transparent)
- .combinedClickable(onClick = onClick, onLongClick = onLongClick)
- .padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 10.dp),
- verticalAlignment = Alignment.Top,
- ) {
- Avatar(if (fromSide) displayName(t.from) else displayName(t.to.firstOrNull() ?: "?"))
- Spacer(Modifier.width(14.dp))
- Column(Modifier.weight(1f)) {
- Row(Modifier.padding(end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
- Text(
- who,
- Modifier.weight(1f, fill = false),
- fontSize = 15.sp,
- fontWeight = if (unread) FontWeight.Bold else FontWeight.Normal,
- color = if (unread) MaterialTheme.colorScheme.onSurface else Muted,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- )
- if (t.count > 1) {
- Spacer(Modifier.width(6.dp))
- Text("${t.count}", fontSize = 12.sp, color = Muted)
- }
- if (t.hasAttachments) {
- Spacer(Modifier.width(6.dp))
- Icon(Icons.Outlined.AttachFile, "Has attachments", Modifier.size(14.dp), tint = Muted)
- }
- Spacer(Modifier.weight(1f).widthIn(min = 8.dp))
- Text(
- fmtTime(t.lastAt),
- fontSize = 12.sp,
- fontWeight = if (unread) FontWeight.Bold else FontWeight.Normal,
- color = if (unread) MaterialTheme.colorScheme.onSurface else Muted,
- )
- }
- Text(
- t.subject.ifEmpty { "(no subject)" },
- Modifier.padding(end = 8.dp),
- fontSize = 14.sp,
- fontWeight = if (unread) FontWeight.Bold else FontWeight.Normal,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- )
- Row(verticalAlignment = Alignment.CenterVertically) {
- Text(
- t.snippet,
- Modifier.weight(1f),
- fontSize = 13.5.sp,
- color = Muted,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- )
- // A star on every row, as on the web; the Bin has none.
- if (vm.folder != ListFolder.Bin) {
- IconButton(onClick = { vm.toggleStar(t.id, !t.starred) }, Modifier.size(32.dp)) {
- if (t.starred) Icon(Icons.Filled.Star, "Unstar", Modifier.size(18.dp), tint = StarYellow)
- else Icon(Icons.Outlined.StarOutline, "Star", Modifier.size(18.dp), tint = Muted)
- }
- }
- }
- }
- }
-}
-
-/** A coloured initial, as the web draws it: the same hue from the same name. */
-@Composable
-private fun Avatar(name: String) {
- val initial = name.trim().firstOrNull { it.isLetterOrDigit() }?.uppercaseChar() ?: '?'
- // The web's hash runs over code points, taking each one's first UTF-16 unit.
- var hue = 0
- var i = 0
- while (i < name.length) {
- hue = (hue * 31 + name[i].code) % 360
- i += Character.charCount(name.codePointAt(i))
- }
- Box(
- Modifier.padding(top = 2.dp).size(40.dp).clip(CircleShape).background(Color.hsl(hue.toFloat(), 0.55f, 0.42f)),
- contentAlignment = Alignment.Center,
- ) {
- Text(initial.toString(), color = Color.White, fontSize = 17.sp, fontWeight = FontWeight.SemiBold)
- }
-}
-
-/** The long-press menu, as a bottom sheet. */
-@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
-@Composable
-private fun ThreadMenu(vm: MailViewModel, t: ThreadSummary, onClose: () -> Unit) {
- val sheet = rememberModalBottomSheetState(skipPartiallyExpanded = true)
- var confirmDelete by remember { mutableStateOf(false) }
-
- @Composable
- fun item(label: String, icon: ImageVector, danger: Boolean = false, run: () -> Unit) {
- ListItem(
- headlineContent = { Text(label, color = if (danger) Danger else Color.Unspecified) },
- leadingContent = { Icon(icon, null, tint = if (danger) Danger else Muted) },
- colors = ListItemDefaults.colors(containerColor = Color.Transparent),
- modifier = Modifier.combinedClickable(onClick = run),
- )
- }
-
- ModalBottomSheet(onDismissRequest = onClose, sheetState = sheet) {
- Column(Modifier.navigationBarsPadding().padding(bottom = 8.dp)) {
- Text(
- t.subject.ifEmpty { "(no subject)" },
- Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
- style = MaterialTheme.typography.titleMedium,
- maxLines = 2,
- overflow = TextOverflow.Ellipsis,
- )
- HorizontalDivider()
- when (vm.folder) {
- ListFolder.Bin -> {
- item("Open", Icons.Outlined.OpenInNew) { onClose(); vm.open(t) }
- item("Restore", Icons.Outlined.RestoreFromTrash) { onClose(); vm.restore(t.id) }
- item(
- if (confirmDelete) "Tap again to delete forever" else "Delete forever",
- Icons.Outlined.DeleteForever,
- danger = true,
- ) {
- if (!confirmDelete) confirmDelete = true else { onClose(); vm.deleteForever(t.id) }
- }
- }
- else -> {
- if (vm.folder == ListFolder.Drafts) {
- item("Edit", Icons.Outlined.Edit) { onClose(); vm.editDraft(t.latestId) }
- item("Open conversation", Icons.Outlined.OpenInNew) { onClose(); vm.openThread(t.id, false) }
- } else {
- item("Open", Icons.Outlined.OpenInNew) { onClose(); vm.open(t) }
- }
- if (t.starred) {
- item("Unstar", Icons.Outlined.StarOutline) { onClose(); vm.toggleStar(t.id, false) }
- } else {
- item("Star", Icons.Outlined.Star) { onClose(); vm.toggleStar(t.id, true) }
- }
- if (vm.folder == ListFolder.Inbox || vm.folder == ListFolder.Starred) {
- if (t.unread > 0) {
- item("Mark as read", Icons.Outlined.MarkEmailRead) { onClose(); vm.toggleRead(t) }
- } else {
- item("Mark as unread", Icons.Outlined.MarkEmailUnread) { onClose(); vm.toggleRead(t) }
- }
- }
- item("Move to Bin", Icons.Outlined.Delete, danger = true) { onClose(); vm.moveToBin(t.id) }
- }
- }
- }
- }
-}
-
-@Composable
-private fun Drawer(vm: MailViewModel, close: () -> Unit) {
- val context = LocalContext.current
- val me = vm.me
- val inboxUnread = vm.unread.values.sum()
-
- @Composable
- fun entry(label: String, icon: ImageVector, selected: Boolean, badge: Int = 0, indent: Boolean = false, onClick: () -> Unit) {
- NavigationDrawerItem(
- label = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) },
- icon = { Icon(icon, null) },
- selected = selected,
- badge = if (badge > 0) ({ Badge { Text("$badge") } }) else null,
- onClick = { close(); onClick() },
- modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding).padding(start = if (indent) 24.dp else 0.dp),
- )
- }
-
- ModalDrawerSheet {
- Column(Modifier.verticalScroll(rememberScrollState()).padding(vertical = 12.dp)) {
- Row(Modifier.padding(horizontal = 24.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) {
- AccountPicture(me, 40.dp)
- Spacer(Modifier.width(12.dp))
- Column {
- Text(me?.name ?: me?.username ?: "Inbox", style = MaterialTheme.typography.titleMedium)
- me?.addresses?.firstOrNull()?.let { Text(it, style = MaterialTheme.typography.labelMedium, color = Muted) }
- }
- }
- HorizontalDivider(Modifier.padding(vertical = 8.dp))
- for (f in ListFolder.entries) {
- entry(
- f.label,
- folderIcons.getValue(f),
- selected = vm.folder == f,
- badge = if (f == ListFolder.Inbox) inboxUnread else 0,
- ) { vm.show(f) }
- }
-
- if (me != null && me.addresses.size > 1) {
- HorizontalDivider(Modifier.padding(vertical = 8.dp))
- entry("All addresses", Icons.Outlined.AllInbox, selected = vm.mailbox == null) { vm.show(vm.folder, null) }
- for (domain in me.domains) {
- val addrs = me.addresses.filter { it.endsWith("@$domain") }
- entry(
- domain,
- Icons.Outlined.Language,
- selected = vm.mailbox == "@$domain",
- badge = addrs.sumOf { vm.unread[it] ?: 0 },
- ) { vm.show(vm.folder, "@$domain") }
- if (addrs.size > 1) {
- for (addr in addrs) {
- entry(
- addr.substringBefore("@"),
- Icons.Outlined.AlternateEmail,
- selected = vm.mailbox == addr,
- badge = vm.unread[addr] ?: 0,
- indent = true,
- ) { vm.show(vm.folder, addr) }
- }
- }
- }
- }
-
- HorizontalDivider(Modifier.padding(vertical = 8.dp))
- entry("Settings", Icons.Outlined.Settings, selected = false) { vm.openSettings() }
- if (me?.isAdmin == true) {
- // Admin stays on the web; it's rarely needed and not worth a second copy.
- entry("Admin (web)", Icons.Outlined.Shield, selected = false) {
- CustomTabsIntent.Builder().build()
- .launchUrl(context, Uri.parse("${gay.doughmination.mail.BuildConfig.INBOX_URL}/admin"))
- }
- }
- }
- }
-}
diff --git a/app/app/src/main/java/gay/doughmination/mail/ui/ThreadScreen.kt b/app/app/src/main/java/gay/doughmination/mail/ui/ThreadScreen.kt
deleted file mode 100644
index c18a0d7..0000000
--- a/app/app/src/main/java/gay/doughmination/mail/ui/ThreadScreen.kt
+++ /dev/null
@@ -1,272 +0,0 @@
-package gay.doughmination.mail.ui
-
-import android.app.DownloadManager
-import android.content.Context
-import android.net.Uri
-import android.os.Build
-import android.os.Environment
-import android.widget.Toast
-import androidx.compose.foundation.clickable
-import androidx.compose.foundation.horizontalScroll
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.PaddingValues
-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.height
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.layout.width
-import androidx.compose.foundation.lazy.LazyColumn
-import androidx.compose.foundation.lazy.items
-import androidx.compose.foundation.rememberScrollState
-import androidx.compose.foundation.text.selection.SelectionContainer
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.automirrored.outlined.ArrowBack
-import androidx.compose.material.icons.automirrored.outlined.Forward
-import androidx.compose.material.icons.automirrored.outlined.Reply
-import androidx.compose.material.icons.filled.Star
-import androidx.compose.material.icons.outlined.AttachFile
-import androidx.compose.material.icons.outlined.Delete
-import androidx.compose.material.icons.outlined.DeleteForever
-import androidx.compose.material.icons.outlined.Edit
-import androidx.compose.material.icons.outlined.Image
-import androidx.compose.material.icons.outlined.MarkEmailUnread
-import androidx.compose.material.icons.outlined.RestoreFromTrash
-import androidx.compose.material.icons.outlined.StarOutline
-import androidx.compose.material3.AssistChip
-import androidx.compose.material3.Card
-import androidx.compose.material3.CardDefaults
-import androidx.compose.material3.CircularProgressIndicator
-import androidx.compose.material3.ExperimentalMaterial3Api
-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.SnackbarHost
-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.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-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.text.font.FontWeight
-import androidx.compose.ui.text.style.TextOverflow
-import androidx.compose.ui.unit.dp
-import gay.doughmination.mail.InboxApp
-import gay.doughmination.mail.data.Api
-import gay.doughmination.mail.data.AttachmentInfo
-import gay.doughmination.mail.data.Message
-
-@OptIn(ExperimentalMaterial3Api::class)
-@Composable
-fun ThreadScreen(vm: MailViewModel, screen: Screen.Thread) {
- LaunchedEffect(screen, vm.threadVersion) { vm.loadThread(screen.id, screen.bin) }
- val thread = vm.thread?.takeIf { it.id == screen.id }
- var confirmDelete by remember { mutableStateOf(false) }
-
- Scaffold(
- topBar = {
- TopAppBar(
- title = {},
- navigationIcon = {
- IconButton(onClick = { vm.back() }) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, "Back") }
- },
- actions = {
- if (thread == null) return@TopAppBar
- if (screen.bin) {
- IconButton(onClick = { vm.restore(thread.id) }) {
- Icon(Icons.Outlined.RestoreFromTrash, "Restore")
- }
- IconButton(onClick = { if (confirmDelete) vm.deleteForever(thread.id) else confirmDelete = true }) {
- Icon(Icons.Outlined.DeleteForever, if (confirmDelete) "Tap again to delete forever" else "Delete forever", tint = if (confirmDelete) Danger else Muted)
- }
- } else {
- IconButton(onClick = { vm.toggleStar(thread.id, !thread.starred) }) {
- if (thread.starred) Icon(Icons.Filled.Star, "Unstar", tint = StarYellow)
- else Icon(Icons.Outlined.StarOutline, "Star")
- }
- if (thread.messages.any { it.folder == "inbox" }) {
- IconButton(onClick = { vm.markUnread(thread.id) }) {
- Icon(Icons.Outlined.MarkEmailUnread, "Mark as unread")
- }
- }
- IconButton(onClick = { vm.moveToBin(thread.id) }) { Icon(Icons.Outlined.Delete, "Move to Bin") }
- }
- },
- )
- },
- snackbarHost = { SnackbarHost(LocalSnackbar.current) },
- ) { padding ->
- when {
- thread != null -> LazyColumn(
- Modifier.padding(padding).fillMaxSize(),
- contentPadding = PaddingValues(12.dp),
- verticalArrangement = Arrangement.spacedBy(10.dp),
- ) {
- item {
- Text(
- thread.subject.ifEmpty { "(no subject)" },
- Modifier.padding(horizontal = 4.dp, vertical = 4.dp),
- style = MaterialTheme.typography.headlineSmall,
- )
- }
- val newest = thread.messages.lastOrNull()?.id
- items(thread.messages, key = { it.id }) { m ->
- MessageCard(vm, m, screen.bin, startOpen = m.id == newest || !m.read)
- }
- }
- vm.threadError != null -> Column(
- Modifier.padding(padding).fillMaxSize(),
- verticalArrangement = Arrangement.Center,
- horizontalAlignment = Alignment.CenterHorizontally,
- ) {
- Text(vm.threadError!!, color = Muted)
- TextButton(onClick = { vm.back() }) { Text("Go back") }
- }
- else -> Column(
- Modifier.padding(padding).fillMaxSize(),
- verticalArrangement = Arrangement.Center,
- horizontalAlignment = Alignment.CenterHorizontally,
- ) { CircularProgressIndicator() }
- }
- }
-}
-
-@Composable
-private fun MessageCard(vm: MailViewModel, m: Message, bin: Boolean, startOpen: Boolean) {
- val api = (LocalContext.current.applicationContext as InboxApp).api
- var open by rememberSaveable(m.id) { mutableStateOf(startOpen) }
- var showRemote by rememberSaveable(m.id) { mutableStateOf(false) }
- var confirmDelete by remember { mutableStateOf(false) }
- val isDraft = m.folder == "drafts"
-
- Card(
- colors = CardDefaults.cardColors(containerColor = Raised),
- modifier = Modifier.fillMaxWidth(),
- ) {
- Column(Modifier.clickable { open = !open }.padding(14.dp)) {
- Row(verticalAlignment = Alignment.CenterVertically) {
- Text(
- if (isDraft) "Draft" else displayName(m.from),
- Modifier.weight(1f),
- fontWeight = FontWeight.SemiBold,
- color = if (isDraft) Danger else MaterialTheme.colorScheme.onSurface,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- )
- Text(fmtTime(m.sentAt), style = MaterialTheme.typography.labelMedium, color = Muted)
- }
- if (!open) {
- Text(m.snippet, color = Muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
- } else {
- Text(bareAddress(m.from), style = MaterialTheme.typography.labelMedium, color = Muted)
- if (m.to.isNotEmpty()) Text("To: ${m.to.joinToString(", ")}", style = MaterialTheme.typography.labelMedium, color = Muted)
- if (m.cc.isNotEmpty()) Text("Cc: ${m.cc.joinToString(", ")}", style = MaterialTheme.typography.labelMedium, color = Muted)
- if (m.bcc.isNotEmpty()) Text("Bcc: ${m.bcc.joinToString(", ")}", style = MaterialTheme.typography.labelMedium, color = Muted)
- }
- }
- if (!open) return@Card
-
- val html = m.html
- if (html != null) {
- if (hasRemoteContent(html) && !showRemote) {
- OutlinedButton(onClick = { showRemote = true }, Modifier.padding(horizontal = 14.dp)) {
- Icon(Icons.Outlined.Image, null)
- Spacer(Modifier.width(6.dp))
- Text("Load remote images")
- }
- Spacer(Modifier.height(8.dp))
- }
- EmailView(api, html, m.attachments, showRemote, Modifier.fillMaxWidth())
- } else {
- SelectionContainer {
- Text(m.text.orEmpty(), Modifier.padding(horizontal = 14.dp))
- }
- }
-
- val files = m.attachments.filter { it.contentId == null || html == null }
- if (files.isNotEmpty()) {
- Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 14.dp, vertical = 8.dp)) {
- val context = LocalContext.current
- for (a in files) {
- AssistChip(
- onClick = { download(context, api, a) },
- label = { Text("${a.filename} · ${fmtSize(a.size)}", maxLines = 1) },
- leadingIcon = { Icon(Icons.Outlined.AttachFile, null) },
- modifier = Modifier.padding(end = 8.dp),
- )
- }
- }
- }
-
- Row(Modifier.padding(horizontal = 4.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
- if (isDraft && !bin) {
- TextButton(onClick = { vm.composeDraft(m) }) {
- Icon(Icons.Outlined.Edit, null)
- Spacer(Modifier.width(6.dp))
- Text("Edit")
- }
- } else if (!bin) {
- TextButton(onClick = { vm.composeReply(m) }) {
- Icon(Icons.AutoMirrored.Outlined.Reply, null)
- Spacer(Modifier.width(6.dp))
- Text("Reply")
- }
- TextButton(onClick = { vm.composeForward(m) }) {
- Icon(Icons.AutoMirrored.Outlined.Forward, null)
- Spacer(Modifier.width(6.dp))
- Text("Forward")
- }
- }
- Spacer(Modifier.weight(1f))
- if (bin) {
- IconButton(onClick = { vm.restoreMessage(m) }) { Icon(Icons.Outlined.RestoreFromTrash, "Restore this message") }
- }
- IconButton(onClick = {
- if (!bin && !isDraft) vm.deleteMessage(m, bin)
- else if (confirmDelete) vm.deleteMessage(m, bin)
- else confirmDelete = true
- }) {
- Icon(
- Icons.Outlined.Delete,
- when {
- confirmDelete -> "Tap again to delete forever"
- bin || isDraft -> "Delete forever"
- else -> "Move to Bin"
- },
- tint = if (confirmDelete) Danger else Muted,
- )
- }
- }
- }
-}
-
-/** Saves an attachment to Downloads, with the system's own progress notification. */
-private fun download(context: Context, api: Api, a: AttachmentInfo) {
- val name = a.filename.replace('/', '_')
- val request = DownloadManager.Request(Uri.parse(api.attachmentUrl(a.id)))
- .setTitle(a.filename)
- .setMimeType(a.contentType)
- .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
- // Public Downloads needs a storage permission before Android 10; earlier
- // versions keep it in the app's own folder, still opened from the notification.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
- request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name)
- } else {
- request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, name)
- }
- api.authorize(okhttp3.Request.Builder().url(api.attachmentUrl(a.id))).build()
- .header("Authorization")?.let { request.addRequestHeader("Authorization", it) }
- (context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager).enqueue(request)
- Toast.makeText(context, "Downloading ${a.filename}", Toast.LENGTH_SHORT).show()
-}
diff --git a/app/app/src/main/res/drawable-nodpi/background.webp b/app/app/src/main/res/drawable-nodpi/background.webp
deleted file mode 100644
index 1f56761..0000000
Binary files a/app/app/src/main/res/drawable-nodpi/background.webp and /dev/null differ
diff --git a/app/app/src/main/res/drawable/ic_launcher_background.xml b/app/app/src/main/res/drawable/ic_launcher_background.xml
deleted file mode 100644
index e392302..0000000
--- a/app/app/src/main/res/drawable/ic_launcher_background.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Blush from the mascot's palette: light, so its dark outlines read. -->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="108dp"
- android:height="108dp"
- android:viewportWidth="108"
- android:viewportHeight="108">
- <path
- android:fillColor="@color/icon_background"
- android:pathData="M0,0h108v108h-108z" />
-</vector>
diff --git a/app/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/app/src/main/res/drawable/ic_launcher_foreground.xml
deleted file mode 100644
index 8a446ba..0000000
--- a/app/app/src/main/res/drawable/ic_launcher_foreground.xml
+++ /dev/null
@@ -1,168 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- The Doughmination mascot from email/public/icon.svg, made by
- converting it and fitting it inside the 72dp circle a launcher's mask (and
- the splash screen's) always shows. The doughnut's hole is the clip-path:
- the outer square runs clockwise and the hole anticlockwise, so it cuts out. -->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="108dp"
- android:height="108dp"
- android:viewportWidth="108"
- android:viewportHeight="108">
- <group android:scaleX="0.123" android:scaleY="0.123" android:translateX="22.072" android:translateY="21.09">
- <path
- android:pathData="M256 300V380"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="32"
- android:strokeLineCap="round" />
- <path
- android:pathData="M256 300V380"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="16"
- android:strokeLineCap="round" />
- <path
- android:pathData="M194,380h124a14,14 0 0 1 14,14v76a14,14 0 0 1 -14,14h-124a14,14 0 0 1 -14,-14v-76a14,14 0 0 1 14,-14z"
- android:fillColor="#FF383DCD"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="10" />
- <path
- android:pathData="M196 398L256 442L316 398"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="22"
- android:strokeLineCap="round"
- android:strokeLineJoin="round" />
- <path
- android:pathData="M196 398L256 442L316 398"
- android:strokeColor="#FFF1E4EA"
- android:strokeWidth="10"
- android:strokeLineCap="round"
- android:strokeLineJoin="round" />
- <group android:translateX="256" android:translateY="192">
- <group android:scaleX="0.72" android:scaleY="0.72">
- <group android:translateX="-256" android:translateY="-250">
- <path
- android:pathData="M140 170 C80 120 20 100 -36 96 C-14 134 -18 168 -34 198 C2 186 22 206 18 246 C46 226 74 238 80 282 C100 262 124 266 140 286 Z"
- android:fillColor="#FF1C1F42"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="12"
- android:strokeLineJoin="round" />
- <path
- android:pathData="M 372 170 C 432 120 492 100 548 96 C 526 134 530 168 546 198 C 510 186 490 206 494 246 C 466 226 438 238 432 282 C 412 262 388 266 372 286 Z"
- android:fillColor="#FF1C1F42"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="12"
- android:strokeLineJoin="round" />
- <path
- android:pathData="M128 182 C70 140 10 118 -26 108"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="6"
- android:strokeLineCap="round" />
- <path
- android:pathData="M384 182 C442 140 502 118 538 108"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="6"
- android:strokeLineCap="round" />
- <group>
- <clip-path android:pathData="M0 0H512V512H0Z M198 250a58 58 0 1 0 116 0a58 58 0 1 0 -116 0Z" />
- <path
- android:pathData="M76,260a180,180 0 1 1 360,0a180,180 0 1 1 -360,0z"
- android:fillColor="#FF0B0C1C" />
- <path
- android:pathData="M76,250a180,180 0 1 1 360,0a180,180 0 1 1 -360,0z"
- android:fillColor="#FF0B0C1C" />
- <path
- android:pathData="M86,260a170,170 0 1 1 340,0a170,170 0 1 1 -340,0z"
- android:fillColor="#FF565B9D" />
- <path
- android:pathData="M86,250a170,170 0 1 1 340,0a170,170 0 1 1 -340,0z"
- android:fillColor="#FF929CC0" />
- <group android:translateX="0" android:translateY="8">
- <path
- android:pathData="M394 250 L395 254 L395 257 L396 261 L396 265 L396 268 L395 272 L394 276 L393 279 L392 283 L390 286 L388 289 L386 292 L384 295 L382 298 L380 301 L378 304 L375 307 L373 310 L371 313 L369 316 L368 318 L366 321 L365 325 L363 328 L362 332 L363 337 L368 345 L375 357 L375 363 L364 358 L356 355 L351 355 L347 357 L345 359 L342 362 L339 364 L336 366 L332 368 L329 369 L326 371 L323 373 L320 376 L319 382 L320 394 L322 408 L320 417 L311 405 L302 392 L296 384 L291 380 L287 378 L283 379 L280 379 L277 381 L273 382 L270 383 L267 384 L263 386 L260 388 L256 394 L252 404 L247 413 L244 403 L241 394 L237 391 L234 389 L230 388 L227 387 L223 386 L220 384 L217 382 L214 381 L210 379 L207 378 L203 379 L196 385 L186 398 L174 411 L173 403 L179 384 L182 370 L183 363 L181 359 L178 357 L175 356 L172 354 L168 353 L165 351 L162 349 L158 348 L155 346 L151 345 L145 345 L135 348 L121 354 L118 350 L127 338 L134 330 L135 324 L135 320 L135 316 L134 312 L133 309 L133 305 L132 301 L132 298 L131 294 L129 291 L125 289 L114 288 L108 285 L117 279 L123 275 L125 271 L124 267 L123 264 L122 261 L120 257 L119 254 L118 250 L117 246 L117 243 L116 239 L116 235 L116 232 L117 228 L118 224 L119 221 L120 217 L122 214 L124 211 L126 208 L128 205 L130 202 L132 199 L134 196 L137 193 L139 190 L141 187 L143 184 L144 182 L146 179 L148 175 L149 172 L150 169 L152 166 L153 162 L155 159 L157 156 L158 152 L160 149 L163 146 L165 143 L167 141 L170 138 L173 136 L176 134 L180 132 L183 131 L186 130 L190 129 L194 128 L197 127 L201 127 L205 126 L208 126 L212 125 L215 125 L219 124 L222 123 L225 123 L229 122 L232 121 L235 119 L239 118 L242 117 L245 116 L249 114 L252 113 L256 112 L260 111 L263 111 L267 110 L271 110 L274 110 L278 111 L282 112 L285 113 L289 114 L292 116 L295 118 L298 120 L301 122 L304 124 L307 126 L310 128 L313 131 L316 133 L319 135 L322 137 L324 138 L327 140 L331 142 L334 143 L337 144 L340 146 L344 147 L347 149 L350 151 L354 152 L357 154 L360 157 L363 159 L365 161 L368 164 L370 167 L372 170 L374 174 L375 177 L376 180 L377 184 L378 188 L379 191 L379 195 L380 199 L380 202 L381 206 L381 209 L382 213 L383 216 L383 219 L384 223 L385 226 L387 229 L388 233 L389 236 L390 239 L392 243 L393 246Z"
- android:fillColor="#FF0B0C1C" />
- </group>
- <path
- android:pathData="M394 250 L395 254 L395 257 L396 261 L396 265 L396 268 L395 272 L394 276 L393 279 L392 283 L390 286 L388 289 L386 292 L384 295 L382 298 L380 301 L378 304 L375 307 L373 310 L371 313 L369 316 L368 318 L366 321 L365 325 L363 328 L362 332 L363 337 L368 345 L375 357 L375 363 L364 358 L356 355 L351 355 L347 357 L345 359 L342 362 L339 364 L336 366 L332 368 L329 369 L326 371 L323 373 L320 376 L319 382 L320 394 L322 408 L320 417 L311 405 L302 392 L296 384 L291 380 L287 378 L283 379 L280 379 L277 381 L273 382 L270 383 L267 384 L263 386 L260 388 L256 394 L252 404 L247 413 L244 403 L241 394 L237 391 L234 389 L230 388 L227 387 L223 386 L220 384 L217 382 L214 381 L210 379 L207 378 L203 379 L196 385 L186 398 L174 411 L173 403 L179 384 L182 370 L183 363 L181 359 L178 357 L175 356 L172 354 L168 353 L165 351 L162 349 L158 348 L155 346 L151 345 L145 345 L135 348 L121 354 L118 350 L127 338 L134 330 L135 324 L135 320 L135 316 L134 312 L133 309 L133 305 L132 301 L132 298 L131 294 L129 291 L125 289 L114 288 L108 285 L117 279 L123 275 L125 271 L124 267 L123 264 L122 261 L120 257 L119 254 L118 250 L117 246 L117 243 L116 239 L116 235 L116 232 L117 228 L118 224 L119 221 L120 217 L122 214 L124 211 L126 208 L128 205 L130 202 L132 199 L134 196 L137 193 L139 190 L141 187 L143 184 L144 182 L146 179 L148 175 L149 172 L150 169 L152 166 L153 162 L155 159 L157 156 L158 152 L160 149 L163 146 L165 143 L167 141 L170 138 L173 136 L176 134 L180 132 L183 131 L186 130 L190 129 L194 128 L197 127 L201 127 L205 126 L208 126 L212 125 L215 125 L219 124 L222 123 L225 123 L229 122 L232 121 L235 119 L239 118 L242 117 L245 116 L249 114 L252 113 L256 112 L260 111 L263 111 L267 110 L271 110 L274 110 L278 111 L282 112 L285 113 L289 114 L292 116 L295 118 L298 120 L301 122 L304 124 L307 126 L310 128 L313 131 L316 133 L319 135 L322 137 L324 138 L327 140 L331 142 L334 143 L337 144 L340 146 L344 147 L347 149 L350 151 L354 152 L357 154 L360 157 L363 159 L365 161 L368 164 L370 167 L372 170 L374 174 L375 177 L376 180 L377 184 L378 188 L379 191 L379 195 L380 199 L380 202 L381 206 L381 209 L382 213 L383 216 L383 219 L384 223 L385 226 L387 229 L388 233 L389 236 L390 239 L392 243 L393 246Z"
- android:fillColor="#FF1C1F42" />
- <path
- android:pathData="M150 196 A118 118 0 0 1 238 134"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="12"
- android:strokeLineCap="round" />
- <path
- android:pathData="M330 159C331.7 174.3 331.7 174.3 340.2 176C331.7 177.7 331.7 177.7 330 187.9C328.3 177.7 328.3 177.7 319.8 176C328.3 174.3 328.3 174.3 330 159Z"
- android:fillColor="#FFCFD7F3" />
- <group android:rotation="-50" android:pivotX="356" android:pivotY="262">
- <path
- android:pathData="M346,258h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FF7491CE" />
- </group>
- <path
- android:pathData="M300 319C301.7 334.3 301.7 334.3 310.2 336C301.7 337.7 301.7 337.7 300 347.9C298.3 337.7 298.3 337.7 289.8 336C298.3 334.3 298.3 334.3 300 319Z"
- android:fillColor="#FFF1E4EA" />
- <group android:rotation="20" android:pivotX="212" android:pivotY="338">
- <path
- android:pathData="M202,334h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FF7491CE" />
- </group>
- <path
- android:pathData="M162 265C163.7 280.3 163.7 280.3 172.2 282C163.7 283.7 163.7 283.7 162 293.9C160.3 283.7 160.3 283.7 151.8 282C160.3 280.3 160.3 280.3 162 265Z"
- android:fillColor="#FFCFD7F3" />
- <group android:rotation="40" android:pivotX="168" android:pivotY="198">
- <path
- android:pathData="M158,194h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FFF1E4EA" />
- </group>
- <path
- android:pathData="M232 133C233.7 148.3 233.7 148.3 242.2 150C233.7 151.7 233.7 151.7 232 161.9C230.3 151.7 230.3 151.7 221.8 150C230.3 148.3 230.3 148.3 232 133Z"
- android:fillColor="#FF7491CE" />
- <group android:rotation="60" android:pivotX="292" android:pivotY="146">
- <path
- android:pathData="M282,142h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FFF1E4EA" />
- </group>
- <group android:rotation="95" android:pivotX="150" android:pivotY="236">
- <path
- android:pathData="M140,232h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FF7491CE" />
- </group>
- <group android:rotation="-30" android:pivotX="372" android:pivotY="212">
- <path
- android:pathData="M362,208h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FFCFD7F3" />
- </group>
- </group>
- <path
- android:pathData="M193,250a63,63 0 1 1 126,0a63,63 0 1 1 -126,0z"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="10" />
- <path
- android:pathData="M198,250a58,58 0 1 1 116,0a58,58 0 1 1 -116,0z"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="6" />
- </group>
- </group>
- </group>
- <group android:translateX="40" android:translateY="0">
- <group android:rotation="-25" android:pivotX="404" android:pivotY="420">
- <path
- android:pathData="M404 370A50 50 0 1 0 404 470A65 65 0 0 1 404 370Z"
- android:fillColor="#FFCFD7F3"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="10"
- android:strokeLineJoin="round" />
- </group>
- </group>
- <path
- android:pathData="M92 368C95.96 408.04 95.96 408.04 118.4 412C95.96 415.96 95.96 415.96 92 442.8C88.04 415.96 88.04 415.96 65.6 412C88.04 408.04 88.04 408.04 92 368Z"
- android:fillColor="#FF7491CE"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="8"
- android:strokeLineJoin="round" />
- <path
- android:pathData="M464 288C467.0 315.0 467.0 315.0 482 318C467.0 321.0 467.0 321.0 464 339C461.0 321.0 461.0 321.0 446 318C461.0 315.0 461.0 315.0 464 288Z"
- android:fillColor="#FFF1E4EA"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="6"
- android:strokeLineJoin="round" />
- </group>
-</vector>
diff --git a/app/app/src/main/res/drawable/ic_notification.xml b/app/app/src/main/res/drawable/ic_notification.xml
deleted file mode 100644
index aa39160..0000000
--- a/app/app/src/main/res/drawable/ic_notification.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Status bar icon: a plain white envelope (Android only uses the alpha). -->
-<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="M4,4h16c1.1,0 2,0.9 2,2v12c0,1.1 -0.9,2 -2,2H4c-1.1,0 -2,-0.9 -2,-2V6c0,-1.1 0.9,-2 2,-2zM20,8l-8,5 -8,-5v-2l8,5 8,-5z" />
-</vector>
diff --git a/app/app/src/main/res/drawable/ic_splash.xml b/app/app/src/main/res/drawable/ic_splash.xml
deleted file mode 100644
index b919d7c..0000000
--- a/app/app/src/main/res/drawable/ic_splash.xml
+++ /dev/null
@@ -1,190 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- ic_launcher_foreground, with the parts the splash animates (the whole
- mascot, its wings and the envelope) in named groups. The envelope starts
- see-through: it drops in once the mascot is up. See ic_splash_animated. -->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="108dp"
- android:height="108dp"
- android:viewportWidth="108"
- android:viewportHeight="108">
- <group android:scaleX="0.123" android:scaleY="0.123" android:translateX="22.072" android:translateY="21.09">
- <group android:name="mascot" android:pivotX="260" android:pivotY="268">
- <group android:name="envelope" android:pivotX="256" android:pivotY="300">
- <path
- android:name="envelope_0"
- android:pathData="M256 300V380"
- android:fillAlpha="0"
- android:strokeAlpha="0"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="32"
- android:strokeLineCap="round" />
- <path
- android:name="envelope_1"
- android:pathData="M256 300V380"
- android:fillAlpha="0"
- android:strokeAlpha="0"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="16"
- android:strokeLineCap="round" />
- <path
- android:name="envelope_2"
- android:pathData="M194,380h124a14,14 0 0 1 14,14v76a14,14 0 0 1 -14,14h-124a14,14 0 0 1 -14,-14v-76a14,14 0 0 1 14,-14z"
- android:fillAlpha="0"
- android:strokeAlpha="0"
- android:fillColor="#FF383DCD"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="10" />
- <path
- android:name="envelope_3"
- android:pathData="M196 398L256 442L316 398"
- android:fillAlpha="0"
- android:strokeAlpha="0"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="22"
- android:strokeLineCap="round"
- android:strokeLineJoin="round" />
- <path
- android:name="envelope_4"
- android:pathData="M196 398L256 442L316 398"
- android:fillAlpha="0"
- android:strokeAlpha="0"
- android:strokeColor="#FFF1E4EA"
- android:strokeWidth="10"
- android:strokeLineCap="round"
- android:strokeLineJoin="round" />
- </group>
- <group android:translateX="256" android:translateY="192">
- <group android:scaleX="0.72" android:scaleY="0.72">
- <group android:translateX="-256" android:translateY="-250">
- <group android:name="wing_left" android:pivotX="140" android:pivotY="228">
- <path
- android:pathData="M140 170 C80 120 20 100 -36 96 C-14 134 -18 168 -34 198 C2 186 22 206 18 246 C46 226 74 238 80 282 C100 262 124 266 140 286 Z"
- android:fillColor="#FF1C1F42"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="12"
- android:strokeLineJoin="round" />
- <path
- android:pathData="M128 182 C70 140 10 118 -26 108"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="6"
- android:strokeLineCap="round" />
- </group>
- <group android:name="wing_right" android:pivotX="372" android:pivotY="228">
- <path
- android:pathData="M 372 170 C 432 120 492 100 548 96 C 526 134 530 168 546 198 C 510 186 490 206 494 246 C 466 226 438 238 432 282 C 412 262 388 266 372 286 Z"
- android:fillColor="#FF1C1F42"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="12"
- android:strokeLineJoin="round" />
- <path
- android:pathData="M384 182 C442 140 502 118 538 108"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="6"
- android:strokeLineCap="round" />
- </group>
- <group>
- <clip-path android:pathData="M0 0H512V512H0Z M198 250a58 58 0 1 0 116 0a58 58 0 1 0 -116 0Z" />
- <path
- android:pathData="M76,260a180,180 0 1 1 360,0a180,180 0 1 1 -360,0z"
- android:fillColor="#FF0B0C1C" />
- <path
- android:pathData="M76,250a180,180 0 1 1 360,0a180,180 0 1 1 -360,0z"
- android:fillColor="#FF0B0C1C" />
- <path
- android:pathData="M86,260a170,170 0 1 1 340,0a170,170 0 1 1 -340,0z"
- android:fillColor="#FF565B9D" />
- <path
- android:pathData="M86,250a170,170 0 1 1 340,0a170,170 0 1 1 -340,0z"
- android:fillColor="#FF929CC0" />
- <group android:translateX="0" android:translateY="8">
- <path
- android:pathData="M394 250 L395 254 L395 257 L396 261 L396 265 L396 268 L395 272 L394 276 L393 279 L392 283 L390 286 L388 289 L386 292 L384 295 L382 298 L380 301 L378 304 L375 307 L373 310 L371 313 L369 316 L368 318 L366 321 L365 325 L363 328 L362 332 L363 337 L368 345 L375 357 L375 363 L364 358 L356 355 L351 355 L347 357 L345 359 L342 362 L339 364 L336 366 L332 368 L329 369 L326 371 L323 373 L320 376 L319 382 L320 394 L322 408 L320 417 L311 405 L302 392 L296 384 L291 380 L287 378 L283 379 L280 379 L277 381 L273 382 L270 383 L267 384 L263 386 L260 388 L256 394 L252 404 L247 413 L244 403 L241 394 L237 391 L234 389 L230 388 L227 387 L223 386 L220 384 L217 382 L214 381 L210 379 L207 378 L203 379 L196 385 L186 398 L174 411 L173 403 L179 384 L182 370 L183 363 L181 359 L178 357 L175 356 L172 354 L168 353 L165 351 L162 349 L158 348 L155 346 L151 345 L145 345 L135 348 L121 354 L118 350 L127 338 L134 330 L135 324 L135 320 L135 316 L134 312 L133 309 L133 305 L132 301 L132 298 L131 294 L129 291 L125 289 L114 288 L108 285 L117 279 L123 275 L125 271 L124 267 L123 264 L122 261 L120 257 L119 254 L118 250 L117 246 L117 243 L116 239 L116 235 L116 232 L117 228 L118 224 L119 221 L120 217 L122 214 L124 211 L126 208 L128 205 L130 202 L132 199 L134 196 L137 193 L139 190 L141 187 L143 184 L144 182 L146 179 L148 175 L149 172 L150 169 L152 166 L153 162 L155 159 L157 156 L158 152 L160 149 L163 146 L165 143 L167 141 L170 138 L173 136 L176 134 L180 132 L183 131 L186 130 L190 129 L194 128 L197 127 L201 127 L205 126 L208 126 L212 125 L215 125 L219 124 L222 123 L225 123 L229 122 L232 121 L235 119 L239 118 L242 117 L245 116 L249 114 L252 113 L256 112 L260 111 L263 111 L267 110 L271 110 L274 110 L278 111 L282 112 L285 113 L289 114 L292 116 L295 118 L298 120 L301 122 L304 124 L307 126 L310 128 L313 131 L316 133 L319 135 L322 137 L324 138 L327 140 L331 142 L334 143 L337 144 L340 146 L344 147 L347 149 L350 151 L354 152 L357 154 L360 157 L363 159 L365 161 L368 164 L370 167 L372 170 L374 174 L375 177 L376 180 L377 184 L378 188 L379 191 L379 195 L380 199 L380 202 L381 206 L381 209 L382 213 L383 216 L383 219 L384 223 L385 226 L387 229 L388 233 L389 236 L390 239 L392 243 L393 246Z"
- android:fillColor="#FF0B0C1C" />
- </group>
- <path
- android:pathData="M394 250 L395 254 L395 257 L396 261 L396 265 L396 268 L395 272 L394 276 L393 279 L392 283 L390 286 L388 289 L386 292 L384 295 L382 298 L380 301 L378 304 L375 307 L373 310 L371 313 L369 316 L368 318 L366 321 L365 325 L363 328 L362 332 L363 337 L368 345 L375 357 L375 363 L364 358 L356 355 L351 355 L347 357 L345 359 L342 362 L339 364 L336 366 L332 368 L329 369 L326 371 L323 373 L320 376 L319 382 L320 394 L322 408 L320 417 L311 405 L302 392 L296 384 L291 380 L287 378 L283 379 L280 379 L277 381 L273 382 L270 383 L267 384 L263 386 L260 388 L256 394 L252 404 L247 413 L244 403 L241 394 L237 391 L234 389 L230 388 L227 387 L223 386 L220 384 L217 382 L214 381 L210 379 L207 378 L203 379 L196 385 L186 398 L174 411 L173 403 L179 384 L182 370 L183 363 L181 359 L178 357 L175 356 L172 354 L168 353 L165 351 L162 349 L158 348 L155 346 L151 345 L145 345 L135 348 L121 354 L118 350 L127 338 L134 330 L135 324 L135 320 L135 316 L134 312 L133 309 L133 305 L132 301 L132 298 L131 294 L129 291 L125 289 L114 288 L108 285 L117 279 L123 275 L125 271 L124 267 L123 264 L122 261 L120 257 L119 254 L118 250 L117 246 L117 243 L116 239 L116 235 L116 232 L117 228 L118 224 L119 221 L120 217 L122 214 L124 211 L126 208 L128 205 L130 202 L132 199 L134 196 L137 193 L139 190 L141 187 L143 184 L144 182 L146 179 L148 175 L149 172 L150 169 L152 166 L153 162 L155 159 L157 156 L158 152 L160 149 L163 146 L165 143 L167 141 L170 138 L173 136 L176 134 L180 132 L183 131 L186 130 L190 129 L194 128 L197 127 L201 127 L205 126 L208 126 L212 125 L215 125 L219 124 L222 123 L225 123 L229 122 L232 121 L235 119 L239 118 L242 117 L245 116 L249 114 L252 113 L256 112 L260 111 L263 111 L267 110 L271 110 L274 110 L278 111 L282 112 L285 113 L289 114 L292 116 L295 118 L298 120 L301 122 L304 124 L307 126 L310 128 L313 131 L316 133 L319 135 L322 137 L324 138 L327 140 L331 142 L334 143 L337 144 L340 146 L344 147 L347 149 L350 151 L354 152 L357 154 L360 157 L363 159 L365 161 L368 164 L370 167 L372 170 L374 174 L375 177 L376 180 L377 184 L378 188 L379 191 L379 195 L380 199 L380 202 L381 206 L381 209 L382 213 L383 216 L383 219 L384 223 L385 226 L387 229 L388 233 L389 236 L390 239 L392 243 L393 246Z"
- android:fillColor="#FF1C1F42" />
- <path
- android:pathData="M150 196 A118 118 0 0 1 238 134"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="12"
- android:strokeLineCap="round" />
- <path
- android:pathData="M330 159C331.7 174.3 331.7 174.3 340.2 176C331.7 177.7 331.7 177.7 330 187.9C328.3 177.7 328.3 177.7 319.8 176C328.3 174.3 328.3 174.3 330 159Z"
- android:fillColor="#FFCFD7F3" />
- <group android:rotation="-50" android:pivotX="356" android:pivotY="262">
- <path
- android:pathData="M346,258h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FF7491CE" />
- </group>
- <path
- android:pathData="M300 319C301.7 334.3 301.7 334.3 310.2 336C301.7 337.7 301.7 337.7 300 347.9C298.3 337.7 298.3 337.7 289.8 336C298.3 334.3 298.3 334.3 300 319Z"
- android:fillColor="#FFF1E4EA" />
- <group android:rotation="20" android:pivotX="212" android:pivotY="338">
- <path
- android:pathData="M202,334h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FF7491CE" />
- </group>
- <path
- android:pathData="M162 265C163.7 280.3 163.7 280.3 172.2 282C163.7 283.7 163.7 283.7 162 293.9C160.3 283.7 160.3 283.7 151.8 282C160.3 280.3 160.3 280.3 162 265Z"
- android:fillColor="#FFCFD7F3" />
- <group android:rotation="40" android:pivotX="168" android:pivotY="198">
- <path
- android:pathData="M158,194h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FFF1E4EA" />
- </group>
- <path
- android:pathData="M232 133C233.7 148.3 233.7 148.3 242.2 150C233.7 151.7 233.7 151.7 232 161.9C230.3 151.7 230.3 151.7 221.8 150C230.3 148.3 230.3 148.3 232 133Z"
- android:fillColor="#FF7491CE" />
- <group android:rotation="60" android:pivotX="292" android:pivotY="146">
- <path
- android:pathData="M282,142h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FFF1E4EA" />
- </group>
- <group android:rotation="95" android:pivotX="150" android:pivotY="236">
- <path
- android:pathData="M140,232h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FF7491CE" />
- </group>
- <group android:rotation="-30" android:pivotX="372" android:pivotY="212">
- <path
- android:pathData="M362,208h20a4,4 0 0 1 4,4v0a4,4 0 0 1 -4,4h-20a4,4 0 0 1 -4,-4v-0a4,4 0 0 1 4,-4z"
- android:fillColor="#FFCFD7F3" />
- </group>
- </group>
- <path
- android:pathData="M193,250a63,63 0 1 1 126,0a63,63 0 1 1 -126,0z"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="10" />
- <path
- android:pathData="M198,250a58,58 0 1 1 116,0a58,58 0 1 1 -116,0z"
- android:strokeColor="#FF565B9D"
- android:strokeWidth="6" />
- </group>
- </group>
- </group>
- <group android:translateX="40" android:translateY="0">
- <group android:rotation="-25" android:pivotX="404" android:pivotY="420">
- <path
- android:pathData="M404 370A50 50 0 1 0 404 470A65 65 0 0 1 404 370Z"
- android:fillColor="#FFCFD7F3"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="10"
- android:strokeLineJoin="round" />
- </group>
- </group>
- <path
- android:pathData="M92 368C95.96 408.04 95.96 408.04 118.4 412C95.96 415.96 95.96 415.96 92 442.8C88.04 415.96 88.04 415.96 65.6 412C88.04 408.04 88.04 408.04 92 368Z"
- android:fillColor="#FF7491CE"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="8"
- android:strokeLineJoin="round" />
- <path
- android:pathData="M464 288C467.0 315.0 467.0 315.0 482 318C467.0 321.0 467.0 321.0 464 339C461.0 321.0 461.0 321.0 446 318C461.0 315.0 461.0 315.0 464 288Z"
- android:fillColor="#FFF1E4EA"
- android:strokeColor="#FF0B0C1C"
- android:strokeWidth="6"
- android:strokeLineJoin="round" />
- </group>
- </group>
-</vector>
diff --git a/app/app/src/main/res/drawable/ic_splash_animated.xml b/app/app/src/main/res/drawable/ic_splash_animated.xml
deleted file mode 100644
index e853487..0000000
--- a/app/app/src/main/res/drawable/ic_splash_animated.xml
+++ /dev/null
@@ -1,246 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- The splash (Android 12+): the mascot flies up into the disc with three
- wingbeats while the envelope drops onto its string. Then, for as long as
- mail is loading, it hovers and flaps with the envelope swinging below.
- Times are in ms; the loops start once the opening has finished. -->
-<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:aapt="http://schemas.android.com/aapt"
- android:drawable="@drawable/ic_splash">
-
- <target android:name="mascot">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="translateY"
- android:valueFrom="70"
- android:valueTo="0"
- android:duration="900"
- android:interpolator="@interpolator/splash_rise" />
- <objectAnimator
- android:propertyName="translateY"
- android:startOffset="900"
- android:valueFrom="0"
- android:valueTo="-14"
- android:duration="700"
- android:repeatCount="infinite"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- </set>
- </aapt:attr>
- </target>
-
- <!-- Three quick beats on the way up, then slower ones while mail loads. -->
- <target android:name="wing_left">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="rotation"
- android:valueFrom="0"
- android:valueTo="-24"
- android:duration="150"
- android:repeatCount="5"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- <objectAnimator
- android:propertyName="scaleX"
- android:valueFrom="1"
- android:valueTo="0.85"
- android:duration="150"
- android:repeatCount="5"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- <objectAnimator
- android:propertyName="rotation"
- android:startOffset="900"
- android:valueFrom="0"
- android:valueTo="-24"
- android:duration="350"
- android:repeatCount="infinite"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- <objectAnimator
- android:propertyName="scaleX"
- android:startOffset="900"
- android:valueFrom="1"
- android:valueTo="0.85"
- android:duration="350"
- android:repeatCount="infinite"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- </set>
- </aapt:attr>
- </target>
-
- <!-- Three quick beats on the way up, then slower ones while mail loads. -->
- <target android:name="wing_right">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="rotation"
- android:valueFrom="0"
- android:valueTo="24"
- android:duration="150"
- android:repeatCount="5"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- <objectAnimator
- android:propertyName="scaleX"
- android:valueFrom="1"
- android:valueTo="0.85"
- android:duration="150"
- android:repeatCount="5"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- <objectAnimator
- android:propertyName="rotation"
- android:startOffset="900"
- android:valueFrom="0"
- android:valueTo="24"
- android:duration="350"
- android:repeatCount="infinite"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- <objectAnimator
- android:propertyName="scaleX"
- android:startOffset="900"
- android:valueFrom="1"
- android:valueTo="0.85"
- android:duration="350"
- android:repeatCount="infinite"
- android:repeatMode="reverse"
- android:interpolator="@android:interpolator/accelerate_decelerate" />
- </set>
- </aapt:attr>
- </target>
-
- <!-- Drops in from above, then swings in time with the hover. -->
- <target android:name="envelope">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="translateY"
- android:startOffset="350"
- android:valueFrom="-170"
- android:valueTo="0"
- android:duration="800"
- android:interpolator="@interpolator/splash_drop" />
- <objectAnimator
- android:propertyName="scaleX"
- android:startOffset="350"
- android:valueFrom="0.6"
- android:valueTo="1"
- android:duration="800"
- android:interpolator="@interpolator/splash_drop" />
- <objectAnimator
- android:propertyName="scaleY"
- android:startOffset="350"
- android:valueFrom="0.6"
- android:valueTo="1"
- android:duration="800"
- android:interpolator="@interpolator/splash_drop" />
- <objectAnimator
- android:startOffset="1150"
- android:duration="1400"
- android:repeatCount="infinite">
- <propertyValuesHolder android:propertyName="rotation">
- <keyframe android:fraction="0" android:value="0" />
- <keyframe android:fraction="0.25" android:value="7" />
- <keyframe android:fraction="0.75" android:value="-7" />
- <keyframe android:fraction="1" android:value="0" />
- </propertyValuesHolder>
- </objectAnimator>
- </set>
- </aapt:attr>
- </target>
-
- <target android:name="envelope_0">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="fillAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- <objectAnimator
- android:propertyName="strokeAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- </set>
- </aapt:attr>
- </target>
- <target android:name="envelope_1">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="fillAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- <objectAnimator
- android:propertyName="strokeAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- </set>
- </aapt:attr>
- </target>
- <target android:name="envelope_2">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="fillAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- <objectAnimator
- android:propertyName="strokeAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- </set>
- </aapt:attr>
- </target>
- <target android:name="envelope_3">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="fillAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- <objectAnimator
- android:propertyName="strokeAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- </set>
- </aapt:attr>
- </target>
- <target android:name="envelope_4">
- <aapt:attr name="android:animation">
- <set>
- <objectAnimator
- android:propertyName="fillAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- <objectAnimator
- android:propertyName="strokeAlpha"
- android:startOffset="350"
- android:valueFrom="0"
- android:valueTo="1"
- android:duration="320" />
- </set>
- </aapt:attr>
- </target>
-</animated-vector>
diff --git a/app/app/src/main/res/font/ibm_plex_sans_bold.ttf b/app/app/src/main/res/font/ibm_plex_sans_bold.ttf
deleted file mode 100644
index c864a80..0000000
Binary files a/app/app/src/main/res/font/ibm_plex_sans_bold.ttf and /dev/null differ
diff --git a/app/app/src/main/res/font/ibm_plex_sans_medium.ttf b/app/app/src/main/res/font/ibm_plex_sans_medium.ttf
deleted file mode 100644
index 94738b8..0000000
Binary files a/app/app/src/main/res/font/ibm_plex_sans_medium.ttf and /dev/null differ
diff --git a/app/app/src/main/res/font/ibm_plex_sans_regular.ttf b/app/app/src/main/res/font/ibm_plex_sans_regular.ttf
deleted file mode 100644
index a4f4148..0000000
Binary files a/app/app/src/main/res/font/ibm_plex_sans_regular.ttf and /dev/null differ
diff --git a/app/app/src/main/res/font/ibm_plex_sans_semibold.ttf b/app/app/src/main/res/font/ibm_plex_sans_semibold.ttf
deleted file mode 100644
index 454f3d4..0000000
Binary files a/app/app/src/main/res/font/ibm_plex_sans_semibold.ttf and /dev/null differ
diff --git a/app/app/src/main/res/interpolator/splash_drop.xml b/app/app/src/main/res/interpolator/splash_drop.xml
deleted file mode 100644
index f3e2cff..0000000
--- a/app/app/src/main/res/interpolator/splash_drop.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Overshoots, so the envelope bounces on its string. -->
-<pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
- android:controlX1="0.3"
- android:controlY1="1.5"
- android:controlX2="0.5"
- android:controlY2="1" />
diff --git a/app/app/src/main/res/interpolator/splash_rise.xml b/app/app/src/main/res/interpolator/splash_rise.xml
deleted file mode 100644
index 02f0ee9..0000000
--- a/app/app/src/main/res/interpolator/splash_rise.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<pathInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
- android:controlX1="0.2"
- android:controlY1="0.8"
- android:controlX2="0.2"
- android:controlY2="1" />
diff --git a/app/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/app/app/src/main/res/mipmap-anydpi/ic_launcher.xml
deleted file mode 100644
index 3984a9f..0000000
--- a/app/app/src/main/res/mipmap-anydpi/ic_launcher.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Adaptive, so the launcher fills its own shape instead of shrinking a
- square PNG onto a white plate. Monochrome is for Android 13 themed icons. -->
-<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
- <background android:drawable="@drawable/ic_launcher_background" />
- <foreground android:drawable="@drawable/ic_launcher_foreground" />
- <monochrome android:drawable="@drawable/ic_launcher_foreground" />
-</adaptive-icon>
diff --git a/app/app/src/main/res/values-v31/themes.xml b/app/app/src/main/res/values-v31/themes.xml
deleted file mode 100644
index 4f339fb..0000000
--- a/app/app/src/main/res/values-v31/themes.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <!-- Android 12+ can animate the splash icon; older versions show it still. -->
- <style name="Theme.Inbox.Starting" parent="Theme.SplashScreen.IconBackground">
- <item name="windowSplashScreenBackground">@color/background</item>
- <item name="windowSplashScreenAnimatedIcon">@drawable/ic_splash_animated</item>
- <item name="windowSplashScreenAnimationDuration">1000</item>
- <item name="windowSplashScreenIconBackgroundColor">@color/icon_background</item>
- <item name="postSplashScreenTheme">@style/Theme.Inbox</item>
- </style>
-</resources>
diff --git a/app/app/src/main/res/values/colors.xml b/app/app/src/main/res/values/colors.xml
deleted file mode 100644
index 2f01e8e..0000000
--- a/app/app/src/main/res/values/colors.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <color name="background">#0B0A0D</color>
- <color name="icon_background">#F1E4EA</color>
-</resources>
diff --git a/app/app/src/main/res/values/strings.xml b/app/app/src/main/res/values/strings.xml
deleted file mode 100644
index 045c1e4..0000000
--- a/app/app/src/main/res/values/strings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <string name="app_name">Inbox</string>
-</resources>
diff --git a/app/app/src/main/res/values/themes.xml b/app/app/src/main/res/values/themes.xml
deleted file mode 100644
index bd564ec..0000000
--- a/app/app/src/main/res/values/themes.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <!-- Compose draws everything; this only colours the window before it does. -->
- <style name="Theme.Inbox" parent="android:Theme.Material.NoActionBar">
- <item name="android:windowBackground">@color/background</item>
- <item name="android:statusBarColor">@android:color/transparent</item>
- <item name="android:navigationBarColor">@android:color/transparent</item>
- </style>
-
- <!-- The splash: the mascot on a blush disc, held until the first page of
- mail is in (see MainActivity), then it hands over to Theme.Inbox. -->
- <style name="Theme.Inbox.Starting" parent="Theme.SplashScreen.IconBackground">
- <item name="windowSplashScreenBackground">@color/background</item>
- <item name="windowSplashScreenAnimatedIcon">@drawable/ic_launcher_foreground</item>
- <item name="windowSplashScreenIconBackgroundColor">@color/icon_background</item>
- <item name="postSplashScreenTheme">@style/Theme.Inbox</item>
- </style>
-</resources>
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
deleted file mode 100644
index 5beb9b9..0000000
--- a/app/build.gradle.kts
+++ /dev/null
@@ -1,7 +0,0 @@
-plugins {
- id("com.android.application") version "8.7.3" apply false
- id("org.jetbrains.kotlin.android") version "2.0.21" apply false
- id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false
- id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" apply false
- id("com.google.gms.google-services") version "4.4.2" apply false
-}
diff --git a/app/gradle.properties b/app/gradle.properties
deleted file mode 100644
index 18825f9..0000000
--- a/app/gradle.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
-android.useAndroidX=true
-android.nonTransitiveRClass=true
diff --git a/app/gradle/wrapper/gradle-wrapper.jar b/app/gradle/wrapper/gradle-wrapper.jar
deleted file mode 100644
index 9fa7f28..0000000
Binary files a/app/gradle/wrapper/gradle-wrapper.jar and /dev/null differ
diff --git a/app/gradle/wrapper/gradle-wrapper.properties b/app/gradle/wrapper/gradle-wrapper.properties
deleted file mode 100644
index e3343bc..0000000
--- a/app/gradle/wrapper/gradle-wrapper.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-distributionBase=GRADLE_USER_HOME
-distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
-networkTimeout=10000
-retries=0
-retryBackOffMs=500
-validateDistributionUrl=true
-zipStoreBase=GRADLE_USER_HOME
-zipStorePath=wrapper/dists
diff --git a/app/gradlew b/app/gradlew
deleted file mode 100755
index 379a658..0000000
--- a/app/gradlew
+++ /dev/null
@@ -1,248 +0,0 @@
-#!/bin/sh
-
-#
-# Copyright © 2015 the original authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-# SPDX-License-Identifier: Apache-2.0
-#
-
-##############################################################################
-#
-# gradlew start up script for POSIX generated by Gradle.
-#
-# Important for running:
-#
-# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
-# noncompliant, but you have some other compliant shell such as ksh or
-# bash, then to run this script, type that shell name before the whole
-# command line, like:
-#
-# ksh gradlew
-#
-# Busybox and similar reduced shells will NOT work, because this script
-# requires all of these POSIX shell features:
-# * functions;
-# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
-# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
-# * compound commands having a testable exit status, especially «case»;
-# * various built-in commands including «command», «set», and «ulimit».
-#
-# Important for patching:
-#
-# (2) This script targets any POSIX shell, so it avoids extensions provided
-# by Bash, Ksh, etc; in particular arrays are avoided.
-#
-# The "traditional" practice of packing multiple parameters into a
-# space-separated string is a well documented source of bugs and security
-# problems, so this is (mostly) avoided, by progressively accumulating
-# options in "$@", and eventually passing that to Java.
-#
-# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
-# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
-# see the in-line comments for details.
-#
-# There are tweaks for specific operating systems such as AIX, CygWin,
-# Darwin, MinGW, and NonStop.
-#
-# (3) This script is generated from the Groovy template
-# https://github.com/gradle/gradle/blob/<unknown>/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
-# within the Gradle project.
-#
-# You can find Gradle at https://github.com/gradle/gradle/.
-#
-##############################################################################
-
-# Attempt to set APP_HOME
-
-# Resolve links: $0 may be a link
-app_path=$0
-
-# Need this for daisy-chained symlinks.
-while
- APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
- [ -h "$app_path" ]
-do
- ls=$( ls -ld "$app_path" )
- link=${ls#*' -> '}
- case $link in #(
- /*) app_path=$link ;; #(
- *) app_path=$APP_HOME$link ;;
- esac
-done
-
-# This is normally unused
-# shellcheck disable=SC2034
-APP_BASE_NAME=${0##*/}
-# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
-APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD=maximum
-
-warn () {
- echo "$*"
-} >&2
-
-die () {
- echo
- echo "$*"
- echo
- exit 1
-} >&2
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-nonstop=false
-case "$( uname )" in #(
- CYGWIN* ) cygwin=true ;; #(
- Darwin* ) darwin=true ;; #(
- MSYS* | MINGW* ) msys=true ;; #(
- NONSTOP* ) nonstop=true ;;
-esac
-
-
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD=$JAVA_HOME/jre/sh/java
- else
- JAVACMD=$JAVA_HOME/bin/java
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD=java
- if ! command -v java >/dev/null 2>&1
- then
- die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-fi
-
-# Increase the maximum file descriptors if we can.
-if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
- case $MAX_FD in #(
- max*)
- # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC2039,SC3045
- MAX_FD=$( ulimit -H -n ) ||
- warn "Could not query maximum file descriptor limit"
- esac
- case $MAX_FD in #(
- '' | soft) :;; #(
- *)
- # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC2039,SC3045
- ulimit -n "$MAX_FD" ||
- warn "Could not set maximum file descriptor limit to $MAX_FD"
- esac
-fi
-
-# Collect all arguments for the java command, stacking in reverse order:
-# * args from the command line
-# * the main class name
-# * -classpath
-# * -D...appname settings
-# * --module-path (only if needed)
-# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
-
-# For Cygwin or MSYS, switch paths to Windows format before running java
-if "$cygwin" || "$msys" ; then
- APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
-
- JAVACMD=$( cygpath --unix "$JAVACMD" )
-
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- for arg do
- if
- case $arg in #(
- -*) false ;; # don't mess with options #(
- /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
- [ -e "$t" ] ;; #(
- *) false ;;
- esac
- then
- arg=$( cygpath --path --ignore --mixed "$arg" )
- fi
- # Roll the args list around exactly as many times as the number of
- # args, so each arg winds up back in the position where it started, but
- # possibly modified.
- #
- # NB: a `for` loop captures its iteration list before it begins, so
- # changing the positional parameters here affects neither the number of
- # iterations, nor the values presented in `arg`.
- shift # remove old arg
- set -- "$@" "$arg" # push replacement arg
- done
-fi
-
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
-
-# Collect all arguments for the java command:
-# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
-# and any embedded shellness will be escaped.
-# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
-# treated as '${Hostname}' itself on the command line.
-
-set -- \
- "-Dorg.gradle.appname=$APP_BASE_NAME" \
- -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
- "$@"
-
-# Stop when "xargs" is not available.
-if ! command -v xargs >/dev/null 2>&1
-then
- die "xargs is not available"
-fi
-
-# Use "xargs" to parse quoted args.
-#
-# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
-#
-# In Bash we could simply go:
-#
-# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
-# set -- "${ARGS[@]}" "$@"
-#
-# but POSIX shell has neither arrays nor command substitution, so instead we
-# post-process each arg (as a line of input to sed) to backslash-escape any
-# character that might be a shell metacharacter, then use eval to reverse
-# that process (while maintaining the separation between arguments), and wrap
-# the whole thing up as a single "set" statement.
-#
-# This will of course break if any of these variables contains a newline or
-# an unmatched quote.
-#
-
-eval "set -- $(
- printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
- xargs -n1 |
- sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
- tr '\n' ' '
- )" '"$@"'
-
-exec "$JAVACMD" "$@"
diff --git a/app/gradlew.bat b/app/gradlew.bat
deleted file mode 100644
index 03754c4..0000000
--- a/app/gradlew.bat
+++ /dev/null
@@ -1,112 +0,0 @@
-@rem
-@rem Copyright 2015 the original author or authors.
-@rem
-@rem Licensed under the Apache License, Version 2.0 (the "License");
-@rem you may not use this file except in compliance with the License.
-@rem You may obtain a copy of the License at
-@rem
-@rem https://www.apache.org/licenses/LICENSE-2.0
-@rem
-@rem Unless required by applicable law or agreed to in writing, software
-@rem distributed under the License is distributed on an "AS IS" BASIS,
-@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-@rem See the License for the specific language governing permissions and
-@rem limitations under the License.
-@rem
-@rem SPDX-License-Identifier: Apache-2.0
-@rem
-
-@if "%DEBUG%"=="" @echo off
-@rem ##########################################################################
-@rem
-@rem gradlew startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables, and ensure extensions are enabled
-setlocal EnableExtensions
-
-@rem Catch executions from older scripts and ensure they exit cleanly.
-@rem This can be removed once we can be reasonably confident that few people
-@rem will be migrating directly to this new wrapper.
-goto afterSafetyNet
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
-goto exitWithErrorLevel
-:afterSafetyNet
-
-set DIRNAME=%~dp0
-if "%DIRNAME%"=="" set DIRNAME=.
-@rem This is normally unused
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Resolve any "." and ".." in APP_HOME to make it shorter.
-for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if %ERRORLEVEL% equ 0 goto execute
-
-1>&2 echo.
-1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-1>&2 echo.
-1>&2 echo Please set the JAVA_HOME variable in your environment to match the
-1>&2 echo location of your Java installation.
-
-"%COMSPEC%" /c exit 1
-goto exitWithErrorLevel
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto execute
-
-1>&2 echo.
-1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-1>&2 echo.
-1>&2 echo Please set the JAVA_HOME variable in your environment to match the
-1>&2 echo location of your Java installation.
-
-"%COMSPEC%" /c exit 1
-goto exitWithErrorLevel
-
-:execute
-@rem Setup the command line
-
-
-
-@rem Execute gradlew
-@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
-@rem which allows us to clear the local environment before executing the java command
-endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
-
-@rem This label must not be changed. We rely on old scripts being able to jump to this point.
-:exitWithErrorLevel
-@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
-"%COMSPEC%" /c exit %ERRORLEVEL%
diff --git a/app/settings.gradle.kts b/app/settings.gradle.kts
deleted file mode 100644
index 6be2236..0000000
--- a/app/settings.gradle.kts
+++ /dev/null
@@ -1,18 +0,0 @@
-pluginManagement {
- repositories {
- google()
- mavenCentral()
- gradlePluginPortal()
- }
-}
-
-dependencyResolutionManagement {
- repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
- repositories {
- google()
- mavenCentral()
- }
-}
-
-rootProject.name = "email-app"
-include(":app")
diff --git a/email/bun.lock b/bun.lock
similarity index 100%
rename from email/bun.lock
rename to bun.lock
diff --git a/email/.gitignore b/email/.gitignore
deleted file mode 100644
index cdfbe7a..0000000
--- a/email/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-node_modules/
-.wrangler/
-.dev.vars
-dist/
-*.log
diff --git a/email/README.md b/email/README.md
deleted file mode 100644
index 2dc8919..0000000
--- a/email/README.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# Inbox
-
-A multi-domain mailbox on Cloudflare Workers. Mail comes in and goes out through
-[Resend](https://resend.com), people sign in through the SSO, and every user gets
-`<username>@<domain>` on each domain that's switched on. There's no config file:
-domains, aliases and admins are managed from the Admin page.
-
-## How it fits together
-
-```
-src/
- shared/types.ts API shapes, used by both sides
- worker/ Hono API (only /api, /auth, /webhook reach the Worker)
- lib/routing.ts who owns which address: pure, unit-tested
- services/ D1, R2, Resend, SSO, push
- routes/ HTTP handlers
- web/ Svelte 5 app, served as static assets
- components/EmailFrame.svelte the only place email HTML is rendered
-migrations/ D1 schema
-test/ vitest, running inside workerd with local D1 + R2
-```
-
-- **D1** (`DB`) holds users, domains, aliases, threads, messages, sessions.
-- **R2** (`BUCKET`) holds attachment bytes under `inbox/`. It's the same bucket the
- old proxy used.
-- **Domains** are synced from Resend into D1 (`services/domains.ts`), never typed in.
-- **Routing**: on an active domain, mail to `x@domain` goes to the alias `x` if
- there is one, otherwise to user `x`, otherwise to that domain's catch-all,
- otherwise nowhere. You can send from exactly the addresses whose mail reaches
- you. An email addressed to several users is stored once in each mailbox.
-- **Email rendering**: email HTML goes in a sandboxed `srcdoc` iframe with no
- script, its own CSP, and remote content blocked until you click to load it.
- That keeps an email's fonts and styles inside the frame. Attachments are only
- ever shown inline when they're plain images.
-- **Sign-in**: the SSO, with sessions in D1 keyed by a hash of the cookie's
- token. The SSO account (`sub`) is the identity, so someone renamed there keeps
- their mailbox here. Role names like `postmaster` and `abuse` can't be signed up
- for; hand them out as aliases. `ADMIN_USERS` makes a new account an admin only
- while there's no admin yet.
-- **Android app**: signs in through the same flow in a browser tab, started with
- `/auth/login?app=<PKCE challenge>`. The callback redirects to
- `gay.doughmination.mail://auth?code=...`, the app swaps that code and its
- verifier at `POST /auth/app/token` for a session token, and sends it as
- `Authorization: Bearer`.
-
-## Setup
-
-```sh
-npm install
-cp .dev.vars.example .dev.vars # fill in the secrets
-npx wrangler d1 create email-db-v2 # put the id in wrangler.jsonc
-npm run db:migrate:local
-npm run dev # http://localhost:5173
-```
-
-Local sign-in needs `http://localhost:5173/auth/callback` registered as a redirect
-URI on the SSO client.
-
-`ADMIN_USERS` in `wrangler.jsonc` lists people who are always admins. Anyone the
-SSO lets in becomes a user on first sign-in.
-
-## Deploying
-
-```sh
-npm run db:migrate:remote
-npx wrangler secret put RESEND_API_KEY # also RESEND_WEBHOOK_SECRET,
- # OIDC_CLIENT_SECRET, VAPID_PRIVATE_KEY
-npx wrangler secret put FCM_SERVICE_ACCOUNT < service-account.json # Android notifications
-npm run deploy
-```
-
-`FCM_SERVICE_ACCOUNT` is the Firebase project's service account key (Firebase
-console > Project settings > Service accounts > Generate new private key). New
-mail is pushed to browsers through Web Push and to the Android app through
-FCM; without the key, the app just gets no notifications.
-
-Then:
-
-1. In Resend, point a webhook at `https://<host>/webhook/inbound` for
- `email.received`, plus `domain.created`, `domain.updated` and `domain.deleted`.
-2. That's it for domains. They come from your Resend account: every domain there
- is switched on automatically, and it routes mail once receiving is on in
- Resend. The list re-syncs on those webhooks, daily, and whenever Admin →
- Domains is opened. That page is where you switch one off or pick a catch-all.
-
-## Demo
-
-`/demo` (e.g. https://mail.doughmination.gay/demo) is the same app with made-up
-mail and no sign-in. Under that path the API is swapped for an in-memory fake
-(`src/web/lib/demo.ts`), so nothing touches the Worker, D1, R2 or Resend, and no
-real email comes in or goes out. Sending moves a message to Sent, mail to one of
-the demo's own addresses lands in its inbox, anyone else gets a pretend reply a
-few seconds later, and reloading starts over. Locally it's at
-http://localhost:5173/demo.
-
-## Scripts
-
-| | |
-|---|---|
-| `npm run dev` | Vite + the Worker in workerd, with hot reload |
-| `npm run typecheck` | Worker and tests (`tsc`), and the app (`svelte-check`) |
-| `npm test` | vitest inside workerd |
-| `npm run types` | regenerate `worker-configuration.d.ts` after changing `wrangler.jsonc` |
diff --git a/email/src/worker/routes/download.ts b/email/src/worker/routes/download.ts
deleted file mode 100644
index 12a4dd6..0000000
--- a/email/src/worker/routes/download.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { Hono } from "hono";
-import type { AppEnv } from "../middleware";
-
-/** The rolling release CI keeps the newest Android build on. */
-const LATEST = "https://api.github.com/repos/doughmination/email/releases/tags/latest";
-const RELEASES = "https://github.com/doughmination/email/releases/latest";
-
-// Release APKs are named by version (inbox-1.0.6.apk), so /download looks up
-// the current one: the site's link stays the same from build to build.
-export const download = new Hono<AppEnv>().get("/", async (c) => {
- const res = await fetch(LATEST, {
- headers: { accept: "application/vnd.github+json", "user-agent": "doughmination-mail" },
- // Cached at the edge, so a busy day doesn't run into GitHub's rate limit.
- cf: { cacheTtl: 300, cacheEverything: true },
- });
- if (!res.ok) return c.redirect(RELEASES);
- const { assets } = (await res.json()) as { assets: { name: string; browser_download_url: string }[] };
- const apk = assets.find((a) => /^inbox-.+\.apk$/.test(a.name));
- return c.redirect(apk?.browser_download_url ?? RELEASES);
-});
diff --git a/email/index.html b/index.html
similarity index 100%
rename from email/index.html
rename to index.html
diff --git a/email/migrations/0001_init.sql b/migrations/0001_init.sql
similarity index 100%
rename from email/migrations/0001_init.sql
rename to migrations/0001_init.sql
diff --git a/email/migrations/0002_resend_domains.sql b/migrations/0002_resend_domains.sql
similarity index 100%
rename from email/migrations/0002_resend_domains.sql
rename to migrations/0002_resend_domains.sql
diff --git a/email/migrations/0003_bcc.sql b/migrations/0003_bcc.sql
similarity index 100%
rename from email/migrations/0003_bcc.sql
rename to migrations/0003_bcc.sql
diff --git a/email/migrations/0004_bin_and_names.sql b/migrations/0004_bin_and_names.sql
similarity index 100%
rename from email/migrations/0004_bin_and_names.sql
rename to migrations/0004_bin_and_names.sql
diff --git a/email/migrations/0005_starred.sql b/migrations/0005_starred.sql
similarity index 100%
rename from email/migrations/0005_starred.sql
rename to migrations/0005_starred.sql
diff --git a/email/migrations/0006_hashed_sessions.sql b/migrations/0006_hashed_sessions.sql
similarity index 100%
rename from email/migrations/0006_hashed_sessions.sql
rename to migrations/0006_hashed_sessions.sql
diff --git a/email/migrations/0007_fcm_tokens.sql b/migrations/0007_fcm_tokens.sql
similarity index 100%
rename from email/migrations/0007_fcm_tokens.sql
rename to migrations/0007_fcm_tokens.sql
diff --git a/email/migrations/0008_profile_and_swipes.sql b/migrations/0008_profile_and_swipes.sql
similarity index 100%
rename from email/migrations/0008_profile_and_swipes.sql
rename to migrations/0008_profile_and_swipes.sql
diff --git a/email/package.json b/package.json
similarity index 100%
rename from email/package.json
rename to package.json
diff --git a/email/public/.well-known/assetlinks.json b/public/.well-known/assetlinks.json
similarity index 100%
rename from email/public/.well-known/assetlinks.json
rename to public/.well-known/assetlinks.json
diff --git a/email/public/_headers b/public/_headers
similarity index 100%
rename from email/public/_headers
rename to public/_headers
diff --git a/email/public/apple-touch-icon.png b/public/apple-touch-icon.png
similarity index 100%
rename from email/public/apple-touch-icon.png
rename to public/apple-touch-icon.png
diff --git a/email/public/background.avif b/public/background.avif
similarity index 100%
rename from email/public/background.avif
rename to public/background.avif
diff --git a/email/public/favicon.ico b/public/favicon.ico
similarity index 100%
rename from email/public/favicon.ico
rename to public/favicon.ico
diff --git a/email/public/icon.svg b/public/icon.svg
similarity index 100%
rename from email/public/icon.svg
rename to public/icon.svg
diff --git a/email/public/manifest.webmanifest b/public/manifest.webmanifest
similarity index 100%
rename from email/public/manifest.webmanifest
rename to public/manifest.webmanifest
diff --git a/email/public/sw.js b/public/sw.js
similarity index 100%
rename from email/public/sw.js
rename to public/sw.js
diff --git a/email/src/shared/types.ts b/src/shared/types.ts
similarity index 100%
rename from email/src/shared/types.ts
rename to src/shared/types.ts
diff --git a/email/src/web/App.svelte b/src/web/App.svelte
similarity index 100%
rename from email/src/web/App.svelte
rename to src/web/App.svelte
diff --git a/email/src/web/app.css b/src/web/app.css
similarity index 100%
rename from email/src/web/app.css
rename to src/web/app.css
diff --git a/email/src/web/components/AccountPicture.svelte b/src/web/components/AccountPicture.svelte
similarity index 100%
rename from email/src/web/components/AccountPicture.svelte
rename to src/web/components/AccountPicture.svelte
diff --git a/email/src/web/components/ActionMenu.svelte b/src/web/components/ActionMenu.svelte
similarity index 100%
rename from email/src/web/components/ActionMenu.svelte
rename to src/web/components/ActionMenu.svelte
diff --git a/email/src/web/components/Composer.svelte b/src/web/components/Composer.svelte
similarity index 100%
rename from email/src/web/components/Composer.svelte
rename to src/web/components/Composer.svelte
diff --git a/email/src/web/components/EmailFrame.svelte b/src/web/components/EmailFrame.svelte
similarity index 100%
rename from email/src/web/components/EmailFrame.svelte
rename to src/web/components/EmailFrame.svelte
diff --git a/email/src/web/components/LegalPage.svelte b/src/web/components/LegalPage.svelte
similarity index 100%
rename from email/src/web/components/LegalPage.svelte
rename to src/web/components/LegalPage.svelte
diff --git a/email/src/web/components/RecipientInput.svelte b/src/web/components/RecipientInput.svelte
similarity index 100%
rename from email/src/web/components/RecipientInput.svelte
rename to src/web/components/RecipientInput.svelte
diff --git a/email/src/web/components/Sidebar.svelte b/src/web/components/Sidebar.svelte
similarity index 100%
rename from email/src/web/components/Sidebar.svelte
rename to src/web/components/Sidebar.svelte
diff --git a/email/src/web/components/SwipeRow.svelte b/src/web/components/SwipeRow.svelte
similarity index 100%
rename from email/src/web/components/SwipeRow.svelte
rename to src/web/components/SwipeRow.svelte
diff --git a/email/src/web/components/ThreadList.svelte b/src/web/components/ThreadList.svelte
similarity index 100%
rename from email/src/web/components/ThreadList.svelte
rename to src/web/components/ThreadList.svelte
diff --git a/email/src/web/components/ThreadView.svelte b/src/web/components/ThreadView.svelte
similarity index 100%
rename from email/src/web/components/ThreadView.svelte
rename to src/web/components/ThreadView.svelte
diff --git a/email/src/web/fonts/IBMPlexSans-Bold.woff2 b/src/web/fonts/IBMPlexSans-Bold.woff2
similarity index 100%
rename from email/src/web/fonts/IBMPlexSans-Bold.woff2
rename to src/web/fonts/IBMPlexSans-Bold.woff2
diff --git a/email/src/web/fonts/IBMPlexSans-Medium.woff2 b/src/web/fonts/IBMPlexSans-Medium.woff2
similarity index 100%
rename from email/src/web/fonts/IBMPlexSans-Medium.woff2
rename to src/web/fonts/IBMPlexSans-Medium.woff2
diff --git a/email/src/web/fonts/IBMPlexSans-Regular.woff2 b/src/web/fonts/IBMPlexSans-Regular.woff2
similarity index 100%
rename from email/src/web/fonts/IBMPlexSans-Regular.woff2
rename to src/web/fonts/IBMPlexSans-Regular.woff2
diff --git a/email/src/web/fonts/IBMPlexSans-SemiBold.woff2 b/src/web/fonts/IBMPlexSans-SemiBold.woff2
similarity index 100%
rename from email/src/web/fonts/IBMPlexSans-SemiBold.woff2
rename to src/web/fonts/IBMPlexSans-SemiBold.woff2
diff --git a/email/src/web/lib/api.ts b/src/web/lib/api.ts
similarity index 100%
rename from email/src/web/lib/api.ts
rename to src/web/lib/api.ts
diff --git a/email/src/web/lib/demo.ts b/src/web/lib/demo.ts
similarity index 100%
rename from email/src/web/lib/demo.ts
rename to src/web/lib/demo.ts
diff --git a/email/src/web/lib/format.ts b/src/web/lib/format.ts
similarity index 100%
rename from email/src/web/lib/format.ts
rename to src/web/lib/format.ts
diff --git a/email/src/web/lib/icons/AllInbox.svelte b/src/web/lib/icons/AllInbox.svelte
similarity index 100%
rename from email/src/web/lib/icons/AllInbox.svelte
rename to src/web/lib/icons/AllInbox.svelte
diff --git a/email/src/web/lib/icons/AlternateEmail.svelte b/src/web/lib/icons/AlternateEmail.svelte
similarity index 100%
rename from email/src/web/lib/icons/AlternateEmail.svelte
rename to src/web/lib/icons/AlternateEmail.svelte
diff --git a/email/src/web/lib/icons/ArchiveRestore.svelte b/src/web/lib/icons/ArchiveRestore.svelte
similarity index 100%
rename from email/src/web/lib/icons/ArchiveRestore.svelte
rename to src/web/lib/icons/ArchiveRestore.svelte
diff --git a/email/src/web/lib/icons/ArrowLeft.svelte b/src/web/lib/icons/ArrowLeft.svelte
similarity index 100%
rename from email/src/web/lib/icons/ArrowLeft.svelte
rename to src/web/lib/icons/ArrowLeft.svelte
diff --git a/email/src/web/lib/icons/Bell.svelte b/src/web/lib/icons/Bell.svelte
similarity index 100%
rename from email/src/web/lib/icons/Bell.svelte
rename to src/web/lib/icons/Bell.svelte
diff --git a/email/src/web/lib/icons/ChevronDown.svelte b/src/web/lib/icons/ChevronDown.svelte
similarity index 100%
rename from email/src/web/lib/icons/ChevronDown.svelte
rename to src/web/lib/icons/ChevronDown.svelte
diff --git a/email/src/web/lib/icons/ChevronRight.svelte b/src/web/lib/icons/ChevronRight.svelte
similarity index 100%
rename from email/src/web/lib/icons/ChevronRight.svelte
rename to src/web/lib/icons/ChevronRight.svelte
diff --git a/email/src/web/lib/icons/CircleX.svelte b/src/web/lib/icons/CircleX.svelte
similarity index 100%
rename from email/src/web/lib/icons/CircleX.svelte
rename to src/web/lib/icons/CircleX.svelte
diff --git a/email/src/web/lib/icons/Eye.svelte b/src/web/lib/icons/Eye.svelte
similarity index 100%
rename from email/src/web/lib/icons/Eye.svelte
rename to src/web/lib/icons/Eye.svelte
diff --git a/email/src/web/lib/icons/FileText.svelte b/src/web/lib/icons/FileText.svelte
similarity index 100%
rename from email/src/web/lib/icons/FileText.svelte
rename to src/web/lib/icons/FileText.svelte
diff --git a/email/src/web/lib/icons/Forward.svelte b/src/web/lib/icons/Forward.svelte
similarity index 100%
rename from email/src/web/lib/icons/Forward.svelte
rename to src/web/lib/icons/Forward.svelte
diff --git a/email/src/web/lib/icons/Globe.svelte b/src/web/lib/icons/Globe.svelte
similarity index 100%
rename from email/src/web/lib/icons/Globe.svelte
rename to src/web/lib/icons/Globe.svelte
diff --git a/email/src/web/lib/icons/Icon.svelte b/src/web/lib/icons/Icon.svelte
similarity index 100%
rename from email/src/web/lib/icons/Icon.svelte
rename to src/web/lib/icons/Icon.svelte
diff --git a/email/src/web/lib/icons/Image.svelte b/src/web/lib/icons/Image.svelte
similarity index 100%
rename from email/src/web/lib/icons/Image.svelte
rename to src/web/lib/icons/Image.svelte
diff --git a/email/src/web/lib/icons/Inbox.svelte b/src/web/lib/icons/Inbox.svelte
similarity index 100%
rename from email/src/web/lib/icons/Inbox.svelte
rename to src/web/lib/icons/Inbox.svelte
diff --git a/email/src/web/lib/icons/LoaderCircle.svelte b/src/web/lib/icons/LoaderCircle.svelte
similarity index 100%
rename from email/src/web/lib/icons/LoaderCircle.svelte
rename to src/web/lib/icons/LoaderCircle.svelte
diff --git a/email/src/web/lib/icons/LogOut.svelte b/src/web/lib/icons/LogOut.svelte
similarity index 100%
rename from email/src/web/lib/icons/LogOut.svelte
rename to src/web/lib/icons/LogOut.svelte
diff --git a/email/src/web/lib/icons/Mail.svelte b/src/web/lib/icons/Mail.svelte
similarity index 100%
rename from email/src/web/lib/icons/Mail.svelte
rename to src/web/lib/icons/Mail.svelte
diff --git a/email/src/web/lib/icons/MarkRead.svelte b/src/web/lib/icons/MarkRead.svelte
similarity index 100%
rename from email/src/web/lib/icons/MarkRead.svelte
rename to src/web/lib/icons/MarkRead.svelte
diff --git a/email/src/web/lib/icons/MarkUnread.svelte b/src/web/lib/icons/MarkUnread.svelte
similarity index 100%
rename from email/src/web/lib/icons/MarkUnread.svelte
rename to src/web/lib/icons/MarkUnread.svelte
diff --git a/email/src/web/lib/icons/Menu.svelte b/src/web/lib/icons/Menu.svelte
similarity index 100%
rename from email/src/web/lib/icons/Menu.svelte
rename to src/web/lib/icons/Menu.svelte
diff --git a/email/src/web/lib/icons/Mobile.svelte b/src/web/lib/icons/Mobile.svelte
similarity index 100%
rename from email/src/web/lib/icons/Mobile.svelte
rename to src/web/lib/icons/Mobile.svelte
diff --git a/email/src/web/lib/icons/MoreVert.svelte b/src/web/lib/icons/MoreVert.svelte
similarity index 100%
rename from email/src/web/lib/icons/MoreVert.svelte
rename to src/web/lib/icons/MoreVert.svelte
diff --git a/email/src/web/lib/icons/Paperclip.svelte b/src/web/lib/icons/Paperclip.svelte
similarity index 100%
rename from email/src/web/lib/icons/Paperclip.svelte
rename to src/web/lib/icons/Paperclip.svelte
diff --git a/email/src/web/lib/icons/Pencil.svelte b/src/web/lib/icons/Pencil.svelte
similarity index 100%
rename from email/src/web/lib/icons/Pencil.svelte
rename to src/web/lib/icons/Pencil.svelte
diff --git a/email/src/web/lib/icons/Plus.svelte b/src/web/lib/icons/Plus.svelte
similarity index 100%
rename from email/src/web/lib/icons/Plus.svelte
rename to src/web/lib/icons/Plus.svelte
diff --git a/email/src/web/lib/icons/RefreshCw.svelte b/src/web/lib/icons/RefreshCw.svelte
similarity index 100%
rename from email/src/web/lib/icons/RefreshCw.svelte
rename to src/web/lib/icons/RefreshCw.svelte
diff --git a/email/src/web/lib/icons/Reply.svelte b/src/web/lib/icons/Reply.svelte
similarity index 100%
rename from email/src/web/lib/icons/Reply.svelte
rename to src/web/lib/icons/Reply.svelte
diff --git a/email/src/web/lib/icons/Send.svelte b/src/web/lib/icons/Send.svelte
similarity index 100%
rename from email/src/web/lib/icons/Send.svelte
rename to src/web/lib/icons/Send.svelte
diff --git a/email/src/web/lib/icons/Settings.svelte b/src/web/lib/icons/Settings.svelte
similarity index 100%
rename from email/src/web/lib/icons/Settings.svelte
rename to src/web/lib/icons/Settings.svelte
diff --git a/email/src/web/lib/icons/Shield.svelte b/src/web/lib/icons/Shield.svelte
similarity index 100%
rename from email/src/web/lib/icons/Shield.svelte
rename to src/web/lib/icons/Shield.svelte
diff --git a/email/src/web/lib/icons/ShieldCheck.svelte b/src/web/lib/icons/ShieldCheck.svelte
similarity index 100%
rename from email/src/web/lib/icons/ShieldCheck.svelte
rename to src/web/lib/icons/ShieldCheck.svelte
diff --git a/email/src/web/lib/icons/SquarePen.svelte b/src/web/lib/icons/SquarePen.svelte
similarity index 100%
rename from email/src/web/lib/icons/SquarePen.svelte
rename to src/web/lib/icons/SquarePen.svelte
diff --git a/email/src/web/lib/icons/Star.svelte b/src/web/lib/icons/Star.svelte
similarity index 100%
rename from email/src/web/lib/icons/Star.svelte
rename to src/web/lib/icons/Star.svelte
diff --git a/email/src/web/lib/icons/StarOff.svelte b/src/web/lib/icons/StarOff.svelte
similarity index 100%
rename from email/src/web/lib/icons/StarOff.svelte
rename to src/web/lib/icons/StarOff.svelte
diff --git a/email/src/web/lib/icons/Trash.svelte b/src/web/lib/icons/Trash.svelte
similarity index 100%
rename from email/src/web/lib/icons/Trash.svelte
rename to src/web/lib/icons/Trash.svelte
diff --git a/email/src/web/lib/icons/Trash2.svelte b/src/web/lib/icons/Trash2.svelte
similarity index 100%
rename from email/src/web/lib/icons/Trash2.svelte
rename to src/web/lib/icons/Trash2.svelte
diff --git a/email/src/web/lib/icons/X.svelte b/src/web/lib/icons/X.svelte
similarity index 100%
rename from email/src/web/lib/icons/X.svelte
rename to src/web/lib/icons/X.svelte
diff --git a/email/src/web/lib/live.ts b/src/web/lib/live.ts
similarity index 100%
rename from email/src/web/lib/live.ts
rename to src/web/lib/live.ts
diff --git a/email/src/web/lib/router.svelte.ts b/src/web/lib/router.svelte.ts
similarity index 100%
rename from email/src/web/lib/router.svelte.ts
rename to src/web/lib/router.svelte.ts
diff --git a/email/src/web/lib/splash.ts b/src/web/lib/splash.ts
similarity index 100%
rename from email/src/web/lib/splash.ts
rename to src/web/lib/splash.ts
diff --git a/email/src/web/lib/state.svelte.ts b/src/web/lib/state.svelte.ts
similarity index 100%
rename from email/src/web/lib/state.svelte.ts
rename to src/web/lib/state.svelte.ts
diff --git a/email/src/web/main.ts b/src/web/main.ts
similarity index 100%
rename from email/src/web/main.ts
rename to src/web/main.ts
diff --git a/email/src/web/pages/Admin.svelte b/src/web/pages/Admin.svelte
similarity index 100%
rename from email/src/web/pages/Admin.svelte
rename to src/web/pages/Admin.svelte
diff --git a/email/src/web/pages/Privacy.svelte b/src/web/pages/Privacy.svelte
similarity index 100%
rename from email/src/web/pages/Privacy.svelte
rename to src/web/pages/Privacy.svelte
diff --git a/email/src/web/pages/Settings.svelte b/src/web/pages/Settings.svelte
similarity index 100%
rename from email/src/web/pages/Settings.svelte
rename to src/web/pages/Settings.svelte
diff --git a/email/src/web/pages/Terms.svelte b/src/web/pages/Terms.svelte
similarity index 100%
rename from email/src/web/pages/Terms.svelte
rename to src/web/pages/Terms.svelte
diff --git a/email/src/web/tsconfig.json b/src/web/tsconfig.json
similarity index 100%
rename from email/src/web/tsconfig.json
rename to src/web/tsconfig.json
diff --git a/email/src/worker/index.ts b/src/worker/index.ts
similarity index 100%
rename from email/src/worker/index.ts
rename to src/worker/index.ts
diff --git a/email/src/worker/lib/address.ts b/src/worker/lib/address.ts
similarity index 100%
rename from email/src/worker/lib/address.ts
rename to src/worker/lib/address.ts
diff --git a/email/src/worker/lib/chunk.ts b/src/worker/lib/chunk.ts
similarity index 100%
rename from email/src/worker/lib/chunk.ts
rename to src/worker/lib/chunk.ts
diff --git a/email/src/worker/lib/routing.ts b/src/worker/lib/routing.ts
similarity index 100%
rename from email/src/worker/lib/routing.ts
rename to src/worker/lib/routing.ts
diff --git a/email/src/worker/middleware.ts b/src/worker/middleware.ts
similarity index 100%
rename from email/src/worker/middleware.ts
rename to src/worker/middleware.ts
diff --git a/email/src/worker/routes/admin.ts b/src/worker/routes/admin.ts
similarity index 100%
rename from email/src/worker/routes/admin.ts
rename to src/worker/routes/admin.ts
diff --git a/email/src/worker/routes/auth.ts b/src/worker/routes/auth.ts
similarity index 100%
rename from email/src/worker/routes/auth.ts
rename to src/worker/routes/auth.ts
diff --git a/src/worker/routes/download.ts b/src/worker/routes/download.ts
new file mode 100644
index 0000000..3b5fe53
--- /dev/null
+++ b/src/worker/routes/download.ts
@@ -0,0 +1,31 @@
+import { Hono } from "hono";
+import type { AppEnv } from "../middleware";
+
+/**
+ * Releases holding the newest Android build, in order. The app is built in
+ * doughmination/apps, which keeps it on the rolling `inbox-latest` release.
+ * Builds up to 1.0.7 came from this repository's own `latest` release, which
+ * stays as a fallback until the first signed build from the monorepo exists.
+ */
+const SOURCES = [
+ "https://api.github.com/repos/doughmination/apps/releases/tags/inbox-latest",
+ "https://api.github.com/repos/doughmination/email/releases/tags/latest",
+];
+const RELEASES = "https://github.com/doughmination/apps/releases";
+
+// Release APKs are named by version (inbox-1.0.6.apk), so /download looks up
+// the current one: the site's link stays the same from build to build.
+export const download = new Hono<AppEnv>().get("/", async (c) => {
+ for (const url of SOURCES) {
+ const res = await fetch(url, {
+ headers: { accept: "application/vnd.github+json", "user-agent": "doughmination-mail" },
+ // Cached at the edge, so a busy day doesn't run into GitHub's rate limit.
+ cf: { cacheTtl: 300, cacheEverything: true },
+ });
+ if (!res.ok) continue;
+ const { assets } = (await res.json()) as { assets: { name: string; browser_download_url: string }[] };
+ const apk = assets.find((a) => /^inbox-.+\.apk$/.test(a.name));
+ if (apk) return c.redirect(apk.browser_download_url);
+ }
+ return c.redirect(RELEASES);
+});
diff --git a/email/src/worker/routes/mail.ts b/src/worker/routes/mail.ts
similarity index 100%
rename from email/src/worker/routes/mail.ts
rename to src/worker/routes/mail.ts
diff --git a/email/src/worker/routes/webhook.ts b/src/worker/routes/webhook.ts
similarity index 100%
rename from email/src/worker/routes/webhook.ts
rename to src/worker/routes/webhook.ts
diff --git a/email/src/worker/services/attachments.ts b/src/worker/services/attachments.ts
similarity index 100%
rename from email/src/worker/services/attachments.ts
rename to src/worker/services/attachments.ts
diff --git a/email/src/worker/services/directory.ts b/src/worker/services/directory.ts
similarity index 100%
rename from email/src/worker/services/directory.ts
rename to src/worker/services/directory.ts
diff --git a/email/src/worker/services/domains.ts b/src/worker/services/domains.ts
similarity index 100%
rename from email/src/worker/services/domains.ts
rename to src/worker/services/domains.ts
diff --git a/email/src/worker/services/fcm.ts b/src/worker/services/fcm.ts
similarity index 100%
rename from email/src/worker/services/fcm.ts
rename to src/worker/services/fcm.ts
diff --git a/email/src/worker/services/inbound.ts b/src/worker/services/inbound.ts
similarity index 100%
rename from email/src/worker/services/inbound.ts
rename to src/worker/services/inbound.ts
diff --git a/email/src/worker/services/live.ts b/src/worker/services/live.ts
similarity index 100%
rename from email/src/worker/services/live.ts
rename to src/worker/services/live.ts
diff --git a/email/src/worker/services/messages.ts b/src/worker/services/messages.ts
similarity index 100%
rename from email/src/worker/services/messages.ts
rename to src/worker/services/messages.ts
diff --git a/email/src/worker/services/oidc.ts b/src/worker/services/oidc.ts
similarity index 100%
rename from email/src/worker/services/oidc.ts
rename to src/worker/services/oidc.ts
diff --git a/email/src/worker/services/outbound.ts b/src/worker/services/outbound.ts
similarity index 100%
rename from email/src/worker/services/outbound.ts
rename to src/worker/services/outbound.ts
diff --git a/email/src/worker/services/push.ts b/src/worker/services/push.ts
similarity index 100%
rename from email/src/worker/services/push.ts
rename to src/worker/services/push.ts
diff --git a/email/src/worker/services/resend.ts b/src/worker/services/resend.ts
similarity index 100%
rename from email/src/worker/services/resend.ts
rename to src/worker/services/resend.ts
diff --git a/email/src/worker/services/sessions.ts b/src/worker/services/sessions.ts
similarity index 100%
rename from email/src/worker/services/sessions.ts
rename to src/worker/services/sessions.ts
diff --git a/email/src/worker/services/webpush.ts b/src/worker/services/webpush.ts
similarity index 100%
rename from email/src/worker/services/webpush.ts
rename to src/worker/services/webpush.ts
diff --git a/email/src/worker/tsconfig.json b/src/worker/tsconfig.json
similarity index 100%
rename from email/src/worker/tsconfig.json
rename to src/worker/tsconfig.json
diff --git a/email/src/worker/worker-configuration.d.ts b/src/worker/worker-configuration.d.ts
similarity index 100%
rename from email/src/worker/worker-configuration.d.ts
rename to src/worker/worker-configuration.d.ts
diff --git a/email/svelte.config.js b/svelte.config.js
similarity index 100%
rename from email/svelte.config.js
rename to svelte.config.js
diff --git a/email/test/audit-fixes.test.ts b/test/audit-fixes.test.ts
similarity index 100%
rename from email/test/audit-fixes.test.ts
rename to test/audit-fixes.test.ts
diff --git a/email/test/bounce.test.ts b/test/bounce.test.ts
similarity index 100%
rename from email/test/bounce.test.ts
rename to test/bounce.test.ts
diff --git a/email/test/domains.test.ts b/test/domains.test.ts
similarity index 100%
rename from email/test/domains.test.ts
rename to test/domains.test.ts
diff --git a/email/test/env.d.ts b/test/env.d.ts
similarity index 100%
rename from email/test/env.d.ts
rename to test/env.d.ts
diff --git a/email/test/fcm.test.ts b/test/fcm.test.ts
similarity index 100%
rename from email/test/fcm.test.ts
rename to test/fcm.test.ts
diff --git a/email/test/live.test.ts b/test/live.test.ts
similarity index 100%
rename from email/test/live.test.ts
rename to test/live.test.ts
diff --git a/email/test/mailbox.test.ts b/test/mailbox.test.ts
similarity index 100%
rename from email/test/mailbox.test.ts
rename to test/mailbox.test.ts
diff --git a/email/test/profile.test.ts b/test/profile.test.ts
similarity index 100%
rename from email/test/profile.test.ts
rename to test/profile.test.ts
diff --git a/email/test/review-fixes.test.ts b/test/review-fixes.test.ts
similarity index 100%
rename from email/test/review-fixes.test.ts
rename to test/review-fixes.test.ts
diff --git a/email/test/routing.test.ts b/test/routing.test.ts
similarity index 100%
rename from email/test/routing.test.ts
rename to test/routing.test.ts
diff --git a/email/test/setup.ts b/test/setup.ts
similarity index 100%
rename from email/test/setup.ts
rename to test/setup.ts
diff --git a/email/test/tsconfig.json b/test/tsconfig.json
similarity index 100%
rename from email/test/tsconfig.json
rename to test/tsconfig.json
diff --git a/email/tsconfig.json b/tsconfig.json
similarity index 100%
rename from email/tsconfig.json
rename to tsconfig.json
diff --git a/email/vite.config.ts b/vite.config.ts
similarity index 100%
rename from email/vite.config.ts
rename to vite.config.ts
diff --git a/email/vitest.config.ts b/vitest.config.ts
similarity index 100%
rename from email/vitest.config.ts
rename to vitest.config.ts
diff --git a/email/wrangler.jsonc b/wrangler.jsonc
similarity index 100%
rename from email/wrangler.jsonc
rename to wrangler.jsonc