From 3b50e31e55dba7ecfe03d67b015e3eaab97421a6 Mon Sep 17 00:00:00 2001 From: gdz66601 Date: Sun, 30 Aug 2026 07:51:22 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20add=20native=20Android=20client=20a?= =?UTF-8?q?nd=20API=20v1=20/=20=E6=96=B0=E5=A2=9E=E5=8E=9F=E7=94=9F=20Andr?= =?UTF-8?q?oid=20=E5=AE=A2=E6=88=B7=E7=AB=AF=E4=B8=8E=20API=20v1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/d1-migration-manifest.mjs | 28 + .github/workflows/android-ci.yml | 55 ++ .github/workflows/android-release.yml | 115 ++++ .github/workflows/deploy-demo.yml | 4 +- .github/workflows/deploy-worker.yml | 14 +- .gitignore | 8 + README.en.md | 11 + README.ja.md | 11 + README.md | 11 + android/app/build.gradle.kts | 131 ++++ android/app/proguard-rules.pro | 3 + .../1.json | 420 ++++++++++++ .../feature/auth/ServerSetupScreenTest.kt | 21 + android/app/src/debug/AndroidManifest.xml | 7 + android/app/src/main/AndroidManifest.xml | 52 ++ .../aozorae/edgechat/EdgeChatApplication.kt | 19 + .../java/com/aozorae/edgechat/MainActivity.kt | 57 ++ .../aozorae/edgechat/core/database/Daos.kt | 120 ++++ .../core/database/EdgeChatDatabase.kt | 23 + .../edgechat/core/database/Entities.kt | 76 +++ .../aozorae/edgechat/core/database/Mappers.kt | 60 ++ .../core/diagnostics/DiagnosticLog.kt | 28 + .../edgechat/core/network/EdgeChatApi.kt | 124 ++++ .../edgechat/core/network/NetworkSupport.kt | 142 ++++ .../edgechat/core/network/dto/ApiDtos.kt | 292 ++++++++ .../core/realtime/RealtimeCoordinator.kt | 164 +++++ .../core/repository/AttachmentRepository.kt | 63 ++ .../core/repository/ChatRepository.kt | 189 ++++++ .../core/repository/OutboxRepository.kt | 166 +++++ .../core/repository/ServerRepository.kt | 69 ++ .../core/repository/SessionRepository.kt | 113 ++++ .../edgechat/core/session/ServerStore.kt | 93 +++ .../edgechat/core/session/TokenVault.kt | 111 ++++ .../java/com/aozorae/edgechat/di/AppModule.kt | 68 ++ .../edgechat/feature/app/AppViewModel.kt | 167 +++++ .../edgechat/feature/auth/LoginScreen.kt | 86 +++ .../feature/auth/ServerSetupScreen.kt | 72 ++ .../aozorae/edgechat/feature/chat/ChatPane.kt | 260 ++++++++ .../edgechat/feature/chat/ChatViewModel.kt | 179 +++++ .../feature/chat/GroupManagementDialog.kt | 99 +++ .../feature/conversations/ConversationPane.kt | 193 ++++++ .../feature/settings/SettingsSheet.kt | 106 +++ .../com/aozorae/edgechat/ui/EdgeChatApp.kt | 190 ++++++ .../com/aozorae/edgechat/ui/theme/Theme.kt | 42 ++ .../aozorae/edgechat/worker/OutboxWorker.kt | 25 + .../res/drawable/ic_edgechat_foreground.xml | 13 + .../res/mipmap-anydpi-v26/ic_launcher.xml | 5 + .../mipmap-anydpi-v26/ic_launcher_round.xml | 5 + android/app/src/main/res/values/colors.xml | 3 + android/app/src/main/res/values/strings.xml | 3 + android/app/src/main/res/values/themes.xml | 9 + .../main/res/xml/data_extraction_rules.xml | 9 + android/app/src/main/res/xml/file_paths.xml | 5 + .../edgechat/core/network/ApiDtosTest.kt | 22 + .../edgechat/core/session/ServerStoreTest.kt | 32 + android/build.gradle.kts | 8 + android/gradle.properties | 4 + android/gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43453 bytes .../gradle/wrapper/gradle-wrapper.properties | 7 + android/gradlew | 249 +++++++ android/gradlew.bat | 92 +++ android/settings.gradle.kts | 18 + docs/api/edgechat-v1.openapi.yaml | 628 ++++++++++++++++++ docs/api/websocket-v1.md | 35 + test/android-workflows.test.js | 40 ++ test/api-v1-contract.test.js | 59 ++ test/message-deletion.test.js | 6 +- test/message-delivery.test.js | 12 +- test/mobile-api-v1.test.js | 294 ++++++++ test/support/d1.js | 64 ++ .../2026-08-30-mobile-client-v1.sql | 80 +++ .../2026-08-30-native-client-hardening.sql | 12 + worker/schema.sql | 87 +++ worker/src/api/upload.js | 106 +-- worker/src/api/v1.js | 307 +++++++++ worker/src/auth.js | 13 +- worker/src/data/messages.js | 197 +++++- worker/src/data/uploaded-files.js | 47 +- worker/src/do-bridge.js | 13 + worker/src/do/ChannelRoom.js | 73 +- worker/src/do/UserInbox.js | 2 +- worker/src/errors.js | 3 +- worker/src/gc.js | 67 ++ worker/src/index.js | 23 +- worker/src/message-deletion.js | 4 +- worker/src/message-submission.js | 39 +- worker/src/middleware.js | 8 +- worker/src/mobile-session.js | 202 ++++++ worker/src/realtime-tickets.js | 85 +++ worker/src/session.js | 19 + worker/src/unread-projection.js | 5 +- worker/src/utils.js | 14 + 92 files changed, 7205 insertions(+), 110 deletions(-) create mode 100644 .github/workflows/android-ci.yml create mode 100644 .github/workflows/android-release.yml create mode 100644 android/app/build.gradle.kts create mode 100644 android/app/proguard-rules.pro create mode 100644 android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/1.json create mode 100644 android/app/src/androidTest/java/com/aozorae/edgechat/feature/auth/ServerSetupScreenTest.kt create mode 100644 android/app/src/debug/AndroidManifest.xml create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/java/com/aozorae/edgechat/EdgeChatApplication.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/MainActivity.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/database/Daos.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/database/EdgeChatDatabase.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/database/Entities.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/database/Mappers.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/diagnostics/DiagnosticLog.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/network/EdgeChatApi.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/network/NetworkSupport.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/realtime/RealtimeCoordinator.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/repository/AttachmentRepository.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/repository/ChatRepository.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/repository/ServerRepository.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/repository/SessionRepository.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/session/ServerStore.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/core/session/TokenVault.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/feature/app/AppViewModel.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/feature/auth/LoginScreen.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/feature/auth/ServerSetupScreen.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/feature/chat/GroupManagementDialog.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/feature/conversations/ConversationPane.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/feature/settings/SettingsSheet.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/ui/theme/Theme.kt create mode 100644 android/app/src/main/java/com/aozorae/edgechat/worker/OutboxWorker.kt create mode 100644 android/app/src/main/res/drawable/ic_edgechat_foreground.xml create mode 100644 android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml create mode 100644 android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml create mode 100644 android/app/src/main/res/values/colors.xml create mode 100644 android/app/src/main/res/values/strings.xml create mode 100644 android/app/src/main/res/values/themes.xml create mode 100644 android/app/src/main/res/xml/data_extraction_rules.xml create mode 100644 android/app/src/main/res/xml/file_paths.xml create mode 100644 android/app/src/test/java/com/aozorae/edgechat/core/network/ApiDtosTest.kt create mode 100644 android/app/src/test/java/com/aozorae/edgechat/core/session/ServerStoreTest.kt create mode 100644 android/build.gradle.kts create mode 100644 android/gradle.properties create mode 100644 android/gradle/wrapper/gradle-wrapper.jar create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100755 android/gradlew create mode 100644 android/gradlew.bat create mode 100644 android/settings.gradle.kts create mode 100644 docs/api/edgechat-v1.openapi.yaml create mode 100644 docs/api/websocket-v1.md create mode 100644 test/android-workflows.test.js create mode 100644 test/api-v1-contract.test.js create mode 100644 test/mobile-api-v1.test.js create mode 100644 test/support/d1.js create mode 100644 worker/migrations/2026-08-30-mobile-client-v1.sql create mode 100644 worker/migrations/2026-08-30-native-client-hardening.sql create mode 100644 worker/src/api/v1.js create mode 100644 worker/src/mobile-session.js create mode 100644 worker/src/realtime-tickets.js diff --git a/.github/scripts/d1-migration-manifest.mjs b/.github/scripts/d1-migration-manifest.mjs index 88df5ab6..17e47078 100644 --- a/.github/scripts/d1-migration-manifest.mjs +++ b/.github/scripts/d1-migration-manifest.mjs @@ -91,4 +91,32 @@ export const D1_MIGRATIONS = [ file: "worker/migrations/2026-08-20-user-ban-expiry.sql", artifacts: ["column:users.disabled_until"], }, + { + id: "2026-08-30-mobile-client-v1", + file: "worker/migrations/2026-08-30-mobile-client-v1.sql", + artifacts: [ + "column:messages.client_message_id", + "column:uploaded_files.client_upload_id", + "table:device_sessions", + "table:realtime_tickets", + "table:message_events", + "index:idx_messages_client_message", + "index:idx_uploaded_files_client_upload", + "index:idx_device_sessions_refresh_token", + "index:idx_device_sessions_user_installation_active", + "index:idx_device_sessions_user_active", + "index:idx_realtime_tickets_expiry", + "index:idx_message_events_channel_sequence", + "trigger:record_message_created_event", + "trigger:record_message_deleted_event", + ], + }, + { + id: "2026-08-30-native-client-hardening", + file: "worker/migrations/2026-08-30-native-client-hardening.sql", + artifacts: [ + "index:idx_messages_channel_client_message", + "table:message_event_compaction", + ], + }, ]; diff --git a/.github/workflows/android-ci.yml b/.github/workflows/android-ci.yml new file mode 100644 index 00000000..3d818861 --- /dev/null +++ b/.github/workflows/android-ci.yml @@ -0,0 +1,55 @@ +name: Android CI +on: + push: + branches: [master, main] + paths: + - "android/**" + - "docs/api/**" + - "worker/src/api/v1.js" + - "worker/src/mobile-session.js" + - "worker/src/realtime-tickets.js" + - "worker/migrations/2026-08-30-mobile-client-v1.sql" + - "worker/schema.sql" + - ".github/workflows/android-ci.yml" + pull_request: + paths: + - "android/**" + - "docs/api/**" + - "worker/src/api/v1.js" + - "worker/src/mobile-session.js" + - "worker/src/realtime-tickets.js" + - "worker/migrations/2026-08-30-mobile-client-v1.sql" + - "worker/schema.sql" + - ".github/workflows/android-ci.yml" + workflow_dispatch: + +concurrency: + group: android-ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + verify: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@v5 + - name: Validate Gradle wrapper + uses: gradle/actions/wrapper-validation@v4 + - name: Setup Java + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "17" + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + - name: Test, lint and build debug APK + working-directory: android + run: ./gradlew testDebugUnitTest lintDebug assembleDebug --stacktrace + - name: Upload debug APK + uses: actions/upload-artifact@v4 + with: + name: edgechat-debug + path: android/app/build/outputs/apk/debug/app-debug.apk + if-no-files-found: error diff --git a/.github/workflows/android-release.yml b/.github/workflows/android-release.yml new file mode 100644 index 00000000..64681e3d --- /dev/null +++ b/.github/workflows/android-release.yml @@ -0,0 +1,115 @@ +name: Android Release +on: + push: + tags: + - "android-v*" + workflow_dispatch: + inputs: + version: + description: Version without the android-v prefix + required: true + type: string + prerelease: + description: Publish as a prerelease + required: true + default: true + type: boolean + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout + uses: actions/checkout@v5 + with: + fetch-depth: 0 + - name: Validate Gradle wrapper + uses: gradle/actions/wrapper-validation@v4 + - name: Setup Java + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "17" + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + - name: Resolve release version + id: version + shell: bash + env: + INPUT_VERSION: ${{ inputs.version }} + run: | + if [[ "$GITHUB_REF_TYPE" == "tag" ]]; then + version="${GITHUB_REF_NAME#android-v}" + tag="$GITHUB_REF_NAME" + else + version="$INPUT_VERSION" + tag="android-v${INPUT_VERSION}" + fi + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]] + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + - name: Configure release signing + shell: bash + env: + ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: | + for name in ANDROID_KEYSTORE_BASE64 ANDROID_KEYSTORE_PASSWORD ANDROID_KEY_ALIAS ANDROID_KEY_PASSWORD; do + test -n "${!name}" + done + printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > android/release.keystore + cat > android/signing.properties <- + ./gradlew testDebugUnitTest lintRelease assembleRelease bundleRelease + -PedgechatVersionName=${{ steps.version.outputs.version }} + -PedgechatVersionCode=${{ github.run_number }} + --stacktrace + - name: Prepare checksums + shell: bash + run: | + mkdir -p android/release-artifacts + cp android/app/build/outputs/apk/release/app-release.apk android/release-artifacts/edgechat-${{ steps.version.outputs.version }}.apk + cp android/app/build/outputs/bundle/release/app-release.aab android/release-artifacts/edgechat-${{ steps.version.outputs.version }}.aab + cd android/release-artifacts + sha256sum *.apk *.aab > SHA256SUMS.txt + - name: Verify APK signature + shell: bash + run: | + apksigner_path="$(find "$ANDROID_HOME/build-tools" -type f -name apksigner | sort -V | tail -n 1)" + test -n "$apksigner_path" + "$apksigner_path" verify --verbose --print-certs android/release-artifacts/*.apk + jarsigner -verify -strict android/release-artifacts/*.aab + - name: Publish GitHub Release + shell: bash + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ steps.version.outputs.tag }} + PRERELEASE: ${{ github.event_name == 'workflow_dispatch' && inputs.prerelease || contains(steps.version.outputs.version, '-') }} + run: | + prerelease_flag="" + if [[ "$PRERELEASE" == "true" ]]; then prerelease_flag="--prerelease"; fi + if ! git rev-parse "$RELEASE_TAG" >/dev/null 2>&1; then + git tag "$RELEASE_TAG" "$GITHUB_SHA" + git push origin "$RELEASE_TAG" + fi + if gh release view "$RELEASE_TAG" >/dev/null 2>&1; then + gh release upload "$RELEASE_TAG" android/release-artifacts/* --clobber + else + gh release create "$RELEASE_TAG" android/release-artifacts/* \ + --title "EdgeChat Android ${{ steps.version.outputs.version }}" \ + --generate-notes $prerelease_flag + fi + - name: Remove signing material + if: always() + run: rm -f android/release.keystore android/signing.properties diff --git a/.github/workflows/deploy-demo.yml b/.github/workflows/deploy-demo.yml index 5ca1ca6e..77f2e5e9 100644 --- a/.github/workflows/deploy-demo.yml +++ b/.github/workflows/deploy-demo.yml @@ -13,9 +13,9 @@ jobs: contents: read steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@v5 with: node-version: "20" cache: npm diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml index 7338325e..196a79b4 100644 --- a/.github/workflows/deploy-worker.yml +++ b/.github/workflows/deploy-worker.yml @@ -4,6 +4,16 @@ on: branches: - master - main + paths: + - "worker/**" + - "frontend/**" + - "test/**" + - ".github/scripts/**" + - ".github/workflows/deploy-worker.yml" + - "package.json" + - "package-lock.json" + - "biome.json" + - "wrangler.example.toml" workflow_dispatch: inputs: apply_encryption_keyring: @@ -26,9 +36,9 @@ jobs: contents: read steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@v5 with: node-version: "20" cache: npm diff --git a/.gitignore b/.gitignore index c4fe4642..349c4099 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,11 @@ frontend/dist/ frontend/demo-dist/ .playwright-cli/ .tmp/ + +# Android local/build outputs +android/.gradle/ +android/**/build/ +android/local.properties +android/signing.properties +android/*.jks +android/*.keystore diff --git a/README.en.md b/README.en.md index 3de521f0..7be370b3 100644 --- a/README.en.md +++ b/README.en.md @@ -146,6 +146,17 @@ GitHub Actions deployment is recommended first — it suits long-term maintenanc - Quick start: - Detailed guide: +### Native Android Client + +The repository's `android/` directory is an independent Kotlin + Jetpack Compose client for Android 8 / API 26 and newer. It depends only on the stable `/api/v1` contract and never packages Vue components or CSS. On first launch, paste a valid HTTPS server origin or open `edgechat://connect?server=https%3A%2F%2Fchat.example.com`; the app validates server capabilities before sign-in. + +- Installation: download `edgechat-*.apk` from GitHub Releases and verify `SHA256SUMS.txt` +- CI: `.github/workflows/android-ci.yml` runs unit tests, Lint, and a Debug APK build +- Release: push an `android-v*` tag or run `Android Release` manually after configuring `ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, and `ANDROID_KEY_PASSWORD` +- Limitation: the first release has no FCM. WebSockets close in the background and incremental sync catches up after returning to the foreground, so background instant notifications are not promised + +Full guide: +
🔐 Privacy & Server-Side Encryption (click to expand) diff --git a/README.ja.md b/README.ja.md index ddcad441..dc69ca12 100644 --- a/README.ja.md +++ b/README.ja.md @@ -146,6 +146,17 @@ GitHub Actions でのデプロイを優先的に推奨します。長期的な - クイックスタート: - 詳細チュートリアル: +### ネイティブ Android クライアント + +リポジトリの `android/` は Android 8 / API 26 以降向けの独立した Kotlin + Jetpack Compose クライアントです。安定した `/api/v1` 契約だけを共有し、Vue コンポーネントや CSS は APK に含めません。初回起動時に有効な HTTPS サーバー URL を入力するか、`edgechat://connect?server=https%3A%2F%2Fchat.example.com` を開くと、ログイン前にサーバー機能を確認します。 + +- インストール:GitHub Releases から `edgechat-*.apk` を取得し、`SHA256SUMS.txt` を確認 +- CI:`.github/workflows/android-ci.yml` が単体テスト、Lint、Debug APK ビルドを実行 +- リリース:`android-v*` タグ、または手動の `Android Release` を使用し、4 つの `ANDROID_KEYSTORE_*` Secret を設定 +- 制限:初版は FCM 非対応です。バックグラウンドでは WebSocket を閉じ、フォアグラウンド復帰時に差分同期するため、バックグラウンド即時通知は保証しません + +詳細: +
🔐 プライバシーとサーバー側暗号化の説明(クリックで展開) diff --git a/README.md b/README.md index cab04e22..6d99199d 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,17 @@ EdgeChat 是一个部署在 Cloudflare 上的团队聊天系统:账号体系 - 快速开始: - 详细教程: +### 原生 Android 客户端 + +仓库内的 `android/` 是独立的 Kotlin + Jetpack Compose 客户端(Android 8 / API 26 起),只依赖稳定的 `/api/v1` 协议,不复用网页组件或 CSS。首次启动粘贴有效 HTTPS 服务器地址,或打开 `edgechat://connect?server=https%3A%2F%2Fchat.example.com`,客户端会先校验服务器能力再登录。 + +- 安装包:从 GitHub Releases 下载 `edgechat-*.apk` 并核对 `SHA256SUMS.txt` +- CI:`.github/workflows/android-ci.yml` 运行单元测试、Lint 和 Debug APK 构建 +- 发布:推送 `android-v*` 标签或手动运行 `Android Release`,需要配置 `ANDROID_KEYSTORE_BASE64`、`ANDROID_KEYSTORE_PASSWORD`、`ANDROID_KEY_ALIAS`、`ANDROID_KEY_PASSWORD` +- 限制:首版不接入 FCM,应用进入后台后会关闭 WebSocket;恢复前台时通过增量同步补齐消息,不承诺后台即时通知 + +完整说明: +
🔐 隐私与服务端加密说明(点击展开) diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 00000000..4c028717 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,131 @@ +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") + id("com.google.devtools.ksp") + id("com.google.dagger.hilt.android") +} + +val signingProperties = Properties().apply { + val file = rootProject.file("signing.properties") + if (file.exists()) file.inputStream().use(::load) +} + +android { + namespace = "com.aozorae.edgechat" + compileSdk = 35 + + defaultConfig { + applicationId = "com.aozorae.edgechat" + minSdk = 26 + targetSdk = 35 + versionCode = providers.gradleProperty("edgechatVersionCode").orNull?.toIntOrNull() ?: 1 + versionName = providers.gradleProperty("edgechatVersionName").orNull ?: "0.1.0" + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + vectorDrawables.useSupportLibrary = true + } + + signingConfigs { + if (signingProperties.isNotEmpty()) { + create("release") { + storeFile = rootProject.file(signingProperties.getProperty("storeFile")) + storePassword = signingProperties.getProperty("storePassword") + keyAlias = signingProperties.getProperty("keyAlias") + keyPassword = signingProperties.getProperty("keyPassword") + } + } + } + + buildTypes { + debug { + applicationIdSuffix = ".debug" + versionNameSuffix = "-debug" + } + release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + if (signingProperties.isNotEmpty()) signingConfig = signingConfigs.getByName("release") + } + } + + buildFeatures { + compose = true + buildConfig = true + } + + packaging { + resources.excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions.jvmTarget = "17" + +} + +ksp { + arg("room.schemaLocation", "$projectDir/schemas") +} + +dependencies { + val composeBom = platform("androidx.compose:compose-bom:2024.10.01") + implementation(composeBom) + androidTestImplementation(composeBom) + + implementation("androidx.core:core-ktx:1.15.0") + implementation("androidx.activity:activity-compose:1.9.3") + implementation("androidx.lifecycle:lifecycle-runtime-compose:2.8.7") + implementation("androidx.lifecycle:lifecycle-process:2.8.7") + implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7") + implementation("androidx.navigation:navigation-compose:2.8.3") + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.ui:ui-tooling-preview") + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.material:material-icons-extended") + + implementation("com.google.dagger:hilt-android:2.52") + ksp("com.google.dagger:hilt-compiler:2.52") + implementation("androidx.hilt:hilt-navigation-compose:1.2.0") + implementation("androidx.hilt:hilt-work:1.2.0") + ksp("androidx.hilt:hilt-compiler:1.2.0") + + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") + implementation("com.squareup.retrofit2:retrofit:2.11.0") + implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0") + + implementation("androidx.room:room-runtime:2.6.1") + implementation("androidx.room:room-ktx:2.6.1") + implementation("androidx.room:room-paging:2.6.1") + ksp("androidx.room:room-compiler:2.6.1") + implementation("androidx.paging:paging-runtime-ktx:3.3.2") + implementation("androidx.paging:paging-compose:3.3.2") + implementation("androidx.datastore:datastore-preferences:1.1.1") + implementation("androidx.work:work-runtime-ktx:2.10.0") + + implementation("io.coil-kt:coil-compose:2.7.0") + implementation("androidx.media3:media3-exoplayer:1.5.0") + implementation("androidx.media3:media3-ui:1.5.0") + implementation("androidx.media3:media3-datasource-okhttp:1.5.0") + + testImplementation("junit:junit:4.13.2") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0") + testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") + testImplementation("androidx.room:room-testing:2.6.1") + androidTestImplementation("androidx.test.ext:junit:1.2.1") + androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1") + androidTestImplementation("androidx.compose.ui:ui-test-junit4") + debugImplementation("androidx.compose.ui:ui-tooling") + debugImplementation("androidx.compose.ui:ui-test-manifest") +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 00000000..e79ce649 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,3 @@ +-keepattributes Signature,*Annotation* +-keep class com.aozorae.edgechat.core.network.dto.** { *; } +-dontwarn org.conscrypt.** diff --git a/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/1.json b/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/1.json new file mode 100644 index 00000000..2a888e1e --- /dev/null +++ b/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/1.json @@ -0,0 +1,420 @@ +{ + "formatVersion": 1, + "database": { + "version": 1, + "identityHash": "78c87c5d41b8f91b25d8e4553887e015", + "entities": [ + { + "tableName": "users", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `username` TEXT NOT NULL, `displayName` TEXT NOT NULL, `avatarUrl` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "username", + "columnName": "username", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "conversations", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `id` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT NOT NULL, `avatarUrl` TEXT NOT NULL, `isGeneral` INTEGER NOT NULL, `isMember` INTEGER NOT NULL, `canManage` INTEGER NOT NULL, `myRole` TEXT NOT NULL, `memberCount` INTEGER NOT NULL, `otherUserId` INTEGER, `lastMessageAt` TEXT, `unreadCount` INTEGER NOT NULL, PRIMARY KEY(`kind`, `id`))", + "fields": [ + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subtitle", + "columnName": "subtitle", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isGeneral", + "columnName": "isGeneral", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isMember", + "columnName": "isMember", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canManage", + "columnName": "canManage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "myRole", + "columnName": "myRole", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "memberCount", + "columnName": "memberCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "otherUserId", + "columnName": "otherUserId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "lastMessageAt", + "columnName": "lastMessageAt", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "unreadCount", + "columnName": "unreadCount", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "kind", + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `roomKind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `clientMessageId` TEXT, `content` TEXT NOT NULL, `createdAt` TEXT NOT NULL, `source` TEXT NOT NULL, `senderKind` TEXT NOT NULL, `senderId` TEXT NOT NULL, `senderUsername` TEXT NOT NULL, `senderDisplayName` TEXT NOT NULL, `senderAvatarUrl` TEXT NOT NULL, `attachmentKey` TEXT, `attachmentName` TEXT, `attachmentType` TEXT, `attachmentSize` INTEGER, `attachmentUrl` TEXT, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "roomKind", + "columnName": "roomKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "clientMessageId", + "columnName": "clientMessageId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderKind", + "columnName": "senderKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderId", + "columnName": "senderId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderUsername", + "columnName": "senderUsername", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderDisplayName", + "columnName": "senderDisplayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderAvatarUrl", + "columnName": "senderAvatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "attachmentKey", + "columnName": "attachmentKey", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentName", + "columnName": "attachmentName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentType", + "columnName": "attachmentType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentSize", + "columnName": "attachmentSize", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "attachmentUrl", + "columnName": "attachmentUrl", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_messages_roomKind_roomId_id", + "unique": false, + "columnNames": [ + "roomKind", + "roomId", + "id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_roomKind_roomId_id` ON `${TABLE_NAME}` (`roomKind`, `roomId`, `id`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "room_sync", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `cursor` INTEGER NOT NULL, PRIMARY KEY(`kind`, `roomId`))", + "fields": [ + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cursor", + "columnName": "cursor", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "kind", + "roomId" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "outbox", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`clientMessageId` TEXT NOT NULL, `roomKind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `content` TEXT NOT NULL, `localAttachmentPath` TEXT, `attachmentName` TEXT, `attachmentType` TEXT, `attachmentSize` INTEGER, `clientUploadId` TEXT, `uploadedKey` TEXT, `uploadedUrl` TEXT, `state` TEXT NOT NULL, `failure` TEXT, `attempts` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`clientMessageId`))", + "fields": [ + { + "fieldPath": "clientMessageId", + "columnName": "clientMessageId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomKind", + "columnName": "roomKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "localAttachmentPath", + "columnName": "localAttachmentPath", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentName", + "columnName": "attachmentName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentType", + "columnName": "attachmentType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentSize", + "columnName": "attachmentSize", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "clientUploadId", + "columnName": "clientUploadId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "uploadedKey", + "columnName": "uploadedKey", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "uploadedUrl", + "columnName": "uploadedUrl", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "failure", + "columnName": "failure", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "clientMessageId" + ] + }, + "indices": [ + { + "name": "index_outbox_createdAt", + "unique": false, + "columnNames": [ + "createdAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_outbox_createdAt` ON `${TABLE_NAME}` (`createdAt`)" + } + ], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '78c87c5d41b8f91b25d8e4553887e015')" + ] + } +} \ No newline at end of file diff --git a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/auth/ServerSetupScreenTest.kt b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/auth/ServerSetupScreenTest.kt new file mode 100644 index 00000000..6a22357e --- /dev/null +++ b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/auth/ServerSetupScreenTest.kt @@ -0,0 +1,21 @@ +package com.aozorae.edgechat.feature.auth + +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import org.junit.Rule +import org.junit.Test + +class ServerSetupScreenTest { + @get:Rule val compose = createComposeRule() + + @Test + fun continueButtonStartsDisabled() { + compose.setContent { + ServerSetupScreen(false, null, "en-US", {}) + } + compose.onNodeWithText("Server address").assertIsDisplayed() + compose.onNodeWithText("Verify and continue").assertIsNotEnabled() + } +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000..81665069 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..ffdf6324 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/com/aozorae/edgechat/EdgeChatApplication.kt b/android/app/src/main/java/com/aozorae/edgechat/EdgeChatApplication.kt new file mode 100644 index 00000000..7fe85d2c --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/EdgeChatApplication.kt @@ -0,0 +1,19 @@ +package com.aozorae.edgechat + +import android.app.Application +import androidx.hilt.work.HiltWorkerFactory +import androidx.work.Configuration +import coil.ImageLoader +import coil.ImageLoaderFactory +import dagger.hilt.android.HiltAndroidApp +import javax.inject.Inject + +@HiltAndroidApp +class EdgeChatApplication : Application(), Configuration.Provider, ImageLoaderFactory { + @Inject lateinit var workerFactory: HiltWorkerFactory + + override val workManagerConfiguration: Configuration + get() = Configuration.Builder().setWorkerFactory(workerFactory).build() + + override fun newImageLoader(): ImageLoader = ImageLoader.Builder(this).crossfade(true).build() +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/MainActivity.kt b/android/app/src/main/java/com/aozorae/edgechat/MainActivity.kt new file mode 100644 index 00000000..5c719def --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/MainActivity.kt @@ -0,0 +1,57 @@ +package com.aozorae.edgechat + +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.core.view.WindowCompat +import androidx.lifecycle.lifecycleScope +import com.aozorae.edgechat.core.realtime.RealtimeCoordinator +import com.aozorae.edgechat.ui.EdgeChatApp +import com.aozorae.edgechat.ui.theme.EdgeChatTheme +import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch + +@AndroidEntryPoint +class MainActivity : ComponentActivity() { + @Inject lateinit var realtime: RealtimeCoordinator + private val deepLinkServer = MutableStateFlow(null) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + WindowCompat.setDecorFitsSystemWindows(window, false) + handleIntent(intent) + setContent { + EdgeChatTheme { + EdgeChatApp(deepLinkServer) + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handleIntent(intent) + } + + override fun onStart() { + super.onStart() + realtime.start() + } + + override fun onStop() { + realtime.stop() + super.onStop() + } + + private fun handleIntent(intent: Intent?) { + val uri = intent?.data ?: return + if (uri.scheme == "edgechat" && uri.host == "connect") { + lifecycleScope.launch { + deepLinkServer.emit(uri.getQueryParameter("server") ?: uri.getQueryParameter("url")) + } + } + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/Daos.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/Daos.kt new file mode 100644 index 00000000..7373bc06 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/Daos.kt @@ -0,0 +1,120 @@ +package com.aozorae.edgechat.core.database + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import kotlinx.coroutines.flow.Flow + +@Dao +interface UserDao { + @Query("SELECT * FROM users ORDER BY displayName COLLATE NOCASE") + fun observeAll(): Flow> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsertAll(users: List) + + @Query("DELETE FROM users") + suspend fun clear() +} + +@Dao +interface ConversationDao { + @Query( + """SELECT * FROM conversations + ORDER BY isGeneral DESC, unreadCount DESC, + CASE WHEN lastMessageAt IS NULL THEN 1 ELSE 0 END, + lastMessageAt DESC, title COLLATE NOCASE""" + ) + fun observeAll(): Flow> + + @Query("SELECT * FROM conversations WHERE kind = :kind AND id = :roomId LIMIT 1") + suspend fun get(kind: String, roomId: Long): ConversationEntity? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsertAll(conversations: List) + + @Query("UPDATE conversations SET unreadCount = :count, lastMessageAt = :createdAt WHERE kind = :kind AND id = :roomId") + suspend fun updateActivity(kind: String, roomId: Long, count: Int, createdAt: String?) + + @Query("UPDATE conversations SET unreadCount = 0 WHERE kind = :kind AND id = :roomId") + suspend fun clearUnread(kind: String, roomId: Long) + + @Query("DELETE FROM conversations") + suspend fun clear() +} + +@Dao +interface MessageDao { + @Query("SELECT * FROM messages WHERE roomKind = :kind AND roomId = :roomId ORDER BY id ASC") + fun observeRoom(kind: String, roomId: Long): Flow> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsertAll(messages: List) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsert(message: MessageEntity) + + @Query("DELETE FROM messages WHERE id = :messageId") + suspend fun delete(messageId: Long) + + @Query("DELETE FROM messages WHERE roomKind = :kind AND roomId = :roomId") + suspend fun deleteRoom(kind: String, roomId: Long) + + @Query("SELECT MIN(id) FROM messages WHERE roomKind = :kind AND roomId = :roomId") + suspend fun oldestId(kind: String, roomId: Long): Long? + + @Query("SELECT MAX(id) FROM messages WHERE roomKind = :kind AND roomId = :roomId") + suspend fun latestId(kind: String, roomId: Long): Long? + + @Query("DELETE FROM messages") + suspend fun clear() +} + +@Dao +interface RoomSyncDao { + @Query("SELECT cursor FROM room_sync WHERE kind = :kind AND roomId = :roomId") + suspend fun cursor(kind: String, roomId: Long): Long? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsert(sync: RoomSyncEntity) + + @Query("DELETE FROM room_sync") + suspend fun clear() +} + +@Dao +interface OutboxDao { + @Query("SELECT * FROM outbox WHERE roomKind = :kind AND roomId = :roomId ORDER BY createdAt ASC") + fun observeRoom(kind: String, roomId: Long): Flow> + + @Query("SELECT * FROM outbox WHERE state IN ('PENDING', 'RETRY') ORDER BY createdAt ASC LIMIT 1") + suspend fun next(): OutboxEntity? + + @Query("SELECT COUNT(*) FROM outbox WHERE state IN ('PENDING', 'RETRY')") + suspend fun pendingCount(): Int + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsert(item: OutboxEntity) + + @Query("UPDATE outbox SET state = :state, failure = :failure WHERE clientMessageId = :id") + suspend fun updateState(id: String, state: String, failure: String? = null) + + @Query("UPDATE outbox SET state = 'RETRY', failure = :failure, attempts = attempts + 1 WHERE clientMessageId = :id") + suspend fun markFailed(id: String, failure: String) + + @Query("UPDATE outbox SET state = 'RETRY', failure = NULL WHERE state IN ('UPLOADING', 'SENDING')") + suspend fun recoverInFlight() + + @Query("UPDATE outbox SET uploadedKey = :key, uploadedUrl = :url, state = 'PENDING', failure = NULL WHERE clientMessageId = :id") + suspend fun setUploaded(id: String, key: String, url: String) + + @Query("SELECT * FROM outbox WHERE clientMessageId = :id LIMIT 1") + suspend fun get(id: String): OutboxEntity? + + @Query("DELETE FROM outbox WHERE clientMessageId = :id") + suspend fun delete(id: String) + + @Query("DELETE FROM outbox") + suspend fun clear() +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/EdgeChatDatabase.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/EdgeChatDatabase.kt new file mode 100644 index 00000000..21000a1f --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/EdgeChatDatabase.kt @@ -0,0 +1,23 @@ +package com.aozorae.edgechat.core.database + +import androidx.room.Database +import androidx.room.RoomDatabase + +@Database( + entities = [ + UserEntity::class, + ConversationEntity::class, + MessageEntity::class, + RoomSyncEntity::class, + OutboxEntity::class, + ], + version = 1, + exportSchema = true, +) +abstract class EdgeChatDatabase : RoomDatabase() { + abstract fun users(): UserDao + abstract fun conversations(): ConversationDao + abstract fun messages(): MessageDao + abstract fun roomSync(): RoomSyncDao + abstract fun outbox(): OutboxDao +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/Entities.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/Entities.kt new file mode 100644 index 00000000..021df368 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/Entities.kt @@ -0,0 +1,76 @@ +package com.aozorae.edgechat.core.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = "users") +data class UserEntity( + @PrimaryKey val id: Long, + val username: String, + val displayName: String, + val avatarUrl: String, +) + +@Entity(tableName = "conversations", primaryKeys = ["kind", "id"]) +data class ConversationEntity( + val kind: String, + val id: Long, + val title: String, + val subtitle: String, + val avatarUrl: String, + val isGeneral: Boolean, + val isMember: Boolean, + val canManage: Boolean, + val myRole: String, + val memberCount: Int, + val otherUserId: Long?, + val lastMessageAt: String?, + val unreadCount: Int, +) + +@Entity( + tableName = "messages", + indices = [Index(value = ["roomKind", "roomId", "id"])], +) +data class MessageEntity( + @PrimaryKey val id: Long, + val roomKind: String, + val roomId: Long, + val clientMessageId: String?, + val content: String, + val createdAt: String, + val source: String, + val senderKind: String, + val senderId: String, + val senderUsername: String, + val senderDisplayName: String, + val senderAvatarUrl: String, + val attachmentKey: String?, + val attachmentName: String?, + val attachmentType: String?, + val attachmentSize: Long?, + val attachmentUrl: String?, +) + +@Entity(tableName = "room_sync", primaryKeys = ["kind", "roomId"]) +data class RoomSyncEntity(val kind: String, val roomId: Long, val cursor: Long) + +@Entity(tableName = "outbox", indices = [Index(value = ["createdAt"])]) +data class OutboxEntity( + @PrimaryKey val clientMessageId: String, + val roomKind: String, + val roomId: Long, + val content: String, + val localAttachmentPath: String?, + val attachmentName: String?, + val attachmentType: String?, + val attachmentSize: Long?, + val clientUploadId: String?, + val uploadedKey: String?, + val uploadedUrl: String?, + val state: String, + val failure: String?, + val attempts: Int, + val createdAt: Long, +) diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/Mappers.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/Mappers.kt new file mode 100644 index 00000000..30024a8b --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/Mappers.kt @@ -0,0 +1,60 @@ +package com.aozorae.edgechat.core.database + +import com.aozorae.edgechat.core.network.dto.ChannelDto +import com.aozorae.edgechat.core.network.dto.DmDto +import com.aozorae.edgechat.core.network.dto.MessageDto +import com.aozorae.edgechat.core.network.dto.UserDto + +fun UserDto.toEntity() = UserEntity(id, username, displayName, avatarUrl) + +fun ChannelDto.toEntity() = ConversationEntity( + kind = kind, + id = id, + title = name, + subtitle = description, + avatarUrl = avatarUrl, + isGeneral = isGeneral, + isMember = isMember, + canManage = canManage, + myRole = myRole, + memberCount = memberCount, + otherUserId = null, + lastMessageAt = lastMessageAt, + unreadCount = unreadCount, +) + +fun DmDto.toEntity() = ConversationEntity( + kind = "dm", + id = id, + title = otherUser.displayName, + subtitle = otherUser.username, + avatarUrl = otherUser.avatarUrl, + isGeneral = false, + isMember = true, + canManage = false, + myRole = "member", + memberCount = 2, + otherUserId = otherUser.id, + lastMessageAt = lastMessageAt, + unreadCount = unreadCount, +) + +fun MessageDto.toEntity(kind: String, roomId: Long) = MessageEntity( + id = id, + roomKind = kind, + roomId = roomId, + clientMessageId = clientMessageId, + content = content, + createdAt = createdAt, + source = source, + senderKind = sender.kind, + senderId = sender.id, + senderUsername = sender.username, + senderDisplayName = sender.displayName, + senderAvatarUrl = sender.avatarUrl, + attachmentKey = attachment?.key, + attachmentName = attachment?.name, + attachmentType = attachment?.type, + attachmentSize = attachment?.size, + attachmentUrl = attachment?.url, +) diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/diagnostics/DiagnosticLog.kt b/android/app/src/main/java/com/aozorae/edgechat/core/diagnostics/DiagnosticLog.kt new file mode 100644 index 00000000..b1e8f6f5 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/diagnostics/DiagnosticLog.kt @@ -0,0 +1,28 @@ +package com.aozorae.edgechat.core.diagnostics + +import android.content.Context +import dagger.hilt.android.qualifiers.ApplicationContext +import java.io.File +import java.time.Instant +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class DiagnosticLog @Inject constructor(@ApplicationContext private val context: Context) { + private val entries = ArrayDeque() + + @Synchronized + fun record(event: String) { + val safe = event.replace(Regex("(?i)(token|password|content)=\\S+"), "$1=[redacted]") + entries.addLast("${Instant.now()} $safe") + while (entries.size > 300) entries.removeFirst() + } + + @Synchronized + fun export(): File { + val directory = File(context.cacheDir, "diagnostics").apply { mkdirs() } + return File(directory, "edgechat-diagnostics.txt").apply { + writeText(entries.joinToString("\n")) + } + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/network/EdgeChatApi.kt b/android/app/src/main/java/com/aozorae/edgechat/core/network/EdgeChatApi.kt new file mode 100644 index 00000000..5ec45c7a --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/network/EdgeChatApi.kt @@ -0,0 +1,124 @@ +package com.aozorae.edgechat.core.network + +import com.aozorae.edgechat.core.network.dto.* +import okhttp3.MultipartBody +import okhttp3.RequestBody +import retrofit2.Response +import retrofit2.http.Body +import retrofit2.http.DELETE +import retrofit2.http.GET +import retrofit2.http.Multipart +import retrofit2.http.PATCH +import retrofit2.http.POST +import retrofit2.http.Part +import retrofit2.http.Path +import retrofit2.http.Query + +interface EdgeChatApi { + @GET("api/v1/capabilities") + suspend fun capabilities(): Response + + @POST("api/v1/auth/login") + suspend fun login(@Body request: LoginRequest): Response + + @POST("api/v1/auth/refresh") + suspend fun refresh(@Body request: RefreshRequest): Response + + @POST("api/v1/auth/logout") + suspend fun logout(): Response + + @GET("api/v1/auth/session") + suspend fun session(): Response + + @GET("api/v1/bootstrap") + suspend fun bootstrap(): Response + + @GET("api/v1/rooms/{kind}/{id}/messages") + suspend fun messages( + @Path("kind") kind: String, + @Path("id") roomId: Long, + @Query("before") before: Long? = null, + @Query("limit") limit: Int = 50, + ): Response + + @GET("api/v1/rooms/{kind}/{id}/sync") + suspend fun sync( + @Path("kind") kind: String, + @Path("id") roomId: Long, + @Query("cursor") cursor: Long, + @Query("limit") limit: Int = 100, + ): Response + + @POST("api/v1/rooms/{kind}/{id}/messages") + suspend fun sendMessage( + @Path("kind") kind: String, + @Path("id") roomId: Long, + @Body request: SendMessageRequest, + ): Response + + @DELETE("api/v1/rooms/{kind}/{id}/messages/{messageId}") + suspend fun deleteMessage( + @Path("kind") kind: String, + @Path("id") roomId: Long, + @Path("messageId") messageId: Long, + ): Response + + @POST("api/v1/rooms/{kind}/{id}/read") + suspend fun markRead( + @Path("kind") kind: String, + @Path("id") roomId: Long, + @Body request: ReadRequest, + ): Response + + @POST("api/v1/realtime/tickets") + suspend fun realtimeTicket(@Body request: TicketRequest): Response + + @Multipart + @POST("api/v1/uploads") + suspend fun upload( + @Part file: MultipartBody.Part, + @Part("clientUploadId") clientUploadId: RequestBody, + ): Response + + @GET("api/v1/channels") + suspend fun channels(): Response + + @POST("api/v1/channels") + suspend fun createGroup(@Body request: CreateGroupRequest): Response + + @POST("api/v1/channels/{id}/join") + suspend fun joinChannel(@Path("id") channelId: Long): Response + + @GET("api/v1/channels/{id}/members") + suspend fun members(@Path("id") channelId: Long): Response + + @POST("api/v1/channels/{id}/invite") + suspend fun inviteMembers( + @Path("id") channelId: Long, + @Body request: InviteMembersRequest, + ): Response + + @DELETE("api/v1/channels/{channelId}/members/{userId}") + suspend fun removeMember( + @Path("channelId") channelId: Long, + @Path("userId") userId: Long, + ): Response + + @PATCH("api/v1/channels/{id}") + suspend fun updateChannel( + @Path("id") channelId: Long, + @Body request: UpdateChannelRequest, + ): Response + + @DELETE("api/v1/channels/{id}") + suspend fun deleteChannel(@Path("id") channelId: Long): Response + + @POST("api/v1/dm/open") + suspend fun openDm(@Body request: OpenDmRequest): Response + + @PATCH("api/v1/me/profile") + suspend fun updateProfile(@Body request: UpdateProfileRequest): Response + + @POST("api/v1/auth/change-password") + suspend fun changePassword(@Body request: ChangePasswordRequest): Response +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/network/NetworkSupport.kt b/android/app/src/main/java/com/aozorae/edgechat/core/network/NetworkSupport.kt new file mode 100644 index 00000000..c0c36df8 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/network/NetworkSupport.kt @@ -0,0 +1,142 @@ +package com.aozorae.edgechat.core.network + +import com.aozorae.edgechat.BuildConfig +import com.aozorae.edgechat.core.diagnostics.DiagnosticLog +import com.aozorae.edgechat.core.network.dto.ApiErrorEnvelope +import com.aozorae.edgechat.core.network.dto.MobileAuthResponse +import com.aozorae.edgechat.core.network.dto.RefreshRequest +import com.aozorae.edgechat.core.session.ServerStore +import com.aozorae.edgechat.core.session.StoredTokens +import com.aozorae.edgechat.core.session.TokenVault +import java.io.IOException +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import okhttp3.Authenticator +import okhttp3.Interceptor +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import okhttp3.Route + +class EdgeChatApiException(val code: String, override val message: String, val status: Int) : IOException(message) + +fun retrofit2.Response.bodyOrThrow(json: Json): T { + if (isSuccessful) return body() ?: throw EdgeChatApiException("empty_response", "服务器返回空响应", code()) + val raw = errorBody()?.string().orEmpty() + val error = runCatching { json.decodeFromString(raw).error }.getOrNull() + throw EdgeChatApiException(error?.code ?: "http_${code()}", error?.message ?: "请求失败", code()) +} + +@Singleton +class ServerUrlInterceptor @Inject constructor(private val serverStore: ServerStore) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + if (request.url.host != PLACEHOLDER_HOST) return chain.proceed(request) + val base = runBlocking { serverStore.baseUrl() } + ?: throw IOException("尚未配置 EdgeChat 服务器") + val target = request.url.newBuilder() + .scheme(java.net.URI(base).scheme) + .host(java.net.URI(base).host) + .port(java.net.URI(base).let { if (it.port > 0) it.port else if (it.scheme == "https") 443 else 80 }) + .build() + return chain.proceed(request.newBuilder().url(target).build()) + } + + companion object { + const val PLACEHOLDER_HOST = "edgechat.invalid" + } +} + +@Singleton +class AuthInterceptor @Inject constructor(private val tokenVault: TokenVault) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + if (request.url.encodedPath in PUBLIC_PATHS) return chain.proceed(request) + val token = runBlocking { tokenVault.accessToken() } + val authenticated = token?.let { + request.newBuilder().header("Authorization", "Bearer $it").build() + } ?: request + return chain.proceed(authenticated) + } + + private companion object { + val PUBLIC_PATHS = setOf( + "/api/v1/capabilities", + "/api/v1/auth/login", + "/api/v1/auth/refresh", + ) + } +} + +@Singleton +class SessionAuthenticator @Inject constructor( + private val serverStore: ServerStore, + private val tokenVault: TokenVault, + private val json: Json, + private val diagnostics: DiagnosticLog, +) : Authenticator { + private val refreshClient = OkHttpClient.Builder().build() + private val lock = Any() + + override fun authenticate(route: Route?, response: Response): Request? { + if (response.request.url.encodedPath.endsWith("/auth/refresh") || responseCount(response) > 1) { + return null + } + return synchronized(lock) { + runBlocking { + val failedToken = response.request.header("Authorization")?.removePrefix("Bearer ") + val current = tokenVault.read() ?: return@runBlocking null + if (current.accessToken != failedToken) { + return@runBlocking response.request.newBuilder() + .header("Authorization", "Bearer ${current.accessToken}") + .build() + } + val base = serverStore.baseUrl() ?: return@runBlocking null + val installationId = serverStore.installationId() + val body = json.encodeToString(RefreshRequest(current.refreshToken, installationId)) + .toRequestBody("application/json".toMediaType()) + val refreshRequest = Request.Builder() + .url("${base}api/v1/auth/refresh") + .post(body) + .build() + val refreshed = runCatching { + refreshClient.newCall(refreshRequest).execute().use { call -> + if (!call.isSuccessful) return@use null + call.body?.string()?.let { json.decodeFromString(it) } + } + }.getOrNull() + if (refreshed == null) { + diagnostics.record("session_refresh_failed status=${response.code}") + tokenVault.clear() + return@runBlocking null + } + tokenVault.save( + StoredTokens( + refreshed.accessToken, + refreshed.refreshToken, + refreshed.accessTokenExpiresAt, + refreshed.refreshTokenExpiresAt, + ), + ) + response.request.newBuilder() + .header("Authorization", "Bearer ${refreshed.accessToken}") + .build() + } + } + } + + private fun responseCount(response: Response): Int { + var current: Response? = response + var count = 0 + while (current != null) { + count += 1 + current = current.priorResponse + } + return count + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt b/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt new file mode 100644 index 00000000..6221a636 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt @@ -0,0 +1,292 @@ +package com.aozorae.edgechat.core.network.dto + +import kotlinx.serialization.Serializable +import kotlinx.serialization.KSerializer +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonPrimitive + +@Serializable +data class SiteDto(val siteName: String = "EdgeChat", val siteIconUrl: String = "") + +@Serializable +data class CapabilitiesResponse( + val apiVersion: Int, + val site: SiteDto, + val limits: LimitsDto, + val features: FeaturesDto, +) + +@Serializable +data class LimitsDto(val maxUploadBytes: Long = 20L * 1024 * 1024, val messageRetentionDays: Int = 7) + +@Serializable +data class FeaturesDto( + val deviceSessions: Boolean = false, + val realtimeTickets: Boolean = false, + val idempotentMessages: Boolean = false, + val idempotentUploads: Boolean = false, + val roomSync: Boolean = false, + val backgroundPush: Boolean = false, +) + +@Serializable +data class DeviceDto(val installationId: String, val name: String, val appVersion: String) + +@Serializable +data class LoginRequest(val username: String, val password: String, val device: DeviceDto) + +@Serializable +data class RefreshRequest(val refreshToken: String, val installationId: String) + +@Serializable +data class MobileAuthResponse( + val accessToken: String, + val accessTokenExpiresAt: String, + val refreshToken: String, + val refreshTokenExpiresAt: String, + val session: SessionDto, +) + +@Serializable +data class SessionDto( + val userId: Long, + val username: String, + val displayName: String, + val avatarUrl: String = "", + val isAdmin: Boolean = false, + val sessionVersion: Int = 0, + val deviceSessionId: String? = null, +) + +@Serializable +data class SessionResponse(val session: SessionDto) + +@Serializable +data class UserDto( + val id: Long, + val username: String, + val displayName: String, + val avatarUrl: String = "", +) + +@Serializable +data class ChannelDto( + val id: Long, + val name: String, + val description: String = "", + val avatarKey: String = "", + val avatarUrl: String = "", + val kind: String, + val isGeneral: Boolean = false, + val ownerDisplayName: String = "", + val isMember: Boolean = true, + val myRole: String = "", + val canManage: Boolean = false, + val memberCount: Int = 0, + val lastMessageAt: String? = null, + val unreadCount: Int = 0, +) + +@Serializable +data class DmDto( + val id: Long, + val kind: String = "dm", + val name: String = "", + val lastMessageAt: String? = null, + val unreadCount: Int = 0, + val otherUser: UserDto, +) + +@Serializable +data class BootstrapResponse( + val users: List = emptyList(), + val channels: List = emptyList(), + val dms: List = emptyList(), +) + +@Serializable +data class SenderDto( + val kind: String, + @Serializable(with = FlexibleStringSerializer::class) + val id: String, + val username: String = "", + val displayName: String, + val avatarUrl: String = "", + val source: String = "edgechat", +) + +@Serializable +data class AttachmentDto( + val key: String, + val name: String, + val type: String, + val size: Long = 0, + val url: String, +) + +@Serializable +data class MessageDto( + val id: Long, + val clientMessageId: String? = null, + val content: String = "", + val createdAt: String, + val source: String = "edgechat", + val sender: SenderDto, + val attachment: AttachmentDto? = null, +) + +@Serializable +data class RoomDto(val id: Long, val kind: String, val name: String, val description: String = "") + +@Serializable +data class RoomMessagesResponse( + val room: RoomDto, + val messages: List, + val syncCursor: Long, +) + +@Serializable +data class SyncEventDto( + val sequence: Long, + val type: String, + val messageId: Long? = null, + val message: MessageDto? = null, + val createdAt: String? = null, +) + +@Serializable +data class RoomSyncResponse( + val events: List, + val nextCursor: Long, + val hasMore: Boolean, +) + +@Serializable +data class SendMessageRequest( + val clientMessageId: String, + val content: String, + val attachment: AttachmentDto? = null, +) + +@Serializable +data class SendMessageResponse(val created: Boolean = true, val message: MessageDto) + +@Serializable +data class ReadRequest(val messageId: Long? = null) + +@Serializable +data class ReadResponse(val ok: Boolean, val lastReadMessageId: Long) + +@Serializable +data class TicketRequest(val scope: String, val roomKind: String? = null, val roomId: Long? = null) + +@Serializable +data class TicketResponse(val ticket: String, val expiresAt: String) + +@Serializable +data class UploadResponse(val created: Boolean = true, val file: AttachmentDto) + +@Serializable +data class ChannelsResponse( + val channels: List = emptyList(), + val publicChannels: List = emptyList(), + val privateChannels: List = emptyList(), +) + +@Serializable +data class CreateGroupRequest( + val name: String, + val description: String = "", + val kind: String, + val memberUserIds: List = emptyList(), +) + +@Serializable +data class ChannelResponse(val channel: ChannelDto) + +@Serializable +data class ChannelUpdateResponse(val channel: ChannelUpdateDto? = null, val ok: Boolean = true) + +@Serializable +data class ChannelUpdateDto( + val id: Long, + val name: String, + val avatarKey: String = "", + val avatarUrl: String = "", +) + +@Serializable +data class MemberDto( + val id: Long, + val username: String, + val displayName: String, + val avatarUrl: String = "", + val role: String, + val joinedAt: String = "", +) + +@Serializable +data class MembersResponse(val room: ChannelDto, val members: List) + +@Serializable +data class InviteMembersRequest(val userIds: List) + +@Serializable +data class MembersMutationResponse(val ok: Boolean, val members: List) + +@Serializable +data class UpdateChannelRequest(val name: String? = null, val avatarKey: String? = null) + +@Serializable +data class OpenDmRequest(val userId: Long) + +@Serializable +data class DmResponse(val dm: DmDto) + +@Serializable +data class UpdateProfileRequest( + val displayName: String, + val avatarKey: String? = null, + val clearAvatar: Boolean = false, +) + +@Serializable +data class ChangePasswordRequest(val currentPassword: String, val newPassword: String) + +@Serializable +data class OkResponse(val ok: Boolean) + +@Serializable +data class ApiErrorEnvelope(val error: ApiErrorDto) + +@Serializable +data class ApiErrorDto(val code: String = "invalid_request", val message: String) + +@Serializable +data class RealtimeEnvelope( + val protocolVersion: Int = 1, + val type: String, + val room: RoomDto? = null, + val message: MessageDto? = null, + val messageId: Long? = null, + val createdAt: String? = null, + val unreadCount: Int? = null, + val error: String? = null, +) + +object FlexibleStringSerializer : KSerializer { + override val descriptor: SerialDescriptor = + PrimitiveSerialDescriptor("FlexibleString", PrimitiveKind.STRING) + + override fun deserialize(decoder: Decoder): String { + val jsonDecoder = decoder as? JsonDecoder ?: return decoder.decodeString() + return (jsonDecoder.decodeJsonElement() as JsonPrimitive).content + } + + override fun serialize(encoder: Encoder, value: String) = encoder.encodeString(value) +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/realtime/RealtimeCoordinator.kt b/android/app/src/main/java/com/aozorae/edgechat/core/realtime/RealtimeCoordinator.kt new file mode 100644 index 00000000..1a20aa5c --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/realtime/RealtimeCoordinator.kt @@ -0,0 +1,164 @@ +package com.aozorae.edgechat.core.realtime + +import com.aozorae.edgechat.core.diagnostics.DiagnosticLog +import com.aozorae.edgechat.core.network.EdgeChatApi +import com.aozorae.edgechat.core.network.bodyOrThrow +import com.aozorae.edgechat.core.network.dto.RealtimeEnvelope +import com.aozorae.edgechat.core.network.dto.TicketRequest +import com.aozorae.edgechat.core.repository.ChatRepository +import com.aozorae.edgechat.core.repository.RoomIdentity +import com.aozorae.edgechat.core.session.ServerStore +import com.aozorae.edgechat.core.session.TokenVault +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.serialization.json.Json +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener + +@Singleton +class RealtimeCoordinator @Inject constructor( + private val api: EdgeChatApi, + private val client: OkHttpClient, + private val serverStore: ServerStore, + private val tokenVault: TokenVault, + private val chatRepository: ChatRepository, + private val json: Json, + private val diagnostics: DiagnosticLog, +) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val connections = ConcurrentHashMap() + private val reconnectJobs = ConcurrentHashMap() + @Volatile private var foreground = false + @Volatile private var currentRoom: RoomIdentity? = null + @Volatile private var generation = 0L + + fun start() { + foreground = true + generation += 1 + val activeGeneration = generation + scope.launch { + if (tokenVault.read() == null || serverStore.baseUrl() == null) return@launch + runCatching { + chatRepository.bootstrap() + currentRoom?.let { chatRepository.sync(it) } + }.onFailure { diagnostics.record("foreground_sync_failed reason=${it.javaClass.simpleName}") } + connect("inbox", null, activeGeneration, 0) + currentRoom?.let { connect(roomKey(it), it, activeGeneration, 0) } + } + } + + fun stop() { + foreground = false + generation += 1 + reconnectJobs.values.forEach(Job::cancel) + reconnectJobs.clear() + connections.values.forEach { it.close(1000, "background") } + connections.clear() + } + + fun setRoom(room: RoomIdentity?) { + val previous = currentRoom + if (previous == room) return + currentRoom = room + previous?.let { key -> + val socketKey = roomKey(key) + reconnectJobs.remove(socketKey)?.cancel() + connections.remove(socketKey)?.close(1000, "room_changed") + } + if (foreground && room != null) connect(roomKey(room), room, generation, 0) + } + + private fun connect(key: String, room: RoomIdentity?, expectedGeneration: Long, attempt: Int) { + reconnectJobs.remove(key)?.cancel() + reconnectJobs[key] = scope.launch { + if (!foreground || generation != expectedGeneration) return@launch + if (tokenVault.read() == null || serverStore.baseUrl() == null) return@launch + if (attempt > 0) delay(RECONNECT_DELAYS[(attempt - 1).coerceAtMost(RECONNECT_DELAYS.lastIndex)]) + runCatching { + val request = if (room == null) { + TicketRequest(scope = "inbox") + } else { + TicketRequest(scope = "room", roomKind = room.kind, roomId = room.id) + } + val ticket = api.realtimeTicket(request).bodyOrThrow(json).ticket + val base = requireNotNull(serverStore.baseUrl()).toHttpUrl() + val wsUrl = base.newBuilder() + .scheme(if (base.isHttps) "wss" else "ws") + .addPathSegments("api/v1/realtime/ws") + .addQueryParameter("ticket", ticket) + .build() + val socket = client.newWebSocket( + Request.Builder().url(wsUrl).build(), + listener(key, room, expectedGeneration, attempt), + ) + connections.put(key, socket)?.cancel() + }.onFailure { + diagnostics.record("realtime_connect_failed scope=$key reason=${it.javaClass.simpleName}") + scheduleReconnect(key, room, expectedGeneration, attempt + 1) + } + } + } + + private fun listener( + key: String, + room: RoomIdentity?, + expectedGeneration: Long, + attempt: Int, + ) = object : WebSocketListener() { + override fun onMessage(webSocket: WebSocket, text: String) { + if (generation != expectedGeneration || connections[key] !== webSocket) return + val envelope = runCatching { json.decodeFromString(text) }.getOrNull() + if (envelope == null || envelope.protocolVersion != 1) { + diagnostics.record("realtime_frame_rejected scope=$key") + return + } + scope.launch { + runCatching { chatRepository.handleRealtime(envelope, room) } + .onFailure { diagnostics.record("realtime_apply_failed scope=$key") } + } + } + + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + val wasCurrent = connections.remove(key, webSocket) + if (wasCurrent && code !in NON_RETRYABLE_CODES) { + scheduleReconnect(key, room, expectedGeneration, attempt + 1) + } + } + + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + val wasCurrent = connections.remove(key, webSocket) + diagnostics.record("realtime_failure scope=$key status=${response?.code ?: 0}") + if (wasCurrent && response?.code !in listOf(401, 403)) { + scheduleReconnect(key, room, expectedGeneration, attempt + 1) + } + } + } + + private fun scheduleReconnect( + key: String, + room: RoomIdentity?, + expectedGeneration: Long, + attempt: Int, + ) { + if (!foreground || generation != expectedGeneration) return + connect(key, room, expectedGeneration, attempt) + } + + private fun roomKey(room: RoomIdentity) = "room:${room.kind}:${room.id}" + + private companion object { + val RECONNECT_DELAYS = listOf(1_000L, 2_000L, 5_000L) + val NON_RETRYABLE_CODES = setOf(1000, 1008, 4401, 4403) + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/AttachmentRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/AttachmentRepository.kt new file mode 100644 index 00000000..59504909 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/AttachmentRepository.kt @@ -0,0 +1,63 @@ +package com.aozorae.edgechat.core.repository + +import android.content.ContentResolver +import android.content.Context +import android.net.Uri +import android.provider.OpenableColumns +import androidx.core.content.FileProvider +import com.aozorae.edgechat.core.session.ServerStore +import dagger.hilt.android.qualifiers.ApplicationContext +import java.io.File +import java.util.UUID +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient +import okhttp3.Request + +data class PendingAttachment(val path: String, val name: String, val type: String, val size: Long) + +@Singleton +class AttachmentRepository @Inject constructor( + @ApplicationContext private val context: Context, + private val client: OkHttpClient, + private val serverStore: ServerStore, +) { + suspend fun import(uri: Uri): PendingAttachment = withContext(Dispatchers.IO) { + val resolver = context.contentResolver + val name = resolver.displayName(uri) ?: "attachment" + val type = resolver.getType(uri) ?: "application/octet-stream" + val directory = File(context.filesDir, "pending").apply { mkdirs() } + val target = File(directory, UUID.randomUUID().toString()) + resolver.openInputStream(uri).use { input -> + requireNotNull(input) { "无法读取所选文件" } + target.outputStream().use(input::copyTo) + } + PendingAttachment(target.absolutePath, name, type, target.length()) + } + + suspend fun download(relativeUrl: String, filename: String): Uri = withContext(Dispatchers.IO) { + val base = requireNotNull(serverStore.baseUrl()) + val url = if (relativeUrl.startsWith("http")) relativeUrl else "$base${relativeUrl.trimStart('/')}" + val directory = File(context.cacheDir, "downloads").apply { mkdirs() } + val safeName = filename.replace(Regex("[\\\\/:*?\"<>|]"), "_") + val target = File(directory, safeName) + client.newCall(Request.Builder().url(url).build()).execute().use { response -> + if (!response.isSuccessful) error("附件下载失败") + response.body?.byteStream()?.use { input -> target.outputStream().use(input::copyTo) } + } + FileProvider.getUriForFile(context, "${context.packageName}.files", target) + } + + suspend fun clearPrivateFiles() = withContext(Dispatchers.IO) { + File(context.filesDir, "pending").deleteRecursively() + File(context.cacheDir, "downloads").deleteRecursively() + File(context.cacheDir, "diagnostics").deleteRecursively() + } + + private fun ContentResolver.displayName(uri: Uri): String? = + query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) cursor.getString(0) else null + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/ChatRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/ChatRepository.kt new file mode 100644 index 00000000..6266b62f --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/ChatRepository.kt @@ -0,0 +1,189 @@ +package com.aozorae.edgechat.core.repository + +import androidx.room.withTransaction +import com.aozorae.edgechat.core.database.EdgeChatDatabase +import com.aozorae.edgechat.core.database.MessageEntity +import com.aozorae.edgechat.core.database.RoomSyncEntity +import com.aozorae.edgechat.core.database.toEntity +import com.aozorae.edgechat.core.network.EdgeChatApi +import com.aozorae.edgechat.core.network.EdgeChatApiException +import com.aozorae.edgechat.core.network.bodyOrThrow +import com.aozorae.edgechat.core.network.dto.CreateGroupRequest +import com.aozorae.edgechat.core.network.dto.InviteMembersRequest +import com.aozorae.edgechat.core.network.dto.OpenDmRequest +import com.aozorae.edgechat.core.network.dto.ReadRequest +import com.aozorae.edgechat.core.network.dto.RealtimeEnvelope +import com.aozorae.edgechat.core.network.dto.UpdateChannelRequest +import javax.inject.Inject +import javax.inject.Singleton +import java.util.concurrent.ConcurrentHashMap +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.serialization.json.Json + +data class RoomIdentity(val kind: String, val id: Long) + +@Singleton +class ChatRepository @Inject constructor( + private val api: EdgeChatApi, + private val json: Json, + private val database: EdgeChatDatabase, + private val attachments: AttachmentRepository, +) { + private val roomLocks = ConcurrentHashMap() + val conversations = database.conversations().observeAll() + val users = database.users().observeAll() + + fun messages(room: RoomIdentity): Flow> = + database.messages().observeRoom(room.kind, room.id) + + suspend fun bootstrap() { + val payload = api.bootstrap().bodyOrThrow(json) + database.withTransaction { + database.users().clear() + database.conversations().clear() + database.users().upsertAll(payload.users.map { it.toEntity() }) + database.conversations().upsertAll( + payload.channels.map { it.toEntity() } + payload.dms.map { it.toEntity() }, + ) + } + } + + suspend fun loadLatest(room: RoomIdentity) = withRoomLock(room) { + loadLatestUnlocked(room, reset = false) + } + + private suspend fun loadLatestUnlocked(room: RoomIdentity, reset: Boolean) { + val page = api.messages(room.kind, room.id).bodyOrThrow(json) + database.withTransaction { + val existingCursor = database.roomSync().cursor(room.kind, room.id) + if (reset) database.messages().deleteRoom(room.kind, room.id) + database.messages().upsertAll(page.messages.map { it.toEntity(room.kind, room.id) }) + if (reset || existingCursor == null) { + database.roomSync().upsert(RoomSyncEntity(room.kind, room.id, page.syncCursor)) + } + } + } + + suspend fun loadOlder(room: RoomIdentity) = withRoomLock(room) { + val before = database.messages().oldestId(room.kind, room.id) + ?: return@withRoomLock loadLatestUnlocked(room, reset = false) + val page = api.messages(room.kind, room.id, before = before).bodyOrThrow(json) + database.messages().upsertAll(page.messages.map { it.toEntity(room.kind, room.id) }) + } + + suspend fun sync(room: RoomIdentity) = withRoomLock(room) { + var cursor = database.roomSync().cursor(room.kind, room.id) ?: 0L + try { + do { + val page = api.sync(room.kind, room.id, cursor).bodyOrThrow(json) + database.withTransaction { + page.events.forEach { event -> + when (event.type) { + "message" -> event.message?.let { + database.messages().upsert(it.toEntity(room.kind, room.id)) + it.clientMessageId?.let { clientMessageId -> + database.outbox().delete(clientMessageId) + } + } + "message_deleted" -> event.messageId?.let { database.messages().delete(it) } + } + } + cursor = page.nextCursor + database.roomSync().upsert(RoomSyncEntity(room.kind, room.id, cursor)) + } + } while (page.hasMore) + } catch (error: EdgeChatApiException) { + if (error.code != "sync_cursor_expired") throw error + loadLatestUnlocked(room, reset = true) + } + } + + suspend fun handleRealtime(envelope: RealtimeEnvelope, currentRoom: RoomIdentity?) { + when (envelope.type) { + "message" -> { + val room = envelope.room?.let { RoomIdentity(it.kind, it.id) } ?: currentRoom ?: return + envelope.message?.let { message -> + database.messages().upsert(message.toEntity(room.kind, room.id)) + message.clientMessageId?.let { clientMessageId -> + database.outbox().delete(clientMessageId) + } + } + } + "message_deleted" -> envelope.messageId?.let { database.messages().delete(it) } + "room_message" -> { + val room = envelope.room?.let { RoomIdentity(it.kind, it.id) } ?: return + database.conversations().updateActivity( + room.kind, + room.id, + envelope.unreadCount ?: 0, + envelope.createdAt, + ) + sync(room) + } + } + } + + suspend fun markRead(room: RoomIdentity) { + val latest = database.messages().latestId(room.kind, room.id) + api.markRead(room.kind, room.id, ReadRequest(latest)).bodyOrThrow(json) + database.conversations().clearUnread(room.kind, room.id) + } + + suspend fun deleteMessage(room: RoomIdentity, messageId: Long) { + api.deleteMessage(room.kind, room.id, messageId).bodyOrThrow(json) + database.messages().delete(messageId) + } + + suspend fun join(channelId: Long) { + api.joinChannel(channelId).bodyOrThrow(json) + bootstrap() + } + + suspend fun openDm(userId: Long): RoomIdentity { + val dm = api.openDm(OpenDmRequest(userId)).bodyOrThrow(json).dm + bootstrap() + return RoomIdentity("dm", dm.id) + } + + suspend fun createGroup( + name: String, + description: String, + kind: String, + memberIds: List, + ): RoomIdentity { + val channel = api.createGroup( + CreateGroupRequest(name.trim(), description.trim(), kind, memberIds), + ).bodyOrThrow(json).channel + bootstrap() + return RoomIdentity(channel.kind, channel.id) + } + + suspend fun members(channelId: Long) = api.members(channelId).bodyOrThrow(json) + + suspend fun invite(channelId: Long, userIds: List) = + api.inviteMembers(channelId, InviteMembersRequest(userIds)).bodyOrThrow(json).members + + suspend fun removeMember(channelId: Long, userId: Long) = + api.removeMember(channelId, userId).bodyOrThrow(json).members + + suspend fun updateGroup(channelId: Long, name: String) { + api.updateChannel(channelId, UpdateChannelRequest(name = name.trim())).bodyOrThrow(json) + bootstrap() + } + + suspend fun deleteGroup(channelId: Long) { + api.deleteChannel(channelId).bodyOrThrow(json) + bootstrap() + } + + suspend fun clearCache() { + database.clearAllTables() + attachments.clearPrivateFiles() + bootstrap() + } + + private suspend fun withRoomLock(room: RoomIdentity, block: suspend () -> T): T = + roomLocks.getOrPut(room) { Mutex() }.withLock { block() } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt new file mode 100644 index 00000000..61c56ae4 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt @@ -0,0 +1,166 @@ +package com.aozorae.edgechat.core.repository + +import android.content.Context +import androidx.work.BackoffPolicy +import androidx.work.Constraints +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.WorkManager +import com.aozorae.edgechat.core.database.EdgeChatDatabase +import com.aozorae.edgechat.core.database.OutboxEntity +import com.aozorae.edgechat.core.database.toEntity +import com.aozorae.edgechat.core.network.EdgeChatApi +import com.aozorae.edgechat.core.network.bodyOrThrow +import com.aozorae.edgechat.core.network.dto.AttachmentDto +import com.aozorae.edgechat.core.network.dto.SendMessageRequest +import com.aozorae.edgechat.core.session.TokenVault +import com.aozorae.edgechat.worker.OutboxWorker +import dagger.hilt.android.qualifiers.ApplicationContext +import java.io.File +import java.util.UUID +import java.util.concurrent.TimeUnit +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.Json +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.MultipartBody +import okhttp3.RequestBody.Companion.asRequestBody +import okhttp3.RequestBody.Companion.toRequestBody + +@Singleton +class OutboxRepository @Inject constructor( + @ApplicationContext private val context: Context, + private val api: EdgeChatApi, + private val json: Json, + private val database: EdgeChatDatabase, + private val tokenVault: TokenVault, +) { + private val processingLock = Mutex() + private val workManager = WorkManager.getInstance(context) + + fun observe(room: RoomIdentity): Flow> = + database.outbox().observeRoom(room.kind, room.id) + + suspend fun enqueue(room: RoomIdentity, content: String, attachment: PendingAttachment? = null) { + val messageId = UUID.randomUUID().toString() + database.outbox().upsert( + OutboxEntity( + clientMessageId = messageId, + roomKind = room.kind, + roomId = room.id, + content = content.trim(), + localAttachmentPath = attachment?.path, + attachmentName = attachment?.name, + attachmentType = attachment?.type, + attachmentSize = attachment?.size, + clientUploadId = attachment?.let { UUID.randomUUID().toString() }, + uploadedKey = null, + uploadedUrl = null, + state = "PENDING", + failure = null, + attempts = 0, + createdAt = System.currentTimeMillis(), + ), + ) + schedule() + } + + suspend fun retry(clientMessageId: String) { + database.outbox().updateState(clientMessageId, "RETRY") + schedule() + } + + suspend fun cancel(clientMessageId: String) { + database.outbox().get(clientMessageId)?.localAttachmentPath?.let { File(it).delete() } + database.outbox().delete(clientMessageId) + } + + suspend fun processNext(): Boolean = processingLock.withLock { + if (tokenVault.read() == null) return false + val item = database.outbox().next() ?: return false + try { + val attachment = uploadIfNeeded(item) + database.outbox().updateState(item.clientMessageId, "SENDING") + val sent = api.sendMessage( + item.roomKind, + item.roomId, + SendMessageRequest(item.clientMessageId, item.content, attachment), + ).bodyOrThrow(json) + database.messages().upsert(sent.message.toEntity(item.roomKind, item.roomId)) + database.outbox().delete(item.clientMessageId) + item.localAttachmentPath?.let { File(it).delete() } + true + } catch (error: CancellationException) { + throw error + } catch (error: Exception) { + database.outbox().markFailed(item.clientMessageId, error.message ?: "发送失败") + false + } + } + + suspend fun hasPending(): Boolean = database.outbox().pendingCount() > 0 + + suspend fun recoverInterrupted() = processingLock.withLock { + database.outbox().recoverInFlight() + } + + suspend fun pauseForServerChange() { + withContext(Dispatchers.IO) { + workManager.cancelUniqueWork(WORK_NAME).result.get() + } + processingLock.withLock { + database.outbox().recoverInFlight() + } + } + + suspend fun resume() { + recoverInterrupted() + if (hasPending()) schedule() + } + + private suspend fun uploadIfNeeded(item: OutboxEntity): AttachmentDto? { + val path = item.localAttachmentPath ?: return null + if (item.uploadedKey != null && item.uploadedUrl != null) { + return AttachmentDto( + item.uploadedKey, + item.attachmentName.orEmpty(), + item.attachmentType.orEmpty(), + item.attachmentSize ?: 0, + item.uploadedUrl, + ) + } + database.outbox().updateState(item.clientMessageId, "UPLOADING") + val file = File(path) + val type = item.attachmentType ?: "application/octet-stream" + val part = MultipartBody.Part.createFormData( + "file", + item.attachmentName ?: "attachment", + file.asRequestBody(type.toMediaTypeOrNull()), + ) + val uploadId = requireNotNull(item.clientUploadId) + val uploaded = api.upload(part, uploadId.toRequestBody("text/plain".toMediaTypeOrNull())) + .bodyOrThrow(json) + .file + database.outbox().setUploaded(item.clientMessageId, uploaded.key, uploaded.url) + return uploaded + } + + private fun schedule() { + val request = OneTimeWorkRequestBuilder() + .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()) + .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 15, TimeUnit.SECONDS) + .build() + workManager.enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.KEEP, request) + } + + companion object { + const val WORK_NAME = "edgechat-outbox" + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/ServerRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/ServerRepository.kt new file mode 100644 index 00000000..79ea82fd --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/ServerRepository.kt @@ -0,0 +1,69 @@ +package com.aozorae.edgechat.core.repository + +import com.aozorae.edgechat.core.database.EdgeChatDatabase +import com.aozorae.edgechat.core.network.EdgeChatApiException +import com.aozorae.edgechat.core.network.dto.ApiErrorEnvelope +import com.aozorae.edgechat.core.network.dto.CapabilitiesResponse +import com.aozorae.edgechat.core.session.ServerProfile +import com.aozorae.edgechat.core.session.ServerStore +import com.aozorae.edgechat.core.session.TokenVault +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.Json +import okhttp3.OkHttpClient +import okhttp3.Request + +data class ServerConnection( + val capabilities: CapabilitiesResponse, + val serverChanged: Boolean, +) + +@Singleton +class ServerRepository @Inject constructor( + private val serverStore: ServerStore, + private val tokenVault: TokenVault, + private val database: EdgeChatDatabase, + private val json: Json, + private val attachments: AttachmentRepository, +) { + private val publicClient = OkHttpClient.Builder().build() + + suspend fun connect(rawUrl: String): ServerConnection = withContext(Dispatchers.IO) { + val baseUrl = ServerStore.normalize(rawUrl) + val request = Request.Builder().url("${baseUrl}api/v1/capabilities").build() + val capabilities = publicClient.newCall(request).execute().use { response -> + val body = response.body?.string().orEmpty() + if (!response.isSuccessful) { + val error = runCatching { json.decodeFromString(body).error }.getOrNull() + throw EdgeChatApiException( + error?.code ?: "server_unavailable", + error?.message ?: "无法连接该 EdgeChat 服务器", + response.code, + ) + } + json.decodeFromString(body) + } + if (capabilities.apiVersion != 1) { + throw EdgeChatApiException("api_version_unsupported", "服务器尚未支持 EdgeChat API v1", 400) + } + val previous = serverStore.baseUrl() + if (previous != null && previous != baseUrl) { + tokenVault.clear() + database.clearAllTables() + attachments.clearPrivateFiles() + } + serverStore.saveServer( + ServerProfile(baseUrl, capabilities.site.siteName, capabilities.site.siteIconUrl), + ) + ServerConnection(capabilities, previous != null && previous != baseUrl) + } + + suspend fun disconnect() { + tokenVault.clear() + database.clearAllTables() + attachments.clearPrivateFiles() + serverStore.clearServer() + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/SessionRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/SessionRepository.kt new file mode 100644 index 00000000..905deafa --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/SessionRepository.kt @@ -0,0 +1,113 @@ +package com.aozorae.edgechat.core.repository + +import com.aozorae.edgechat.BuildConfig +import com.aozorae.edgechat.core.database.EdgeChatDatabase +import com.aozorae.edgechat.core.network.EdgeChatApi +import com.aozorae.edgechat.core.network.bodyOrThrow +import com.aozorae.edgechat.core.network.dto.ChangePasswordRequest +import com.aozorae.edgechat.core.network.dto.DeviceDto +import com.aozorae.edgechat.core.network.dto.LoginRequest +import com.aozorae.edgechat.core.network.dto.SessionDto +import com.aozorae.edgechat.core.network.dto.UpdateProfileRequest +import com.aozorae.edgechat.core.session.ServerStore +import com.aozorae.edgechat.core.session.StoredTokens +import com.aozorae.edgechat.core.session.TokenVault +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.serialization.json.Json +import java.io.File +import java.util.UUID +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.MultipartBody +import okhttp3.RequestBody.Companion.asRequestBody +import okhttp3.RequestBody.Companion.toRequestBody + +@Singleton +class SessionRepository @Inject constructor( + private val api: EdgeChatApi, + private val json: Json, + private val serverStore: ServerStore, + private val tokenVault: TokenVault, + private val database: EdgeChatDatabase, + private val attachments: AttachmentRepository, +) { + private val mutableSession = MutableStateFlow(null) + val session: StateFlow = mutableSession.asStateFlow() + val hasStoredSession = tokenVault.hasSession + + suspend fun login(username: String, password: String): SessionDto { + val response = api.login( + LoginRequest( + username.trim(), + password, + DeviceDto( + installationId = serverStore.installationId(), + name = serverStore.deviceName(), + appVersion = BuildConfig.VERSION_NAME, + ), + ), + ).bodyOrThrow(json) + tokenVault.save( + StoredTokens( + response.accessToken, + response.refreshToken, + response.accessTokenExpiresAt, + response.refreshTokenExpiresAt, + ), + ) + mutableSession.value = response.session + return response.session + } + + suspend fun restore(): SessionDto? { + if (tokenVault.read() == null) return null + return runCatching { api.session().bodyOrThrow(json).session } + .onSuccess { mutableSession.value = it } + .onFailure { invalidateLocalSession() } + .getOrNull() + } + + suspend fun updateProfile(displayName: String, avatarKey: String? = null, clearAvatar: Boolean = false) { + mutableSession.value = api.updateProfile( + UpdateProfileRequest(displayName.trim(), avatarKey, clearAvatar), + ).bodyOrThrow(json).session + } + + suspend fun updateAvatar(displayName: String, attachment: PendingAttachment) { + val file = File(attachment.path) + val part = MultipartBody.Part.createFormData( + "file", + attachment.name, + file.asRequestBody(attachment.type.toMediaTypeOrNull()), + ) + val uploaded = api.upload( + part, + UUID.randomUUID().toString().toRequestBody("text/plain".toMediaTypeOrNull()), + ).bodyOrThrow(json).file + updateProfile(displayName, avatarKey = uploaded.key) + file.delete() + } + + suspend fun changePassword(current: String, next: String) { + api.changePassword(ChangePasswordRequest(current, next)).bodyOrThrow(json) + } + + suspend fun logout() { + runCatching { api.logout().bodyOrThrow(json) } + invalidateLocalSession() + } + + suspend fun invalidateLocalSession() { + tokenVault.clear() + clearSessionState() + database.clearAllTables() + attachments.clearPrivateFiles() + } + + fun clearSessionState() { + mutableSession.value = null + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/session/ServerStore.kt b/android/app/src/main/java/com/aozorae/edgechat/core/session/ServerStore.kt new file mode 100644 index 00000000..cb77fc81 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/session/ServerStore.kt @@ -0,0 +1,93 @@ +package com.aozorae.edgechat.core.session + +import android.os.Build +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import com.aozorae.edgechat.BuildConfig +import java.net.URI +import java.util.Locale +import java.util.UUID +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map + +data class ServerProfile(val baseUrl: String, val siteName: String, val siteIconUrl: String) + +@Singleton +class ServerStore @Inject constructor(private val dataStore: DataStore) { + private val baseUrlKey = stringPreferencesKey("server_base_url") + private val siteNameKey = stringPreferencesKey("server_site_name") + private val siteIconKey = stringPreferencesKey("server_site_icon") + private val installationKey = stringPreferencesKey("installation_id") + private val languageKey = stringPreferencesKey("language") + + val server: Flow = dataStore.data.map { values -> + values[baseUrlKey]?.let { + ServerProfile(it, values[siteNameKey] ?: "EdgeChat", values[siteIconKey] ?: "") + } + } + + val language: Flow = dataStore.data.map { it[languageKey] ?: defaultLanguage() } + + suspend fun saveServer(profile: ServerProfile) { + dataStore.edit { + it[baseUrlKey] = profile.baseUrl + it[siteNameKey] = profile.siteName + it[siteIconKey] = profile.siteIconUrl + } + } + + suspend fun clearServer() { + dataStore.edit { + it.remove(baseUrlKey) + it.remove(siteNameKey) + it.remove(siteIconKey) + } + } + + suspend fun baseUrl(): String? = server.first()?.baseUrl + + suspend fun installationId(): String { + val existing = dataStore.data.first()[installationKey] + if (existing != null) return existing + val created = UUID.randomUUID().toString() + dataStore.edit { it[installationKey] = created } + return created + } + + suspend fun setLanguage(language: String) { + dataStore.edit { it[languageKey] = language } + } + + fun deviceName(): String = "${Build.MANUFACTURER} ${Build.MODEL}".trim() + + companion object { + fun normalize(raw: String): String { + val candidate = raw.trim().trimEnd('/') + val withScheme = if (candidate.contains("://")) candidate else "https://$candidate" + val uri = URI(withScheme) + val host = uri.host ?: throw IllegalArgumentException("服务器地址无效") + if (uri.userInfo != null || uri.query != null || uri.fragment != null) { + throw IllegalArgumentException("服务器地址不能包含账号、查询参数或片段") + } + val scheme = uri.scheme?.lowercase(Locale.ROOT) + val debugHttp = BuildConfig.DEBUG && scheme == "http" && + (host == "localhost" || host == "10.0.2.2" || host == "127.0.0.1") + if (scheme != "https" && !debugHttp) { + throw IllegalArgumentException("正式客户端只连接 HTTPS 服务器") + } + if (!uri.path.isNullOrBlank() && uri.path != "/") { + throw IllegalArgumentException("请输入服务器根地址,不要包含路径") + } + val port = if (uri.port > 0) ":${uri.port}" else "" + return "$scheme://$host$port/" + } + + private fun defaultLanguage(): String = + if (Locale.getDefault().language.startsWith("zh")) "zh-CN" else "en-US" + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/session/TokenVault.kt b/android/app/src/main/java/com/aozorae/edgechat/core/session/TokenVault.kt new file mode 100644 index 00000000..f7c09ec2 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/session/TokenVault.kt @@ -0,0 +1,111 @@ +package com.aozorae.edgechat.core.session + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.stringPreferencesKey +import java.security.KeyStore +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map + +data class StoredTokens( + val accessToken: String, + val refreshToken: String, + val accessExpiresAt: String, + val refreshExpiresAt: String, +) + +@Singleton +class TokenVault @Inject constructor(private val dataStore: DataStore) { + private val accessKey = stringPreferencesKey("access_token_encrypted") + private val refreshKey = stringPreferencesKey("refresh_token_encrypted") + private val accessExpiryKey = stringPreferencesKey("access_token_expires_at") + private val refreshExpiryKey = stringPreferencesKey("refresh_token_expires_at") + + val hasSession: Flow = dataStore.data.map { + it[accessKey] != null && it[refreshKey] != null + } + + suspend fun read(): StoredTokens? { + val values = dataStore.data.first() + val access = values[accessKey]?.let(::decrypt) ?: return null + val refresh = values[refreshKey]?.let(::decrypt) ?: return null + return StoredTokens( + access, + refresh, + values[accessExpiryKey].orEmpty(), + values[refreshExpiryKey].orEmpty(), + ) + } + + suspend fun accessToken(): String? = read()?.accessToken + + suspend fun save(tokens: StoredTokens) { + val access = encrypt(tokens.accessToken) + val refresh = encrypt(tokens.refreshToken) + dataStore.edit { + it[accessKey] = access + it[refreshKey] = refresh + it[accessExpiryKey] = tokens.accessExpiresAt + it[refreshExpiryKey] = tokens.refreshExpiresAt + } + } + + suspend fun clear() { + dataStore.edit { + it.remove(accessKey) + it.remove(refreshKey) + it.remove(accessExpiryKey) + it.remove(refreshExpiryKey) + } + } + + private fun key(): SecretKey { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it } + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + generator.init( + KeyGenParameterSpec.Builder( + KEY_ALIAS, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .build(), + ) + return generator.generateKey() + } + + private fun encrypt(value: String): String { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, key()) + val iv = Base64.encodeToString(cipher.iv, Base64.NO_WRAP) + val encrypted = Base64.encodeToString(cipher.doFinal(value.toByteArray()), Base64.NO_WRAP) + return "$iv.$encrypted" + } + + private fun decrypt(value: String): String? = runCatching { + val (iv, encrypted) = value.split('.', limit = 2) + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init( + Cipher.DECRYPT_MODE, + key(), + GCMParameterSpec(128, Base64.decode(iv, Base64.NO_WRAP)), + ) + String(cipher.doFinal(Base64.decode(encrypted, Base64.NO_WRAP))) + }.getOrNull() + + private companion object { + const val KEY_ALIAS = "edgechat-mobile-session-v1" + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt b/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt new file mode 100644 index 00000000..a0e7ed49 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt @@ -0,0 +1,68 @@ +package com.aozorae.edgechat.di + +import android.content.Context +import androidx.datastore.core.DataStore +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.preferencesDataStoreFile +import androidx.room.Room +import com.aozorae.edgechat.core.database.EdgeChatDatabase +import com.aozorae.edgechat.core.network.AuthInterceptor +import com.aozorae.edgechat.core.network.EdgeChatApi +import com.aozorae.edgechat.core.network.ServerUrlInterceptor +import com.aozorae.edgechat.core.network.SessionAuthenticator +import com.aozorae.edgechat.core.network.ServerUrlInterceptor.Companion.PLACEHOLDER_HOST +import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory +import dagger.Module +import dagger.Provides +import dagger.hilt.InstallIn +import dagger.hilt.android.qualifiers.ApplicationContext +import dagger.hilt.components.SingletonComponent +import javax.inject.Singleton +import kotlinx.serialization.json.Json +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import retrofit2.Retrofit + +@Module +@InstallIn(SingletonComponent::class) +object AppModule { + @Provides + @Singleton + fun json(): Json = Json { + ignoreUnknownKeys = true + explicitNulls = false + encodeDefaults = true + } + + @Provides + @Singleton + fun dataStore(@ApplicationContext context: Context): DataStore = + PreferenceDataStoreFactory.create { context.preferencesDataStoreFile("edgechat.preferences_pb") } + + @Provides + @Singleton + fun database(@ApplicationContext context: Context): EdgeChatDatabase = + Room.databaseBuilder(context, EdgeChatDatabase::class.java, "edgechat.db").build() + + @Provides + @Singleton + fun okHttp( + serverUrlInterceptor: ServerUrlInterceptor, + authInterceptor: AuthInterceptor, + authenticator: SessionAuthenticator, + ): OkHttpClient = OkHttpClient.Builder() + .addInterceptor(serverUrlInterceptor) + .addInterceptor(authInterceptor) + .authenticator(authenticator) + .build() + + @Provides + @Singleton + fun api(client: OkHttpClient, json: Json): EdgeChatApi = Retrofit.Builder() + .baseUrl("https://$PLACEHOLDER_HOST/") + .client(client) + .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) + .build() + .create(EdgeChatApi::class.java) +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/app/AppViewModel.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/app/AppViewModel.kt new file mode 100644 index 00000000..93358d05 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/app/AppViewModel.kt @@ -0,0 +1,167 @@ +package com.aozorae.edgechat.feature.app + +import android.content.Context +import android.net.Uri +import androidx.core.content.FileProvider +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.aozorae.edgechat.core.diagnostics.DiagnosticLog +import com.aozorae.edgechat.core.network.dto.SessionDto +import com.aozorae.edgechat.core.repository.AttachmentRepository +import com.aozorae.edgechat.core.repository.ChatRepository +import com.aozorae.edgechat.core.repository.OutboxRepository +import com.aozorae.edgechat.core.repository.ServerRepository +import com.aozorae.edgechat.core.repository.SessionRepository +import com.aozorae.edgechat.core.realtime.RealtimeCoordinator +import com.aozorae.edgechat.core.session.ServerProfile +import com.aozorae.edgechat.core.session.ServerStore +import dagger.hilt.android.lifecycle.HiltViewModel +import dagger.hilt.android.qualifiers.ApplicationContext +import javax.inject.Inject +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import kotlinx.coroutines.flow.collectLatest + +data class AppUiState( + val server: ServerProfile? = null, + val session: SessionDto? = null, + val language: String = "zh-CN", + val loading: Boolean = true, + val error: String? = null, +) + +@HiltViewModel +class AppViewModel @Inject constructor( + @ApplicationContext private val context: Context, + private val serverStore: ServerStore, + private val serverRepository: ServerRepository, + private val sessionRepository: SessionRepository, + private val chatRepository: ChatRepository, + private val outboxRepository: OutboxRepository, + private val attachmentRepository: AttachmentRepository, + private val diagnostics: DiagnosticLog, + private val realtime: RealtimeCoordinator, +) : ViewModel() { + private val loading = MutableStateFlow(true) + private val error = MutableStateFlow(null) + + val state: StateFlow = combine( + serverStore.server, + sessionRepository.session, + serverStore.language, + loading, + error, + ) { server, session, language, busy, failure -> + AppUiState(server, session, language, busy, failure) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AppUiState()) + + init { + viewModelScope.launch { + sessionRepository.hasStoredSession.collectLatest { stored -> + if (!stored && sessionRepository.session.value != null) { + realtime.stop() + sessionRepository.invalidateLocalSession() + } + } + } + viewModelScope.launch { + val restored = sessionRepository.restore() + if (restored != null) { + runCatching { chatRepository.bootstrap() }.onFailure { error.value = it.message } + realtime.start() + } + loading.value = false + } + } + + fun connect(server: String) = launchAction { + val hadSession = sessionRepository.session.value != null + realtime.stop() + outboxRepository.pauseForServerChange() + val connection = try { + serverRepository.connect(server) + } catch (error: Exception) { + if (hadSession) { + outboxRepository.resume() + realtime.start() + } + throw error + } + if (connection.serverChanged) { + sessionRepository.clearSessionState() + } else if (sessionRepository.session.value != null) { + outboxRepository.resume() + realtime.start() + } + } + + fun login(username: String, password: String) = launchAction { + sessionRepository.login(username, password) + chatRepository.bootstrap() + realtime.start() + } + + fun logout() = launchAction { + realtime.stop() + outboxRepository.pauseForServerChange() + sessionRepository.logout() + } + + fun disconnect() = launchAction { + realtime.stop() + outboxRepository.pauseForServerChange() + serverRepository.disconnect() + sessionRepository.clearSessionState() + } + + fun updateProfile(displayName: String) = launchAction { + sessionRepository.updateProfile(displayName) + } + + fun updateAvatar(displayName: String, uri: Uri) = launchAction { + val attachment = attachmentRepository.import(uri) + require(attachment.type.startsWith("image/")) { "头像必须是图片" } + sessionRepository.updateAvatar(displayName, attachment) + } + + fun changePassword(current: String, next: String) = launchAction { + sessionRepository.changePassword(current, next) + } + + fun setLanguage(language: String) { + viewModelScope.launch { serverStore.setLanguage(language) } + } + + fun clearCache() = launchAction { + realtime.stop() + outboxRepository.pauseForServerChange() + chatRepository.clearCache() + outboxRepository.resume() + realtime.start() + } + + fun diagnosticUri(): Uri { + val file = diagnostics.export() + return FileProvider.getUriForFile(context, "${context.packageName}.files", file) + } + + fun clearError() { + error.value = null + } + + private fun launchAction(block: suspend () -> Unit) { + viewModelScope.launch { + loading.value = true + error.value = null + runCatching { block() }.onFailure { + diagnostics.record("ui_action_failed reason=${it.javaClass.simpleName}") + error.value = it.message ?: "操作失败" + } + loading.value = false + } + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/auth/LoginScreen.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/auth/LoginScreen.kt new file mode 100644 index 00000000..c7f8c7b9 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/auth/LoginScreen.kt @@ -0,0 +1,86 @@ +package com.aozorae.edgechat.feature.auth + +import androidx.compose.foundation.layout.Arrangement +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.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.AccountCircle +import androidx.compose.material.icons.outlined.Lock +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +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.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import com.aozorae.edgechat.core.session.ServerProfile + +@Composable +fun LoginScreen( + server: ServerProfile, + loading: Boolean, + language: String, + onLogin: (String, String) -> Unit, + onChangeServer: () -> Unit, +) { + var username by remember { mutableStateOf("") } + var password by remember { mutableStateOf("") } + Column( + modifier = Modifier.fillMaxSize().padding(24.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Column(modifier = Modifier.fillMaxWidth().widthIn(max = 460.dp)) { + Text(server.siteName, style = MaterialTheme.typography.displaySmall) + Text(server.baseUrl, color = MaterialTheme.colorScheme.onSurfaceVariant) + Spacer(Modifier.height(28.dp)) + OutlinedTextField( + value = username, + onValueChange = { username = it }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + label = { Text(if (language == "zh-CN") "用户名" else "Username") }, + leadingIcon = { Icon(Icons.Outlined.AccountCircle, contentDescription = null) }, + ) + Spacer(Modifier.height(12.dp)) + OutlinedTextField( + value = password, + onValueChange = { password = it }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + visualTransformation = PasswordVisualTransformation(), + label = { Text(if (language == "zh-CN") "密码" else "Password") }, + leadingIcon = { Icon(Icons.Outlined.Lock, contentDescription = null) }, + ) + Spacer(Modifier.height(18.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedButton(onClick = onChangeServer, modifier = Modifier.weight(1f)) { + Text(if (language == "zh-CN") "更换服务器" else "Change server") + } + Button( + onClick = { onLogin(username, password) }, + enabled = username.isNotBlank() && password.isNotBlank() && !loading, + modifier = Modifier.weight(1f), + ) { + if (loading) CircularProgressIndicator(Modifier.height(20.dp), strokeWidth = 2.dp) + else Text(if (language == "zh-CN") "登录" else "Sign in") + } + } + } + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/auth/ServerSetupScreen.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/auth/ServerSetupScreen.kt new file mode 100644 index 00000000..9b36ea4e --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/auth/ServerSetupScreen.kt @@ -0,0 +1,72 @@ +package com.aozorae.edgechat.feature.auth + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +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.widthIn +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Link +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + +@Composable +fun ServerSetupScreen( + loading: Boolean, + preset: String?, + language: String, + onConnect: (String) -> Unit, +) { + var server by remember { mutableStateOf("") } + LaunchedEffect(preset) { if (!preset.isNullOrBlank()) server = preset } + Column( + modifier = Modifier.fillMaxSize().padding(24.dp), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Column(modifier = Modifier.fillMaxWidth().widthIn(max = 460.dp)) { + Text("EdgeChat", style = MaterialTheme.typography.displaySmall, fontWeight = FontWeight.SemiBold) + Text( + if (language == "zh-CN") "连接你的 EdgeChat 服务器" else "Connect to your EdgeChat server", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(28.dp)) + OutlinedTextField( + value = server, + onValueChange = { server = it }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + label = { Text(if (language == "zh-CN") "服务器地址" else "Server address") }, + placeholder = { Text("https://chat.example.com") }, + leadingIcon = { Icon(Icons.Outlined.Link, contentDescription = null) }, + ) + Spacer(Modifier.height(16.dp)) + Button( + onClick = { onConnect(server) }, + enabled = server.isNotBlank() && !loading, + modifier = Modifier.fillMaxWidth(), + ) { + if (loading) CircularProgressIndicator(Modifier.height(20.dp), strokeWidth = 2.dp) + else Text(if (language == "zh-CN") "验证并继续" else "Verify and continue") + } + } + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt new file mode 100644 index 00000000..bda20c77 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt @@ -0,0 +1,260 @@ +package com.aozorae.edgechat.feature.chat + +import android.content.Intent +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +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.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +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.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.ArrowBack +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.Delete +import androidx.compose.material.icons.outlined.Download +import androidx.compose.material.icons.outlined.Group +import androidx.compose.material.icons.outlined.Refresh +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.FilledIconButton +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.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.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 com.aozorae.edgechat.core.database.ConversationEntity +import com.aozorae.edgechat.core.database.MessageEntity +import com.aozorae.edgechat.core.database.OutboxEntity +import com.aozorae.edgechat.core.repository.PendingAttachment +import com.aozorae.edgechat.core.repository.RoomIdentity +import kotlinx.coroutines.flow.SharedFlow + +@Composable +fun ChatPane( + room: RoomIdentity?, + conversation: ConversationEntity?, + messages: List, + outbox: List, + attachment: PendingAttachment?, + currentUserId: Long, + busy: Boolean, + language: String, + openAttachmentEvents: SharedFlow>, + onBack: () -> Unit, + onLoadOlder: () -> Unit, + onSend: (String) -> Unit, + onChooseAttachment: (android.net.Uri) -> Unit, + onClearAttachment: () -> Unit, + onRetry: (String) -> Unit, + onCancel: (String) -> Unit, + onDeleteMessage: (Long) -> Unit, + onOpenAttachment: (String, String, String) -> Unit, + onManageGroup: () -> Unit, +) { + val context = LocalContext.current + LaunchedEffect(openAttachmentEvents) { + openAttachmentEvents.collect { (uri, type) -> + val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, type) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + context.startActivity(Intent.createChooser(intent, null)) + } + } + if (room == null || conversation == null) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text( + if (language == "zh-CN") "选择一个会话开始聊天" else "Choose a conversation to start chatting", + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + return + } + BackHandler(onBack = onBack) + var content by remember(room) { mutableStateOf("") } + val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> + uri?.let(onChooseAttachment) + } + Column(Modifier.fillMaxHeight()) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = null) } + Column(Modifier.weight(1f)) { + Text(conversation.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text( + if (conversation.kind == "dm") conversation.subtitle else "${conversation.memberCount} ${if (language == "zh-CN") "位成员" else "members"}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (conversation.canManage) { + IconButton(onClick = onManageGroup) { Icon(Icons.Outlined.Group, contentDescription = null) } + } + if (busy) CircularProgressIndicator(Modifier.width(22.dp), strokeWidth = 2.dp) + } + HorizontalDivider() + LazyColumn( + modifier = Modifier.weight(1f).fillMaxWidth().padding(horizontal = 12.dp), + reverseLayout = true, + ) { + items(outbox.reversed(), key = { "pending:${it.clientMessageId}" }) { item -> + PendingMessageRow(item, language, onRetry, onCancel) + } + items(messages.reversed(), key = { it.id }) { message -> + MessageRow( + message, + own = message.senderKind == "local" && message.senderId == currentUserId.toString(), + onDelete = onDeleteMessage, + onOpenAttachment = onOpenAttachment, + ) + } + item { + OutlinedButton(onClick = onLoadOlder, modifier = Modifier.padding(vertical = 12.dp)) { + Icon(Icons.Outlined.Refresh, contentDescription = null) + Spacer(Modifier.width(8.dp)) + Text(if (language == "zh-CN") "加载更早消息" else "Load older messages") + } + } + } + attachment?.let { + Row( + modifier = Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceVariant).padding(10.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(Icons.Outlined.AttachFile, contentDescription = null) + Spacer(Modifier.width(8.dp)) + Text(it.name, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis) + IconButton(onClick = onClearAttachment) { Icon(Icons.Outlined.Close, contentDescription = null) } + } + } + Row( + modifier = Modifier.fillMaxWidth().padding(10.dp), + verticalAlignment = Alignment.Bottom, + ) { + IconButton(onClick = { picker.launch("*/*") }) { + Icon(Icons.Outlined.AttachFile, contentDescription = if (language == "zh-CN") "附件" else "Attachment") + } + OutlinedTextField( + value = content, + onValueChange = { content = it }, + modifier = Modifier.weight(1f).heightIn(min = 52.dp, max = 140.dp), + placeholder = { Text(if (language == "zh-CN") "输入消息" else "Message") }, + maxLines = 5, + ) + Spacer(Modifier.width(8.dp)) + FilledIconButton( + enabled = content.isNotBlank() || attachment != null, + onClick = { onSend(content); content = "" }, + ) { Icon(Icons.AutoMirrored.Outlined.Send, contentDescription = null) } + } + } +} + +@Composable +private fun MessageRow( + message: MessageEntity, + own: Boolean, + onDelete: (Long) -> Unit, + onOpenAttachment: (String, String, String) -> Unit, +) { + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + horizontalArrangement = if (own) Arrangement.End else Arrangement.Start, + ) { + Surface( + color = if (own) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant, + shape = MaterialTheme.shapes.medium, + modifier = Modifier.fillMaxWidth(0.82f), + ) { + Column(Modifier.padding(12.dp)) { + if (!own) { + Text(message.senderDisplayName, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary) + } + if (message.content.isNotBlank()) Text(message.content) + if (message.attachmentUrl != null) { + Button( + onClick = { + onOpenAttachment( + message.attachmentUrl, + message.attachmentName ?: "attachment", + message.attachmentType ?: "application/octet-stream", + ) + }, + ) { + Icon(Icons.Outlined.Download, contentDescription = null) + Spacer(Modifier.width(8.dp)) + Text(message.attachmentName ?: "attachment", maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + Row(verticalAlignment = Alignment.CenterVertically) { + Text(message.createdAt, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) + if (own) IconButton(onClick = { onDelete(message.id) }) { + Icon(Icons.Outlined.Delete, contentDescription = null) + } + } + } + } + } +} + +@Composable +private fun PendingMessageRow( + item: OutboxEntity, + language: String, + onRetry: (String) -> Unit, + onCancel: (String) -> Unit, +) { + Row(Modifier.fillMaxWidth().padding(vertical = 4.dp), horizontalArrangement = Arrangement.End) { + Surface(color = MaterialTheme.colorScheme.tertiaryContainer, shape = MaterialTheme.shapes.medium) { + Column(Modifier.padding(12.dp)) { + if (item.content.isNotBlank()) Text(item.content) + item.attachmentName?.let { Text(it, style = MaterialTheme.typography.bodySmall) } + Text( + when (item.state) { + "UPLOADING" -> if (language == "zh-CN") "正在上传" else "Uploading" + "SENDING" -> if (language == "zh-CN") "正在发送" else "Sending" + "RETRY" -> item.failure ?: if (language == "zh-CN") "发送失败" else "Failed" + else -> if (language == "zh-CN") "等待发送" else "Queued" + }, + style = MaterialTheme.typography.labelSmall, + ) + Row { + if (item.state == "RETRY") IconButton(onClick = { onRetry(item.clientMessageId) }) { + Icon(Icons.Outlined.Refresh, contentDescription = null) + } + IconButton(onClick = { onCancel(item.clientMessageId) }) { + Icon(Icons.Outlined.Close, contentDescription = null) + } + } + } + } + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt new file mode 100644 index 00000000..878fee0d --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt @@ -0,0 +1,179 @@ +package com.aozorae.edgechat.feature.chat + +import android.net.Uri +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.aozorae.edgechat.core.database.ConversationEntity +import com.aozorae.edgechat.core.database.MessageEntity +import com.aozorae.edgechat.core.database.OutboxEntity +import com.aozorae.edgechat.core.database.UserEntity +import com.aozorae.edgechat.core.network.dto.MemberDto +import com.aozorae.edgechat.core.realtime.RealtimeCoordinator +import com.aozorae.edgechat.core.repository.AttachmentRepository +import com.aozorae.edgechat.core.repository.ChatRepository +import com.aozorae.edgechat.core.repository.OutboxRepository +import com.aozorae.edgechat.core.repository.PendingAttachment +import com.aozorae.edgechat.core.repository.RoomIdentity +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import kotlinx.coroutines.ExperimentalCoroutinesApi + +data class ChatUiState( + val conversations: List = emptyList(), + val users: List = emptyList(), + val selectedRoom: RoomIdentity? = null, + val messages: List = emptyList(), + val outbox: List = emptyList(), + val attachment: PendingAttachment? = null, + val members: List = emptyList(), + val busy: Boolean = false, + val error: String? = null, +) + +@OptIn(ExperimentalCoroutinesApi::class) +@HiltViewModel +class ChatViewModel @Inject constructor( + private val chatRepository: ChatRepository, + private val outboxRepository: OutboxRepository, + private val attachmentRepository: AttachmentRepository, + private val realtime: RealtimeCoordinator, +) : ViewModel() { + private val mutableOpenAttachment = MutableSharedFlow>(extraBufferCapacity = 1) + val openAttachment: SharedFlow> = mutableOpenAttachment + private val selectedRoom = MutableStateFlow(null) + private val attachment = MutableStateFlow(null) + private val members = MutableStateFlow>(emptyList()) + private val busy = MutableStateFlow(false) + private val error = MutableStateFlow(null) + private val roomMessages = selectedRoom.flatMapLatest { room -> + room?.let(chatRepository::messages) ?: flowOf(emptyList()) + } + private val roomOutbox = selectedRoom.flatMapLatest { room -> + room?.let(outboxRepository::observe) ?: flowOf(emptyList()) + } + + val state: StateFlow = combine( + chatRepository.conversations, + chatRepository.users, + selectedRoom, + roomMessages, + roomOutbox, + attachment, + members, + busy, + error, + ) { values -> + @Suppress("UNCHECKED_CAST") + ChatUiState( + conversations = values[0] as List, + users = values[1] as List, + selectedRoom = values[2] as RoomIdentity?, + messages = values[3] as List, + outbox = values[4] as List, + attachment = values[5] as PendingAttachment?, + members = values[6] as List, + busy = values[7] as Boolean, + error = values[8] as String?, + ) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ChatUiState()) + + fun refresh() = action { chatRepository.bootstrap() } + + fun select(room: RoomIdentity?) { + selectedRoom.value = room + members.value = emptyList() + realtime.setRoom(room) + if (room != null) action { + chatRepository.loadLatest(room) + chatRepository.sync(room) + chatRepository.markRead(room) + } + } + + fun loadOlder() { + selectedRoom.value?.let { room -> action { chatRepository.loadOlder(room) } } + } + + fun send(content: String) { + val room = selectedRoom.value ?: return + val pending = attachment.value + if (content.isBlank() && pending == null) return + action { + outboxRepository.enqueue(room, content, pending) + attachment.value = null + } + } + + fun chooseAttachment(uri: Uri) = action { + attachment.value = attachmentRepository.import(uri) + } + + fun clearAttachment() { + attachment.value?.path?.let { java.io.File(it).delete() } + attachment.value = null + } + + fun retry(clientMessageId: String) = action { outboxRepository.retry(clientMessageId) } + + fun cancel(clientMessageId: String) = action { outboxRepository.cancel(clientMessageId) } + + fun deleteMessage(messageId: Long) { + selectedRoom.value?.let { room -> action { chatRepository.deleteMessage(room, messageId) } } + } + + fun openAttachment(url: String, name: String, type: String) = action { + mutableOpenAttachment.emit(attachmentRepository.download(url, name) to type) + } + + fun join(channelId: Long) = action { chatRepository.join(channelId) } + + fun openDm(userId: Long) = action { select(chatRepository.openDm(userId)) } + + fun createGroup(name: String, description: String, kind: String, memberIds: List) = action { + select(chatRepository.createGroup(name, description, kind, memberIds)) + } + + fun loadMembers(channelId: Long) = action { + members.value = chatRepository.members(channelId).members + } + + fun invite(channelId: Long, userIds: List) = action { + members.value = chatRepository.invite(channelId, userIds) + } + + fun removeMember(channelId: Long, userId: Long) = action { + members.value = chatRepository.removeMember(channelId, userId) + } + + fun renameGroup(channelId: Long, name: String) = action { + chatRepository.updateGroup(channelId, name) + } + + fun deleteGroup(channelId: Long) = action { + chatRepository.deleteGroup(channelId) + select(null) + } + + fun clearError() { + error.value = null + } + + private fun action(block: suspend () -> Unit) { + viewModelScope.launch { + busy.value = true + error.value = null + runCatching { block() }.onFailure { error.value = it.message ?: "操作失败" } + busy.value = false + } + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/GroupManagementDialog.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/GroupManagementDialog.kt new file mode 100644 index 00000000..c29c238f --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/GroupManagementDialog.kt @@ -0,0 +1,99 @@ +package com.aozorae.edgechat.feature.chat + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material.icons.outlined.PersonAdd +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.aozorae.edgechat.core.database.ConversationEntity +import com.aozorae.edgechat.core.database.UserEntity +import com.aozorae.edgechat.core.network.dto.MemberDto + +@Composable +fun GroupManagementDialog( + conversation: ConversationEntity, + members: List, + users: List, + language: String, + onLoad: () -> Unit, + onRename: (String) -> Unit, + onInvite: (List) -> Unit, + onRemove: (Long) -> Unit, + onDelete: () -> Unit, + onDismiss: () -> Unit, +) { + var name by remember(conversation.id) { mutableStateOf(conversation.title) } + var selectedUsers by remember { mutableStateOf(setOf()) } + LaunchedEffect(conversation.id) { onLoad() } + val memberIds = members.map { it.id }.toSet() + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(if (language == "zh-CN") "群组管理" else "Group management") }, + text = { + Column { + OutlinedTextField(name, { name = it }, label = { Text(if (language == "zh-CN") "群组名称" else "Group name") }) + Button(onClick = { onRename(name) }, enabled = name.isNotBlank()) { + Text(if (language == "zh-CN") "保存名称" else "Save name") + } + Text(if (language == "zh-CN") "成员" else "Members", modifier = Modifier.padding(top = 16.dp)) + LazyColumn(modifier = Modifier.fillMaxWidth()) { + items(members, key = { it.id }) { member -> + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(member.displayName, modifier = Modifier.weight(1f)) + Text(member.role) + if (member.role != "owner") IconButton(onClick = { onRemove(member.id) }) { + Icon(Icons.Outlined.Delete, contentDescription = null) + } + } + } + items(users.filterNot { it.id in memberIds }, key = { "invite:${it.id}" }) { user -> + Row( + modifier = Modifier.fillMaxWidth().clickable { + selectedUsers = if (user.id in selectedUsers) selectedUsers - user.id else selectedUsers + user.id + }, + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox(user.id in selectedUsers, null) + Text(user.displayName, modifier = Modifier.weight(1f)) + } + } + } + if (selectedUsers.isNotEmpty()) { + Button(onClick = { onInvite(selectedUsers.toList()); selectedUsers = emptySet() }) { + Icon(Icons.Outlined.PersonAdd, contentDescription = null) + Text(if (language == "zh-CN") "邀请所选用户" else "Invite selected") + } + } + if (!conversation.isGeneral) { + OutlinedButton(onClick = onDelete, modifier = Modifier.padding(top = 12.dp)) { + Icon(Icons.Outlined.Delete, contentDescription = null) + Text(if (language == "zh-CN") "删除群组" else "Delete group") + } + } + } + }, + confirmButton = { Button(onClick = onDismiss) { Text(if (language == "zh-CN") "完成" else "Done") } }, + ) +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/conversations/ConversationPane.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/conversations/ConversationPane.kt new file mode 100644 index 00000000..67750a3c --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/conversations/ConversationPane.kt @@ -0,0 +1,193 @@ +package com.aozorae.edgechat.feature.conversations + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +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.material.icons.Icons +import androidx.compose.material.icons.outlined.Add +import androidx.compose.material.icons.outlined.Group +import androidx.compose.material.icons.outlined.Lock +import androidx.compose.material.icons.outlined.Person +import androidx.compose.material.icons.outlined.Settings +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Badge +import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.FilledTonalButton +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.Surface +import androidx.compose.material3.Text +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.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.aozorae.edgechat.core.database.ConversationEntity +import com.aozorae.edgechat.core.database.UserEntity +import com.aozorae.edgechat.core.repository.RoomIdentity + +@Composable +fun ConversationPane( + siteName: String, + conversations: List, + users: List, + selected: RoomIdentity?, + language: String, + onSelect: (RoomIdentity) -> Unit, + onJoin: (Long) -> Unit, + onOpenDm: (Long) -> Unit, + onCreateGroup: (String, String, String, List) -> Unit, + onSettings: () -> Unit, +) { + var showNew by remember { mutableStateOf(false) } + Column(Modifier.fillMaxHeight()) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(siteName, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f)) + IconButton(onClick = { showNew = true }) { + Icon(Icons.Outlined.Add, contentDescription = if (language == "zh-CN") "新建会话" else "New conversation") + } + IconButton(onClick = onSettings) { + Icon(Icons.Outlined.Settings, contentDescription = if (language == "zh-CN") "设置" else "Settings") + } + } + HorizontalDivider() + LazyColumn(Modifier.weight(1f)) { + items(conversations, key = { "${it.kind}:${it.id}" }) { item -> + ConversationRow( + item = item, + selected = selected?.kind == item.kind && selected.id == item.id, + language = language, + onClick = { + if (item.isMember) onSelect(RoomIdentity(item.kind, item.id)) else onJoin(item.id) + }, + ) + } + } + } + if (showNew) { + NewConversationDialog( + users = users, + language = language, + onDismiss = { showNew = false }, + onOpenDm = { showNew = false; onOpenDm(it) }, + onCreateGroup = { name, description, kind, ids -> + showNew = false + onCreateGroup(name, description, kind, ids) + }, + ) + } +} + +@Composable +private fun ConversationRow( + item: ConversationEntity, + selected: Boolean, + language: String, + onClick: () -> Unit, +) { + Surface(color = if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surface) { + Row( + modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon( + if (item.kind == "dm") Icons.Outlined.Person else if (item.kind == "private") Icons.Outlined.Lock else Icons.Outlined.Group, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + ) + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f)) { + Text(item.title, maxLines = 1, overflow = TextOverflow.Ellipsis, fontWeight = FontWeight.Medium) + val subtitle = if (!item.isMember) { + if (language == "zh-CN") "点按加入公开群组" else "Tap to join public group" + } else item.subtitle + if (subtitle.isNotBlank()) { + Text(subtitle, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + if (item.unreadCount > 0) Badge { Text(item.unreadCount.toString()) } + } + } +} + +@Composable +private fun NewConversationDialog( + users: List, + language: String, + onDismiss: () -> Unit, + onOpenDm: (Long) -> Unit, + onCreateGroup: (String, String, String, List) -> Unit, +) { + var mode by remember { mutableStateOf("dm") } + var name by remember { mutableStateOf("") } + var description by remember { mutableStateOf("") } + var privateGroup by remember { mutableStateOf(true) } + var selectedUsers by remember { mutableStateOf(setOf()) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(if (language == "zh-CN") "新建会话" else "New conversation") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (mode == "dm") Button(onClick = {}) { Text(if (language == "zh-CN") "私信" else "Direct") } + else OutlinedButton(onClick = { mode = "dm" }) { Text(if (language == "zh-CN") "私信" else "Direct") } + if (mode == "group") Button(onClick = {}) { Text(if (language == "zh-CN") "群组" else "Group") } + else OutlinedButton(onClick = { mode = "group" }) { Text(if (language == "zh-CN") "群组" else "Group") } + } + if (mode == "group") { + OutlinedTextField(name, { name = it }, label = { Text(if (language == "zh-CN") "群组名称" else "Group name") }) + OutlinedTextField(description, { description = it }, label = { Text(if (language == "zh-CN") "描述" else "Description") }) + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(privateGroup, { privateGroup = it }) + Text(if (language == "zh-CN") "私有群组" else "Private group") + } + } + LazyColumn(modifier = Modifier.fillMaxWidth()) { + items(users, key = { it.id }) { user -> + Row( + modifier = Modifier.fillMaxWidth().clickable { + if (mode == "dm") onOpenDm(user.id) + else selectedUsers = if (user.id in selectedUsers) selectedUsers - user.id else selectedUsers + user.id + }.padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + if (mode == "group") Checkbox(user.id in selectedUsers, null) + Text(user.displayName, modifier = Modifier.weight(1f)) + Text("@${user.username}", style = MaterialTheme.typography.bodySmall) + } + } + } + } + }, + confirmButton = { + if (mode == "group") { + FilledTonalButton( + enabled = name.isNotBlank(), + onClick = { onCreateGroup(name, description, if (privateGroup) "private" else "public", selectedUsers.toList()) }, + ) { Text(if (language == "zh-CN") "创建" else "Create") } + } + }, + dismissButton = { OutlinedButton(onClick = onDismiss) { Text(if (language == "zh-CN") "取消" else "Cancel") } }, + ) +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/settings/SettingsSheet.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/settings/SettingsSheet.kt new file mode 100644 index 00000000..4092b26d --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/settings/SettingsSheet.kt @@ -0,0 +1,106 @@ +package com.aozorae.edgechat.feature.settings + +import android.content.Intent +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.Logout +import androidx.compose.material.icons.outlined.Cached +import androidx.compose.material.icons.outlined.Image +import androidx.compose.material.icons.outlined.Share +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +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.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import com.aozorae.edgechat.core.network.dto.SessionDto + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsSheet( + session: SessionDto, + language: String, + onDismiss: () -> Unit, + onUpdateProfile: (String) -> Unit, + onUpdateAvatar: (String, android.net.Uri) -> Unit, + onChangePassword: (String, String) -> Unit, + onLanguage: (String) -> Unit, + onClearCache: () -> Unit, + diagnosticUri: () -> android.net.Uri, + onLogout: () -> Unit, +) { + val context = LocalContext.current + var displayName by remember(session.userId, session.displayName) { mutableStateOf(session.displayName) } + var currentPassword by remember { mutableStateOf("") } + var newPassword by remember { mutableStateOf("") } + val avatarPicker = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri -> + uri?.let { onUpdateAvatar(displayName, it) } + } + ModalBottomSheet(onDismissRequest = onDismiss) { + Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text(if (language == "zh-CN") "设置" else "Settings", style = MaterialTheme.typography.headlineSmall) + OutlinedTextField(displayName, { displayName = it }, modifier = Modifier.fillMaxWidth(), label = { Text(if (language == "zh-CN") "显示名称" else "Display name") }) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = { onUpdateProfile(displayName) }) { Text(if (language == "zh-CN") "保存资料" else "Save profile") } + OutlinedButton(onClick = { avatarPicker.launch("image/*") }) { + androidx.compose.material3.Icon(Icons.Outlined.Image, contentDescription = null) + Text(if (language == "zh-CN") "更换头像" else "Change avatar") + } + } + HorizontalDivider(Modifier.padding(vertical = 6.dp)) + OutlinedTextField(currentPassword, { currentPassword = it }, modifier = Modifier.fillMaxWidth(), visualTransformation = PasswordVisualTransformation(), label = { Text(if (language == "zh-CN") "当前密码" else "Current password") }) + OutlinedTextField(newPassword, { newPassword = it }, modifier = Modifier.fillMaxWidth(), visualTransformation = PasswordVisualTransformation(), label = { Text(if (language == "zh-CN") "新密码" else "New password") }) + Button(enabled = currentPassword.isNotBlank() && newPassword.isNotBlank(), onClick = { onChangePassword(currentPassword, newPassword); currentPassword = ""; newPassword = "" }) { + Text(if (language == "zh-CN") "修改密码" else "Change password") + } + HorizontalDivider(Modifier.padding(vertical = 6.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + if (language == "zh-CN") Button(onClick = {}) { Text("中文") } + else OutlinedButton(onClick = { onLanguage("zh-CN") }) { Text("中文") } + if (language == "en-US") Button(onClick = {}) { Text("English") } + else OutlinedButton(onClick = { onLanguage("en-US") }) { Text("English") } + } + OutlinedButton(onClick = onClearCache, modifier = Modifier.fillMaxWidth()) { + androidx.compose.material3.Icon(Icons.Outlined.Cached, contentDescription = null) + Text(if (language == "zh-CN") "清理并重新同步本地缓存" else "Clear and resync local cache") + } + OutlinedButton( + onClick = { + val intent = Intent(Intent.ACTION_SEND) + .setType("text/plain") + .putExtra(Intent.EXTRA_STREAM, diagnosticUri()) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + context.startActivity(Intent.createChooser(intent, null)) + }, + modifier = Modifier.fillMaxWidth(), + ) { + androidx.compose.material3.Icon(Icons.Outlined.Share, contentDescription = null) + Text(if (language == "zh-CN") "导出诊断日志" else "Export diagnostics") + } + OutlinedButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) { + androidx.compose.material3.Icon(Icons.AutoMirrored.Outlined.Logout, contentDescription = null) + Text(if (language == "zh-CN") "注销并清理缓存" else "Sign out and clear cache") + } + Spacer(Modifier.height(24.dp)) + } + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt b/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt new file mode 100644 index 00000000..637e2ee4 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt @@ -0,0 +1,190 @@ +package com.aozorae.edgechat.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.width +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.aozorae.edgechat.feature.app.AppViewModel +import com.aozorae.edgechat.feature.auth.LoginScreen +import com.aozorae.edgechat.feature.auth.ServerSetupScreen +import com.aozorae.edgechat.feature.chat.ChatPane +import com.aozorae.edgechat.feature.chat.ChatViewModel +import com.aozorae.edgechat.feature.chat.GroupManagementDialog +import com.aozorae.edgechat.feature.conversations.ConversationPane +import com.aozorae.edgechat.feature.settings.SettingsSheet +import kotlinx.coroutines.flow.StateFlow + +@Composable +fun EdgeChatApp( + deepLinkServer: StateFlow, + appViewModel: AppViewModel = hiltViewModel(), + chatViewModel: ChatViewModel = hiltViewModel(), +) { + val appState by appViewModel.state.collectAsStateWithLifecycle() + val chatState by chatViewModel.state.collectAsStateWithLifecycle() + val preset by deepLinkServer.collectAsStateWithLifecycle() + var showSettings by remember { mutableStateOf(false) } + var showGroup by remember { mutableStateOf(false) } + + LaunchedEffect(preset) { + if (!preset.isNullOrBlank() && preset != appState.server?.baseUrl) appViewModel.connect(requireNotNull(preset)) + } + + if (appState.loading && appState.server == null) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } + } else if (appState.server == null) { + ServerSetupScreen(appState.loading, preset, appState.language, appViewModel::connect) + } else if (appState.session == null) { + LoginScreen( + server = requireNotNull(appState.server), + loading = appState.loading, + language = appState.language, + onLogin = appViewModel::login, + onChangeServer = appViewModel::disconnect, + ) + } else { + val session = requireNotNull(appState.session) + val server = requireNotNull(appState.server) + val selectedConversation = chatState.selectedRoom?.let { room -> + chatState.conversations.firstOrNull { it.kind == room.kind && it.id == room.id } + } + BoxWithConstraints(Modifier.fillMaxSize()) { + val tablet = maxWidth >= 840.dp + if (tablet) { + Row(Modifier.fillMaxSize()) { + Box(Modifier.width(340.dp)) { + ConversationPane( + server.siteName, + chatState.conversations, + chatState.users, + chatState.selectedRoom, + appState.language, + chatViewModel::select, + chatViewModel::join, + chatViewModel::openDm, + chatViewModel::createGroup, + { showSettings = true }, + ) + } + Box(Modifier.weight(1f)) { + ChatPane( + room = chatState.selectedRoom, + conversation = selectedConversation, + messages = chatState.messages, + outbox = chatState.outbox, + attachment = chatState.attachment, + currentUserId = session.userId, + busy = chatState.busy, + language = appState.language, + openAttachmentEvents = chatViewModel.openAttachment, + onBack = { chatViewModel.select(null) }, + onLoadOlder = chatViewModel::loadOlder, + onSend = chatViewModel::send, + onChooseAttachment = chatViewModel::chooseAttachment, + onClearAttachment = chatViewModel::clearAttachment, + onRetry = chatViewModel::retry, + onCancel = chatViewModel::cancel, + onDeleteMessage = chatViewModel::deleteMessage, + onOpenAttachment = chatViewModel::openAttachment, + onManageGroup = { showGroup = true }, + ) + } + } + } else if (chatState.selectedRoom == null) { + ConversationPane( + server.siteName, + chatState.conversations, + chatState.users, + null, + appState.language, + chatViewModel::select, + chatViewModel::join, + chatViewModel::openDm, + chatViewModel::createGroup, + { showSettings = true }, + ) + } else { + ChatPane( + room = chatState.selectedRoom, + conversation = selectedConversation, + messages = chatState.messages, + outbox = chatState.outbox, + attachment = chatState.attachment, + currentUserId = session.userId, + busy = chatState.busy, + language = appState.language, + openAttachmentEvents = chatViewModel.openAttachment, + onBack = { chatViewModel.select(null) }, + onLoadOlder = chatViewModel::loadOlder, + onSend = chatViewModel::send, + onChooseAttachment = chatViewModel::chooseAttachment, + onClearAttachment = chatViewModel::clearAttachment, + onRetry = chatViewModel::retry, + onCancel = chatViewModel::cancel, + onDeleteMessage = chatViewModel::deleteMessage, + onOpenAttachment = chatViewModel::openAttachment, + onManageGroup = { showGroup = true }, + ) + } + } + + if (showSettings) { + SettingsSheet( + session = session, + language = appState.language, + onDismiss = { showSettings = false }, + onUpdateProfile = appViewModel::updateProfile, + onUpdateAvatar = appViewModel::updateAvatar, + onChangePassword = appViewModel::changePassword, + onLanguage = appViewModel::setLanguage, + onClearCache = appViewModel::clearCache, + diagnosticUri = appViewModel::diagnosticUri, + onLogout = { showSettings = false; appViewModel.logout() }, + ) + } + if (showGroup && selectedConversation != null) { + GroupManagementDialog( + conversation = selectedConversation, + members = chatState.members, + users = chatState.users, + language = appState.language, + onLoad = { chatViewModel.loadMembers(selectedConversation.id) }, + onRename = { chatViewModel.renameGroup(selectedConversation.id, it) }, + onInvite = { chatViewModel.invite(selectedConversation.id, it) }, + onRemove = { chatViewModel.removeMember(selectedConversation.id, it) }, + onDelete = { showGroup = false; chatViewModel.deleteGroup(selectedConversation.id) }, + onDismiss = { showGroup = false }, + ) + } + } + + val failure = appState.error ?: chatState.error + if (failure != null) { + AlertDialog( + onDismissRequest = { appViewModel.clearError(); chatViewModel.clearError() }, + title = { Text(if (appState.language == "zh-CN") "操作失败" else "Something went wrong") }, + text = { Text(failure) }, + confirmButton = { + Button(onClick = { appViewModel.clearError(); chatViewModel.clearError() }) { + Text(if (appState.language == "zh-CN") "知道了" else "OK") + } + }, + ) + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/ui/theme/Theme.kt b/android/app/src/main/java/com/aozorae/edgechat/ui/theme/Theme.kt new file mode 100644 index 00000000..fbe63536 --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/ui/theme/Theme.kt @@ -0,0 +1,42 @@ +package com.aozorae.edgechat.ui.theme + +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext + +private val LightColors = lightColorScheme( + primary = Color(0xFF006B5F), + onPrimary = Color.White, + secondary = Color(0xFF4A635E), + tertiary = Color(0xFF3F6375), + surface = Color(0xFFF8FAF8), + surfaceVariant = Color(0xFFDCE5E1), +) + +private val DarkColors = darkColorScheme( + primary = Color(0xFF53DBC8), + secondary = Color(0xFFB1CCC5), + tertiary = Color(0xFFA7CDDF), + surface = Color(0xFF101412), +) + +@Composable +fun EdgeChatTheme(content: @Composable () -> Unit) { + val dark = isSystemInDarkTheme() + val context = LocalContext.current + val colors = if (Build.VERSION.SDK_INT >= 31) { + if (dark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } else if (dark) { + DarkColors + } else { + LightColors + } + MaterialTheme(colorScheme = colors, content = content) +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/worker/OutboxWorker.kt b/android/app/src/main/java/com/aozorae/edgechat/worker/OutboxWorker.kt new file mode 100644 index 00000000..fac21c6c --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/worker/OutboxWorker.kt @@ -0,0 +1,25 @@ +package com.aozorae.edgechat.worker + +import android.content.Context +import androidx.hilt.work.HiltWorker +import androidx.work.CoroutineWorker +import androidx.work.WorkerParameters +import com.aozorae.edgechat.core.repository.OutboxRepository +import dagger.assisted.Assisted +import dagger.assisted.AssistedInject + +@HiltWorker +class OutboxWorker @AssistedInject constructor( + @Assisted context: Context, + @Assisted parameters: WorkerParameters, + private val outbox: OutboxRepository, +) : CoroutineWorker(context, parameters) { + override suspend fun doWork(): Result { + outbox.recoverInterrupted() + repeat(10) { + if (!outbox.hasPending()) return Result.success() + if (!outbox.processNext()) return if (runAttemptCount < 5) Result.retry() else Result.failure() + } + return if (outbox.hasPending()) Result.retry() else Result.success() + } +} diff --git a/android/app/src/main/res/drawable/ic_edgechat_foreground.xml b/android/app/src/main/res/drawable/ic_edgechat_foreground.xml new file mode 100644 index 00000000..f52ce74f --- /dev/null +++ b/android/app/src/main/res/drawable/ic_edgechat_foreground.xml @@ -0,0 +1,13 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..cf5ab9a7 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000..cf5ab9a7 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000..355d2a0d --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,3 @@ + + #C6D8E6 + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..ccb0f848 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + EdgeChat + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 00000000..1072876c --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,9 @@ + + + diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml new file mode 100644 index 00000000..3c332dfd --- /dev/null +++ b/android/app/src/main/res/xml/data_extraction_rules.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/android/app/src/main/res/xml/file_paths.xml b/android/app/src/main/res/xml/file_paths.xml new file mode 100644 index 00000000..81e77c29 --- /dev/null +++ b/android/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/test/java/com/aozorae/edgechat/core/network/ApiDtosTest.kt b/android/app/src/test/java/com/aozorae/edgechat/core/network/ApiDtosTest.kt new file mode 100644 index 00000000..d0eb78f3 --- /dev/null +++ b/android/app/src/test/java/com/aozorae/edgechat/core/network/ApiDtosTest.kt @@ -0,0 +1,22 @@ +package com.aozorae.edgechat.core.network + +import com.aozorae.edgechat.core.network.dto.MessageDto +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Test + +class ApiDtosTest { + private val json = Json { ignoreUnknownKeys = true } + + @Test + fun senderIdAcceptsLocalNumberAndExternalString() { + val local = json.decodeFromString( + """{"id":1,"createdAt":"2026-08-30 12:00:00","sender":{"kind":"local","id":42,"displayName":"A"}}""", + ) + val external = json.decodeFromString( + """{"id":2,"createdAt":"2026-08-30 12:00:01","sender":{"kind":"external","id":"telegram:7","displayName":"B"}}""", + ) + assertEquals("42", local.sender.id) + assertEquals("telegram:7", external.sender.id) + } +} diff --git a/android/app/src/test/java/com/aozorae/edgechat/core/session/ServerStoreTest.kt b/android/app/src/test/java/com/aozorae/edgechat/core/session/ServerStoreTest.kt new file mode 100644 index 00000000..644baa40 --- /dev/null +++ b/android/app/src/test/java/com/aozorae/edgechat/core/session/ServerStoreTest.kt @@ -0,0 +1,32 @@ +package com.aozorae.edgechat.core.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +class ServerStoreTest { + @Test + fun normalizesHttpsOrigin() { + assertEquals("https://chat.example.com/", ServerStore.normalize("chat.example.com/")) + assertEquals("https://chat.example.com:8443/", ServerStore.normalize("https://chat.example.com:8443")) + } + + @Test + fun rejectsPathsAndInsecureProductionHosts() { + assertThrows(IllegalArgumentException::class.java) { + ServerStore.normalize("https://chat.example.com/app") + } + assertThrows(IllegalArgumentException::class.java) { + ServerStore.normalize("http://chat.example.com") + } + assertThrows(IllegalArgumentException::class.java) { + ServerStore.normalize("https://user@chat.example.com") + } + assertThrows(IllegalArgumentException::class.java) { + ServerStore.normalize("https://chat.example.com?server=other") + } + assertThrows(IllegalArgumentException::class.java) { + ServerStore.normalize("https://chat.example.com#settings") + } + } +} diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 00000000..2f0df07f --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + id("com.android.application") version "8.6.1" 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.devtools.ksp") version "2.0.21-1.0.28" apply false + id("com.google.dagger.hilt.android") version "2.52" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 00000000..0e8130d7 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx3072m -Dfile.encoding=UTF-8 +android.useAndroidX=true +kotlin.code.style=official +android.nonTransitiveRClass=true diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..e6441136f3d4ba8a0da8d277868979cfbc8ad796 GIT binary patch literal 43453 zcma&N1CXTcmMvW9vTb(Rwr$&4wr$(C?dmSu>@vG-+vuvg^_??!{yS%8zW-#zn-LkA z5&1^$^{lnmUON?}LBF8_K|(?T0Ra(xUH{($5eN!MR#ZihR#HxkUPe+_R8Cn`RRs(P z_^*#_XlXmGv7!4;*Y%p4nw?{bNp@UZHv1?Um8r6)Fei3p@ClJn0ECfg1hkeuU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>^XYT z@Q^7zp{rkIs{2mUSE^2!Gf6$6;j~&4=-0cSJJDizZp6LTe8b45;{AKM%v99}{{FfC zz709%u0mC=1KXTo(=TqmZQ;c?$M3z(!xah>aywrj40sc2y3rKFw4jCq+Y+u=CH@_V zxz|qeTwa>+<|H%8Dz5u>ZI5MmjTFwXS-Fv!TDd*`>3{krWoNVx$<133`(ftS?ZPyY z&4@ah^3^i`vL$BZa>O|Nt?ucewzsF)0zX3qmM^|waXr=T0pfIb0*$AwU=?Ipl|1Y; z*Pk6{C-p4MY;j@IJ|DW>QHZQJcp;Z~?8(Q+Kk3^0qJ}SCk^*n4W zu9ZFwLHUx-$6xvaQ)SUQcYd6fF8&x)V`1bIuX@>{mE$b|Yd(qomn3;bPwnDUc0F=; zh*6_((%bqAYQWQ~odER?h>1mkL4kpb3s7`0m@rDKGU*oyF)$j~Ffd4fXV$?`f~rHf zB%Y)@5SXZvfwm10RY5X?TEo)PK_`L6qgBp=#>fO49$D zDq8Ozj0q6213tV5Qq=;fZ0$|KroY{Dz=l@lU^J)?Ko@ti20TRplXzphBi>XGx4bou zEWrkNjz0t5j!_ke{g5I#PUlEU$Km8g8TE|XK=MkU@PT4T><2OVamoK;wJ}3X0L$vX zgd7gNa359*nc)R-0!`2X@FOTB`+oETOPc=ubp5R)VQgY+5BTZZJ2?9QwnO=dnulIUF3gFn;BODC2)65)HeVd%t86sL7Rv^Y+nbn+&l z6BAJY(ETvwI)Ts$aiE8rht4KD*qNyE{8{x6R|%akbTBzw;2+6Echkt+W+`u^XX z_z&x%n '} + 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 "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 00000000..25da30db --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,92 @@ +@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 + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 00000000..78135483 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "EdgeChatAndroid" +include(":app") diff --git a/docs/api/edgechat-v1.openapi.yaml b/docs/api/edgechat-v1.openapi.yaml new file mode 100644 index 00000000..338b861b --- /dev/null +++ b/docs/api/edgechat-v1.openapi.yaml @@ -0,0 +1,628 @@ +openapi: 3.1.0 +info: + title: EdgeChat Mobile API + version: 1.0.0 + description: Stable HTTP contract shared by native clients and EdgeChat servers. +servers: + - url: https://chat.example.com/api/v1 +security: + - bearerAuth: [] +paths: + /capabilities: + get: + security: [] + operationId: getCapabilities + responses: + "200": + description: Server capabilities + content: + application/json: + schema: + $ref: "#/components/schemas/Capabilities" + /auth/login: + post: + security: [] + operationId: loginDevice + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/LoginRequest" + responses: + "200": + description: Device session created + content: + application/json: + schema: + $ref: "#/components/schemas/MobileAuth" + "401": + $ref: "#/components/responses/ApiError" + /auth/refresh: + post: + security: [] + operationId: refreshDeviceSession + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [refreshToken, installationId] + properties: + refreshToken: { type: string } + installationId: { type: string, format: uuid } + responses: + "200": + description: Rotated device tokens + content: + application/json: + schema: + $ref: "#/components/schemas/MobileAuth" + "401": + $ref: "#/components/responses/ApiError" + /auth/logout: + post: + operationId: logoutDevice + responses: + "200": { $ref: "#/components/responses/Ok" } + "401": { $ref: "#/components/responses/ApiError" } + /auth/session: + get: + operationId: getSession + responses: + "200": + description: Current session + content: + application/json: + schema: + type: object + required: [session] + properties: + session: { $ref: "#/components/schemas/Session" } + "401": { $ref: "#/components/responses/ApiError" } + /auth/change-password: + post: + operationId: changePassword + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [currentPassword, newPassword] + properties: + currentPassword: { type: string } + newPassword: { type: string } + responses: + "200": { $ref: "#/components/responses/Ok" } + "400": { $ref: "#/components/responses/ApiError" } + /bootstrap: + get: + operationId: bootstrap + responses: + "200": + description: Current users and conversations + content: + application/json: + schema: + $ref: "#/components/schemas/Bootstrap" + /channels: + get: + operationId: listChannels + responses: + "200": + description: Visible channels + content: + application/json: + schema: + type: object + required: [channels, publicChannels, privateChannels] + properties: + channels: { type: array, items: { $ref: "#/components/schemas/Channel" } } + publicChannels: { type: array, items: { $ref: "#/components/schemas/Channel" } } + privateChannels: { type: array, items: { $ref: "#/components/schemas/Channel" } } + post: + operationId: createChannel + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name, kind] + properties: + name: { type: string } + description: { type: string } + kind: { type: string, enum: [public, private] } + memberUserIds: { type: array, items: { type: integer } } + responses: + "200": + description: Created channel + content: + application/json: + schema: + type: object + required: [channel] + properties: + channel: { $ref: "#/components/schemas/Channel" } + /channels/{channelId}/join: + post: + operationId: joinPublicChannel + parameters: + - $ref: "#/components/parameters/ChannelId" + responses: + "200": { $ref: "#/components/responses/Ok" } + /channels/{channelId}/members: + get: + operationId: listChannelMembers + parameters: + - $ref: "#/components/parameters/ChannelId" + responses: + "200": + description: Channel members + content: + application/json: + schema: + type: object + required: [room, members] + properties: + room: { $ref: "#/components/schemas/Channel" } + members: { type: array, items: { $ref: "#/components/schemas/Member" } } + /channels/{channelId}/invite: + post: + operationId: inviteChannelMembers + parameters: + - $ref: "#/components/parameters/ChannelId" + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [userIds] + properties: + userIds: { type: array, items: { type: integer } } + responses: + "200": { $ref: "#/components/responses/MembersMutation" } + /channels/{channelId}/members/{userId}: + delete: + operationId: removeChannelMember + parameters: + - $ref: "#/components/parameters/ChannelId" + - name: userId + in: path + required: true + schema: { type: integer } + responses: + "200": { $ref: "#/components/responses/MembersMutation" } + /channels/{channelId}: + patch: + operationId: updateChannel + parameters: + - $ref: "#/components/parameters/ChannelId" + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + name: { type: string } + avatarKey: { type: [string, "null"] } + responses: + "200": + description: Updated channel or no-op result + delete: + operationId: deleteChannel + parameters: + - $ref: "#/components/parameters/ChannelId" + responses: + "200": { $ref: "#/components/responses/Ok" } + /dm/open: + post: + operationId: openDirectMessage + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [userId] + properties: + userId: { type: integer } + responses: + "200": + description: Direct conversation + /me/profile: + patch: + operationId: updateProfile + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [displayName] + properties: + displayName: { type: string } + avatarKey: { type: [string, "null"] } + clearAvatar: { type: boolean } + responses: + "200": + description: Updated session + /rooms/{kind}/{roomId}/messages: + get: + operationId: listRoomMessages + parameters: + - $ref: "#/components/parameters/RoomKind" + - $ref: "#/components/parameters/RoomId" + - name: before + in: query + schema: { type: integer } + - name: limit + in: query + schema: { type: integer, minimum: 1, maximum: 100, default: 30 } + responses: + "200": + description: Canonical message page + content: + application/json: + schema: + $ref: "#/components/schemas/RoomMessages" + post: + operationId: sendRoomMessage + parameters: + - $ref: "#/components/parameters/RoomKind" + - $ref: "#/components/parameters/RoomId" + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [clientMessageId, content] + properties: + clientMessageId: { type: string, format: uuid } + content: { type: string } + attachment: { oneOf: [{ $ref: "#/components/schemas/Attachment" }, { type: "null" }] } + responses: + "200": { $ref: "#/components/responses/MessageSubmission" } + "201": { $ref: "#/components/responses/MessageSubmission" } + /rooms/{kind}/{roomId}/messages/{messageId}: + delete: + operationId: deleteRoomMessage + parameters: + - $ref: "#/components/parameters/RoomKind" + - $ref: "#/components/parameters/RoomId" + - name: messageId + in: path + required: true + schema: { type: integer } + responses: + "200": { $ref: "#/components/responses/Ok" } + /rooms/{kind}/{roomId}/sync: + get: + operationId: syncRoom + parameters: + - $ref: "#/components/parameters/RoomKind" + - $ref: "#/components/parameters/RoomId" + - name: cursor + in: query + required: true + schema: { type: integer, minimum: 0 } + - name: limit + in: query + schema: { type: integer, minimum: 1, maximum: 100, default: 100 } + responses: + "200": + description: Ordered message and deletion events + content: + application/json: + schema: + $ref: "#/components/schemas/RoomSync" + "409": + description: Cursor expired; reload the current room snapshot + content: + application/json: + schema: { $ref: "#/components/schemas/ErrorEnvelope" } + /rooms/{kind}/{roomId}/read: + post: + operationId: markRoomRead + parameters: + - $ref: "#/components/parameters/RoomKind" + - $ref: "#/components/parameters/RoomId" + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + messageId: { type: [integer, "null"] } + responses: + "200": + description: Read cursor + /uploads: + post: + operationId: uploadAttachment + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [file, clientUploadId] + properties: + file: { type: string, format: binary } + clientUploadId: { type: string, format: uuid } + responses: + "200": { $ref: "#/components/responses/Upload" } + "201": { $ref: "#/components/responses/Upload" } + /realtime/tickets: + post: + operationId: createRealtimeTicket + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [scope] + properties: + scope: { type: string, enum: [inbox, room] } + roomKind: { type: string, enum: [public, private, dm] } + roomId: { type: integer } + responses: + "200": + description: Single-use ticket valid for 60 seconds + content: + application/json: + schema: + type: object + required: [ticket, expiresAt] + properties: + ticket: { type: string } + expiresAt: { type: string, format: date-time } +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + parameters: + ChannelId: + name: channelId + in: path + required: true + schema: { type: integer } + RoomKind: + name: kind + in: path + required: true + schema: { type: string, enum: [public, private, dm] } + RoomId: + name: roomId + in: path + required: true + schema: { type: integer } + responses: + ApiError: + description: Stable client-visible error + content: + application/json: + schema: + $ref: "#/components/schemas/ErrorEnvelope" + Ok: + description: Successful command + content: + application/json: + schema: + type: object + required: [ok] + properties: + ok: { type: boolean, const: true } + MessageSubmission: + description: Canonical message; created is false for an idempotent replay + content: + application/json: + schema: + type: object + required: [created, message] + properties: + created: { type: boolean } + message: { $ref: "#/components/schemas/Message" } + Upload: + description: Canonical uploaded file; created is false for an idempotent replay + content: + application/json: + schema: + type: object + required: [created, file] + properties: + created: { type: boolean } + file: { $ref: "#/components/schemas/Attachment" } + MembersMutation: + description: Updated member list + content: + application/json: + schema: + type: object + required: [ok, members] + properties: + ok: { type: boolean } + members: { type: array, items: { $ref: "#/components/schemas/Member" } } + schemas: + ErrorEnvelope: + type: object + required: [error] + properties: + error: + type: object + required: [code, message] + properties: + code: { type: string } + message: { type: string } + Capabilities: + type: object + required: [apiVersion, site, limits, features] + properties: + apiVersion: { type: integer, const: 1 } + site: + type: object + required: [siteName, siteIconUrl] + properties: + siteName: { type: string } + siteIconUrl: { type: string } + limits: + type: object + required: [maxUploadBytes, messageRetentionDays] + properties: + maxUploadBytes: { type: integer } + messageRetentionDays: { type: integer } + features: + type: object + required: [deviceSessions, realtimeTickets, idempotentMessages, idempotentUploads, roomSync, backgroundPush] + properties: + deviceSessions: { type: boolean } + realtimeTickets: { type: boolean } + idempotentMessages: { type: boolean } + idempotentUploads: { type: boolean } + roomSync: { type: boolean } + backgroundPush: { type: boolean, const: false } + LoginRequest: + type: object + required: [username, password, device] + properties: + username: { type: string } + password: { type: string } + device: + type: object + required: [installationId, name, appVersion] + properties: + installationId: { type: string, format: uuid } + name: { type: string } + appVersion: { type: string } + MobileAuth: + type: object + required: [accessToken, accessTokenExpiresAt, refreshToken, refreshTokenExpiresAt, session] + properties: + accessToken: { type: string } + accessTokenExpiresAt: { type: string } + refreshToken: { type: string } + refreshTokenExpiresAt: { type: string } + session: { $ref: "#/components/schemas/Session" } + Session: + type: object + required: [userId, username, displayName, avatarUrl, isAdmin, sessionVersion] + properties: + userId: { type: integer } + username: { type: string } + displayName: { type: string } + avatarUrl: { type: string } + isAdmin: { type: boolean } + sessionVersion: { type: integer } + deviceSessionId: { type: string } + User: + type: object + required: [id, username, displayName, avatarUrl] + properties: + id: { type: integer } + username: { type: string } + displayName: { type: string } + avatarUrl: { type: string } + Channel: + type: object + required: [id, name, kind] + properties: + id: { type: integer } + name: { type: string } + description: { type: string } + avatarKey: { type: string } + avatarUrl: { type: string } + kind: { type: string, enum: [public, private, dm] } + isGeneral: { type: boolean } + ownerDisplayName: { type: string } + isMember: { type: boolean } + myRole: { type: string } + canManage: { type: boolean } + memberCount: { type: integer } + lastMessageAt: { type: [string, "null"] } + unreadCount: { type: integer } + Member: + type: object + required: [id, username, displayName, avatarUrl, role] + properties: + id: { type: integer } + username: { type: string } + displayName: { type: string } + avatarUrl: { type: string } + role: { type: string, enum: [owner, member] } + joinedAt: { type: string } + Attachment: + type: object + required: [key, name, type, size, url] + properties: + key: { type: string } + name: { type: string } + type: { type: string } + size: { type: integer } + url: { type: string } + Sender: + type: object + required: [kind, id, username, displayName, avatarUrl, source] + properties: + kind: { type: string, enum: [local, external] } + id: { oneOf: [{ type: integer }, { type: string }] } + username: { type: string } + displayName: { type: string } + avatarUrl: { type: string } + source: { type: string } + Message: + type: object + required: [id, content, createdAt, source, sender, attachment] + properties: + id: { type: integer } + clientMessageId: { type: string, format: uuid } + content: { type: string } + createdAt: { type: string } + source: { type: string } + sender: { $ref: "#/components/schemas/Sender" } + attachment: { oneOf: [{ $ref: "#/components/schemas/Attachment" }, { type: "null" }] } + Bootstrap: + type: object + required: [users, channels, dms] + properties: + users: { type: array, items: { $ref: "#/components/schemas/User" } } + channels: { type: array, items: { $ref: "#/components/schemas/Channel" } } + dms: { type: array, items: { type: object } } + RoomMessages: + type: object + required: [room, messages, syncCursor] + properties: + room: + type: object + required: [id, kind, name, description] + properties: + id: { type: integer } + kind: { type: string } + name: { type: string } + description: { type: string } + messages: { type: array, items: { $ref: "#/components/schemas/Message" } } + syncCursor: { type: integer } + RoomSync: + type: object + required: [events, nextCursor, hasMore] + properties: + events: + type: array + items: + type: object + required: [sequence, type] + properties: + sequence: { type: integer } + type: { type: string, enum: [message, message_deleted] } + messageId: { type: integer } + message: { $ref: "#/components/schemas/Message" } + createdAt: { type: string } + nextCursor: { type: integer } + hasMore: { type: boolean } diff --git a/docs/api/websocket-v1.md b/docs/api/websocket-v1.md new file mode 100644 index 00000000..fd62d325 --- /dev/null +++ b/docs/api/websocket-v1.md @@ -0,0 +1,35 @@ +# EdgeChat WebSocket v1 + +Android clients use WebSocket only while the app is visible. Sending, deleting and retrying messages stays on the idempotent HTTP API. + +## Connection + +1. Call `POST /api/v1/realtime/tickets` with Bearer authentication. +2. Use scope `inbox`, or scope `room` with `roomKind` and `roomId`. +3. Connect to `/api/v1/realtime/ws?ticket=...` within 60 seconds. + +The ticket is bound to one device session and one scope. It is consumed once, including a failed redemption after the server has atomically claimed it. Long-lived access and refresh tokens never appear in the WebSocket URL; only the single-use 60-second ticket is carried in the query string. + +## Frames + +Every server frame is JSON and contains `protocolVersion: 1` plus `type`. + +- `ready`: the connection is authorized; room sockets include `room`. +- `message`: includes the canonical `message`. Room clients merge by `message.id` and `message.clientMessageId`. +- `message_deleted`: includes `messageId`. +- `room_message`: inbox signal with `room`, `messageId`, `createdAt` and `unreadCount`; the client then runs room sync. +- `error`: includes a client-safe `error` message and never contains a stack trace. + +Example: + +```json +{"protocolVersion":1,"type":"room_message","room":{"id":7,"kind":"private","name":"team"},"messageId":52,"createdAt":"2026-08-30 12:00:00","unreadCount":3} +``` + +## Lifecycle and recovery + +- Keep one inbox socket and, when open, one current-room socket while the app is visible. +- Close both with code `1000` when the app enters the background. +- Do not reconnect after normal closure, policy failure, authentication failure or authorization failure (`1000`, `1008`, `4401`, `4403`). +- Other failures retry after 1 second, 2 seconds and then 5 seconds. +- After foreground restore, reconnect or process restart, call the HTTP room sync endpoint. WebSocket delivery is never the sole source of truth. diff --git a/test/android-workflows.test.js b/test/android-workflows.test.js new file mode 100644 index 00000000..98b32d10 --- /dev/null +++ b/test/android-workflows.test.js @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const read = (path) => readFileSync(new URL(path, import.meta.url), "utf8").replaceAll("\r\n", "\n"); +const ci = read("../.github/workflows/android-ci.yml"); +const release = read("../.github/workflows/android-release.yml"); +const worker = read("../.github/workflows/deploy-worker.yml"); +const demo = read("../.github/workflows/deploy-demo.yml"); + +test("Android CI validates the wrapper and builds a tested debug APK", () => { + assert.match(ci, /gradle\/actions\/wrapper-validation@v4/); + assert.match(ci, /testDebugUnitTest lintDebug assembleDebug/); + assert.match(ci, /android\/app\/build\/outputs\/apk\/debug\/app-debug\.apk/); + assert.match(ci, /docs\/api\/\*\*/); +}); + +test("Android release requires secret signing and publishes APK, AAB and SHA-256", () => { + for (const secret of [ + "ANDROID_KEYSTORE_BASE64", + "ANDROID_KEYSTORE_PASSWORD", + "ANDROID_KEY_ALIAS", + "ANDROID_KEY_PASSWORD", + ]) { + assert.match(release, new RegExp(`secrets\\.${secret}`)); + } + assert.match(release, /assembleRelease bundleRelease/); + assert.match(release, /sha256sum \*\.apk \*\.aab > SHA256SUMS\.txt/); + assert.match(release, /gh release create/); +}); + +test("Worker ignores Android-only paths and maintained Actions use Node 24 compatible majors", () => { + assert.match(worker, /paths:/); + assert.doesNotMatch(worker, /android\/\*\*/); + for (const workflow of [worker, demo, ci, release]) { + assert.match(workflow, /actions\/checkout@v5/); + } + assert.match(worker, /actions\/setup-node@v5/); + assert.match(demo, /actions\/setup-node@v5/); +}); diff --git a/test/api-v1-contract.test.js b/test/api-v1-contract.test.js new file mode 100644 index 00000000..8c7b687f --- /dev/null +++ b/test/api-v1-contract.test.js @@ -0,0 +1,59 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const openapi = readFileSync( + new URL("../docs/api/edgechat-v1.openapi.yaml", import.meta.url), + "utf8", +).replaceAll("\r\n", "\n"); +const websocket = readFileSync( + new URL("../docs/api/websocket-v1.md", import.meta.url), + "utf8", +).replaceAll("\r\n", "\n"); + +test("OpenAPI v1 locks every native HTTP entry point", () => { + assert.match(openapi, /^openapi: 3\.1\.0/m); + for (const path of [ + "/capabilities:", + "/auth/login:", + "/auth/refresh:", + "/auth/logout:", + "/auth/session:", + "/bootstrap:", + "/channels:", + "/dm/open:", + "/rooms/{kind}/{roomId}/messages:", + "/rooms/{kind}/{roomId}/sync:", + "/uploads:", + "/realtime/tickets:", + ]) { + assert.match(openapi, new RegExp(`^ ${path.replace(/[{}]/g, "\\$&")}`, "m"), path); + } +}); + +test("OpenAPI v1 keeps stable auth, idempotency, sync and error fields", () => { + for (const field of [ + "accessToken", + "accessTokenExpiresAt", + "refreshToken", + "refreshTokenExpiresAt", + "clientMessageId", + "clientUploadId", + "syncCursor", + "nextCursor", + "hasMore", + "required: [code, message]", + ]) { + const escaped = field.replaceAll("[", "\\[").replaceAll("]", "\\]"); + assert.match(openapi, new RegExp(escaped)); + } +}); + +test("WebSocket v1 documents all supported frames and recovery rules", () => { + assert.match(websocket, /protocolVersion: 1/); + for (const type of ["ready", "message", "message_deleted", "room_message", "error"]) { + assert.match(websocket, new RegExp(`\\b${type}\\b`)); + } + assert.match(websocket, /1 second, 2 seconds and then 5 seconds/); + assert.match(websocket, /HTTP room sync endpoint/); +}); diff --git a/test/message-deletion.test.js b/test/message-deletion.test.js index c10e7a66..638f40a4 100644 --- a/test/message-deletion.test.js +++ b/test/message-deletion.test.js @@ -66,7 +66,11 @@ test("消息删除统一完成权限校验、持久化与实时删除 packet", a }, { type: "persist", db, args: { channelId: 4, messageId: 9 } }, ]); - assert.deepEqual(JSON.parse(result.packet), { type: "message_deleted", messageId: 9 }); + assert.deepEqual(JSON.parse(result.packet), { + protocolVersion: 1, + type: "message_deleted", + messageId: 9, + }); }); test("消息删除向客户端收敛无权限、无效参数与重复删除错误", async () => { diff --git a/test/message-delivery.test.js b/test/message-delivery.test.js index 09909bb3..78957a5d 100644 --- a/test/message-delivery.test.js +++ b/test/message-delivery.test.js @@ -28,7 +28,7 @@ test("消息提交 module 统一持久化参数与广播 packet", async () => { args: { channelId: 3, senderId: 7, content: "hello", attachment: { key: "a" } }, }]); assert.equal(result.message, message); - assert.deepEqual(JSON.parse(result.packet), { type: "message", message }); + assert.deepEqual(JSON.parse(result.packet), { protocolVersion: 1, type: "message", message }); }); test("消息提交只转换可预期的空消息错误", async () => { @@ -83,8 +83,9 @@ test("未读投影排除发送者,并行投影所有收件人", async () => { assert.deepEqual(notifications, [ { userId: 2, - payload: { - type: "room_message", + payload: { + protocolVersion: 1, + type: "room_message", room: { id: 4, kind: "private", name: "Team" }, messageId: 8, createdAt: "now", @@ -93,8 +94,9 @@ test("未读投影排除发送者,并行投影所有收件人", async () => { }, { userId: 3, - payload: { - type: "room_message", + payload: { + protocolVersion: 1, + type: "room_message", room: { id: 4, kind: "private", name: "Team" }, messageId: 8, createdAt: "now", diff --git a/test/mobile-api-v1.test.js b/test/mobile-api-v1.test.js new file mode 100644 index 00000000..5803092b --- /dev/null +++ b/test/mobile-api-v1.test.js @@ -0,0 +1,294 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import test from 'node:test'; +import initSqlJs from 'sql.js'; + +import worker from '../worker/src/index.js'; +import { hashPassword } from '../worker/src/auth.js'; +import { + getRoomSyncCursor, + insertMessageIdempotent, + listRoomMessageEvents +} from '../worker/src/data/messages.js'; +import { runScheduledGc } from '../worker/src/gc.js'; +import { saveUploadedFile } from '../worker/src/api/upload.js'; +import { + createMobileDeviceSession, + refreshMobileDeviceSession, + revokeMobileDeviceSession +} from '../worker/src/mobile-session.js'; +import { issueRealtimeTicket, consumeRealtimeTicket } from '../worker/src/realtime-tickets.js'; +import { validateSession } from '../worker/src/session.js'; +import { createD1Adapter, createKvAdapter } from './support/d1.js'; + +const SQL = await initSqlJs(); + +function encodedKey(seed = 1) { + return Buffer.from(Uint8Array.from({ length: 32 }, (_, index) => seed + index)).toString( + 'base64' + ); +} + +function createEnvironment() { + const database = new SQL.Database(); + database.exec(readFileSync(new URL('../worker/schema.sql', import.meta.url), 'utf8')); + const files = new Map(); + return { + database, + env: { + DB: createD1Adapter(database), + SESSIONS: createKvAdapter(), + EDGECHAT_ENCRYPTION_KEYRING: JSON.stringify({ + activeKeyId: 'test-v1', + keys: { 'test-v1': encodedKey() } + }), + MAX_FILE_SIZE: '20971520', + ALLOWED_FILE_TYPES: 'image/,video/,text/,application/pdf,application/octet-stream', + FILES: { + files, + async put(key, value, metadata) { + files.set(key, { value, metadata }); + }, + async delete(key) { + files.delete(key); + }, + async get(key) { + return files.get(key) || null; + } + } + } + }; +} + +async function seedUser(database, username = 'alice') { + const password = 'correct horse battery staple'; + const credentials = await hashPassword(password); + database.run( + `INSERT INTO users ( + username, display_name, password_hash, password_salt, is_admin, session_version + ) VALUES (?, ?, ?, ?, 0, 0)`, + [username, 'Alice', credentials.hash, credentials.salt] + ); + const id = Number(database.exec('SELECT last_insert_rowid()')[0].values[0][0]); + return { + password, + user: { + id, + username, + display_name: 'Alice', + avatar_key: null, + is_admin: 0, + session_version: 0 + } + }; +} + +test('设备会话轮换 refresh token,注销后立即拒绝现有 access token', async () => { + const { database, env } = createEnvironment(); + const { user } = await seedUser(database); + const device = { + installationId: crypto.randomUUID(), + name: 'Pixel test', + appVersion: '1.0.0' + }; + const first = await createMobileDeviceSession(env, user, device); + assert.equal((await validateSession(env, first.accessToken)).ok, true); + + const second = await refreshMobileDeviceSession( + env, + first.refreshToken, + device.installationId + ); + assert.notEqual(second.refreshToken, first.refreshToken); + await assert.rejects( + refreshMobileDeviceSession(env, first.refreshToken, device.installationId), + /刷新凭据/ + ); + assert.equal((await validateSession(env, second.accessToken)).ok, true); + + const stored = JSON.parse(await env.SESSIONS.get(second.accessToken)); + await revokeMobileDeviceSession(env, stored); + assert.equal((await validateSession(env, second.accessToken)).ok, false); +}); + +test('实时票据绑定移动会话并且只能消费一次', async () => { + const { database, env } = createEnvironment(); + const { user } = await seedUser(database); + const login = await createMobileDeviceSession(env, user, { + installationId: crypto.randomUUID(), + name: 'Ticket device', + appVersion: '1.0.0' + }); + const session = JSON.parse(await env.SESSIONS.get(login.accessToken)); + const issued = await issueRealtimeTicket(env, session, { + scope: 'room', + roomKind: 'public', + roomId: 1 + }); + const consumed = await consumeRealtimeTicket(env, issued.ticket); + assert.equal(consumed.scope, 'room'); + assert.equal(consumed.roomId, 1); + assert.equal(await consumeRealtimeTicket(env, issued.ticket), null); +}); + +test('客户端消息和附件重试复用同一服务端记录', async () => { + const { database, env } = createEnvironment(); + const { user } = await seedUser(database); + const channelId = Number( + database.exec("SELECT id FROM channels WHERE name = 'general'")[0].values[0][0] + ); + const clientMessageId = crypto.randomUUID(); + const firstMessage = await insertMessageIdempotent(env, { + channelId, + senderId: user.id, + content: 'hello', + clientMessageId + }); + const retryMessage = await insertMessageIdempotent(env, { + channelId, + senderId: user.id, + content: 'hello', + clientMessageId + }); + assert.equal(firstMessage.created, true); + assert.equal(retryMessage.created, false); + assert.equal(retryMessage.message.id, firstMessage.message.id); + assert.equal(retryMessage.message.clientMessageId, clientMessageId); + + database.run("INSERT INTO channels (name, kind, created_by) VALUES ('mobile-test', 'private', ?)", [ + user.id + ]); + const secondChannelId = Number(database.exec('SELECT last_insert_rowid()')[0].values[0][0]); + const sameIdInAnotherRoom = await insertMessageIdempotent(env, { + channelId: secondChannelId, + senderId: user.id, + content: 'same client id, different room', + clientMessageId + }); + assert.equal(sameIdInAnotherRoom.created, true); + assert.notEqual(sameIdInAnotherRoom.message.id, firstMessage.message.id); + + const uploadId = crypto.randomUUID(); + const file = new File([new TextEncoder().encode('file body')], 'note.txt', { + type: 'text/plain' + }); + const firstUpload = await saveUploadedFile(env, { userId: user.id }, file, { + clientUploadId: uploadId + }); + const retryUpload = await saveUploadedFile(env, { userId: user.id }, file, { + clientUploadId: uploadId + }); + assert.equal(firstUpload.created, true); + assert.equal(retryUpload.created, false); + assert.equal(retryUpload.file.key, firstUpload.file.key); + assert.equal(env.FILES.files.size, 1); + + database.run('UPDATE messages SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?', [ + firstMessage.message.id + ]); + const sync = await listRoomMessageEvents(env, channelId, 0, 100); + assert.equal(sync.events.at(-1).type, 'message_deleted'); + assert.equal(sync.events.at(-1).messageId, firstMessage.message.id); + + await assert.rejects( + insertMessageIdempotent(env, { + channelId, + senderId: user.id, + content: 'deleted retry', + clientMessageId + }), + /idempotency key was already consumed/ + ); + + database.run( + `INSERT INTO message_event_compaction (channel_id, compacted_through) + VALUES (?, ?) + ON CONFLICT(channel_id) DO UPDATE SET compacted_through = excluded.compacted_through`, + [channelId, sync.nextCursor] + ); + await assert.rejects( + listRoomMessageEvents(env, channelId, sync.nextCursor - 1, 100), + (error) => error.code === 'sync_cursor_expired' && error.status === 409 + ); +}); + +test('API v1 从 capabilities、设备登录到复用 bootstrap 保持统一契约', async () => { + const { database, env } = createEnvironment(); + const { password } = await seedUser(database); + + const capabilities = await worker.fetch(new Request('https://chat.example/api/v1/capabilities'), env); + assert.equal(capabilities.status, 200); + assert.equal((await capabilities.json()).apiVersion, 1); + + const login = await worker.fetch( + new Request('https://chat.example/api/v1/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + username: 'alice', + password, + device: { + installationId: crypto.randomUUID(), + name: 'API device', + appVersion: '1.0.0' + } + }) + }), + env + ); + assert.equal(login.status, 200); + const credentials = await login.json(); + assert.ok(credentials.accessToken); + assert.ok(credentials.refreshToken); + + const bootstrap = await worker.fetch( + new Request('https://chat.example/api/v1/bootstrap', { + headers: { Authorization: `Bearer ${credentials.accessToken}` } + }), + env + ); + assert.equal(bootstrap.status, 200); + const payload = await bootstrap.json(); + assert.equal(Array.isArray(payload.channels), true); + assert.equal(payload.channels[0].name, 'general'); + + const unauthorized = await worker.fetch( + new Request('https://chat.example/api/v1/bootstrap'), + env + ); + assert.equal(unauthorized.status, 401); + assert.deepEqual(Object.keys((await unauthorized.json()).error).sort(), ['code', 'message']); +}); + +test('GC 清理同步事件前记录每个会话的压缩游标', async () => { + const { database, env } = createEnvironment(); + const { user } = await seedUser(database); + const channelId = Number( + database.exec("SELECT id FROM channels WHERE name = 'general'")[0].values[0][0] + ); + const message = await insertMessageIdempotent(env, { + channelId, + senderId: user.id, + content: 'old event', + clientMessageId: crypto.randomUUID() + }); + assert.ok(message.message.id > 0); + const eventSequence = database.exec('SELECT MAX(sequence) FROM message_events')[0].values[0][0]; + database.run("UPDATE message_events SET created_at = datetime('now', '-10 day')"); + + const summary = await runScheduledGc({ + ...env, + MESSAGE_RETENTION_DAYS: '7', + GC_BATCH_SIZE: '10' + }); + + assert.equal(summary.expiredMessageEventsDeleted, 1); + assert.equal(database.exec('SELECT COUNT(*) FROM message_events')[0].values[0][0], 0); + assert.equal(await getRoomSyncCursor(env.DB, channelId), eventSequence); + assert.equal( + database.exec( + `SELECT compacted_through FROM message_event_compaction WHERE channel_id = ${channelId}` + )[0].values[0][0], + eventSequence + ); +}); diff --git a/test/support/d1.js b/test/support/d1.js new file mode 100644 index 00000000..d92c7491 --- /dev/null +++ b/test/support/d1.js @@ -0,0 +1,64 @@ +export function createD1Adapter(database) { + function prepare(sql) { + let bindings = []; + return { + bind(...values) { + bindings = values; + return this; + }, + async all() { + const statement = database.prepare(sql); + statement.bind(bindings); + const results = []; + while (statement.step()) { + results.push(statement.getAsObject()); + } + statement.free(); + return { results }; + }, + async run() { + const statement = database.prepare(sql); + statement.run(bindings); + statement.free(); + const changes = database.getRowsModified(); + const lastRow = database.exec('SELECT last_insert_rowid() AS id'); + const lastRowId = Number(lastRow[0]?.values?.[0]?.[0] || 0); + return { meta: { changes, last_row_id: lastRowId } }; + } + }; + } + + return { + prepare, + async batch(statements) { + database.run('BEGIN'); + try { + const results = []; + for (const statement of statements) { + results.push(await statement.run()); + } + database.run('COMMIT'); + return results; + } catch (error) { + database.run('ROLLBACK'); + throw error; + } + } + }; +} + +export function createKvAdapter() { + const values = new Map(); + return { + values, + async get(key) { + return values.get(String(key)) ?? null; + }, + async put(key, value) { + values.set(String(key), String(value)); + }, + async delete(key) { + values.delete(String(key)); + } + }; +} diff --git a/worker/migrations/2026-08-30-mobile-client-v1.sql b/worker/migrations/2026-08-30-mobile-client-v1.sql new file mode 100644 index 00000000..559a45b2 --- /dev/null +++ b/worker/migrations/2026-08-30-mobile-client-v1.sql @@ -0,0 +1,80 @@ +ALTER TABLE messages ADD COLUMN client_message_id TEXT; +ALTER TABLE uploaded_files ADD COLUMN client_upload_id TEXT; + +CREATE TABLE IF NOT EXISTS device_sessions ( + id TEXT PRIMARY KEY, + user_id INTEGER NOT NULL, + installation_id TEXT NOT NULL, + device_name TEXT NOT NULL, + app_version TEXT NOT NULL DEFAULT '', + refresh_token_hash TEXT NOT NULL, + session_version INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_used_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TEXT NOT NULL, + revoked_at TEXT, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS realtime_tickets ( + token_hash TEXT PRIMARY KEY, + access_token_ciphertext TEXT NOT NULL, + user_id INTEGER NOT NULL, + device_session_id TEXT NOT NULL, + scope TEXT NOT NULL CHECK (scope IN ('room', 'inbox')), + room_kind TEXT CHECK (room_kind IN ('public', 'private', 'dm')), + room_id INTEGER, + expires_at TEXT NOT NULL, + consumed_at TEXT, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (device_session_id) REFERENCES device_sessions(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS message_events ( + sequence INTEGER PRIMARY KEY AUTOINCREMENT, + channel_id INTEGER NOT NULL, + message_id INTEGER NOT NULL, + event_type TEXT NOT NULL CHECK (event_type IN ('created', 'deleted')), + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_client_message + ON messages(sender_id, client_message_id) + WHERE client_message_id IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_uploaded_files_client_upload + ON uploaded_files(owner_user_id, client_upload_id) + WHERE client_upload_id IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_device_sessions_refresh_token + ON device_sessions(refresh_token_hash); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_device_sessions_user_installation_active + ON device_sessions(user_id, installation_id) + WHERE revoked_at IS NULL; + +CREATE INDEX IF NOT EXISTS idx_device_sessions_user_active + ON device_sessions(user_id, revoked_at, expires_at); + +CREATE INDEX IF NOT EXISTS idx_realtime_tickets_expiry + ON realtime_tickets(expires_at, consumed_at); + +CREATE INDEX IF NOT EXISTS idx_message_events_channel_sequence + ON message_events(channel_id, sequence); + +-- 触发器让所有现有提交路径自动进入同一个同步事件流,不要求调用者额外记账。 +CREATE TRIGGER IF NOT EXISTS record_message_created_event +AFTER INSERT ON messages +BEGIN + INSERT INTO message_events (channel_id, message_id, event_type) + VALUES (NEW.channel_id, NEW.id, 'created'); +END; + +CREATE TRIGGER IF NOT EXISTS record_message_deleted_event +AFTER UPDATE OF deleted_at ON messages +WHEN OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL +BEGIN + INSERT INTO message_events (channel_id, message_id, event_type) + VALUES (NEW.channel_id, NEW.id, 'deleted'); +END; diff --git a/worker/migrations/2026-08-30-native-client-hardening.sql b/worker/migrations/2026-08-30-native-client-hardening.sql new file mode 100644 index 00000000..ce96d743 --- /dev/null +++ b/worker/migrations/2026-08-30-native-client-hardening.sql @@ -0,0 +1,12 @@ +DROP INDEX IF EXISTS idx_messages_client_message; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_channel_client_message + ON messages(channel_id, sender_id, client_message_id) + WHERE client_message_id IS NOT NULL; + +CREATE TABLE IF NOT EXISTS message_event_compaction ( + channel_id INTEGER PRIMARY KEY, + compacted_through INTEGER NOT NULL DEFAULT 0, + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE +); diff --git a/worker/schema.sql b/worker/schema.sql index 085a87de..5a2a17aa 100644 --- a/worker/schema.sql +++ b/worker/schema.sql @@ -111,6 +111,7 @@ CREATE TABLE IF NOT EXISTS messages ( source_message_id TEXT, source_attachment_id TEXT, source_attachment_unique_id TEXT, + client_message_id TEXT, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, deleted_at TEXT, CHECK ( @@ -197,10 +198,72 @@ CREATE TABLE IF NOT EXISTS uploaded_files ( filename TEXT NOT NULL DEFAULT '', content_type TEXT NOT NULL DEFAULT '', size INTEGER NOT NULL DEFAULT 0, + client_upload_id TEXT, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (owner_user_id) REFERENCES users(id) ); +CREATE TABLE IF NOT EXISTS device_sessions ( + id TEXT PRIMARY KEY, + user_id INTEGER NOT NULL, + installation_id TEXT NOT NULL, + device_name TEXT NOT NULL, + app_version TEXT NOT NULL DEFAULT '', + refresh_token_hash TEXT NOT NULL, + session_version INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_used_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TEXT NOT NULL, + revoked_at TEXT, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS realtime_tickets ( + token_hash TEXT PRIMARY KEY, + access_token_ciphertext TEXT NOT NULL, + user_id INTEGER NOT NULL, + device_session_id TEXT NOT NULL, + scope TEXT NOT NULL CHECK (scope IN ('room', 'inbox')), + room_kind TEXT CHECK (room_kind IN ('public', 'private', 'dm')), + room_id INTEGER, + expires_at TEXT NOT NULL, + consumed_at TEXT, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (device_session_id) REFERENCES device_sessions(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS message_events ( + sequence INTEGER PRIMARY KEY AUTOINCREMENT, + channel_id INTEGER NOT NULL, + message_id INTEGER NOT NULL, + event_type TEXT NOT NULL CHECK (event_type IN ('created', 'deleted')), + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE +); + +CREATE TABLE IF NOT EXISTS message_event_compaction ( + channel_id INTEGER PRIMARY KEY, + compacted_through INTEGER NOT NULL DEFAULT 0, + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (channel_id) REFERENCES channels(id) ON DELETE CASCADE +); + +-- 由数据库在消息写入事务内生成同步游标,HTTP 与 WebSocket 两条提交入口不会产生不同步的事件。 +CREATE TRIGGER IF NOT EXISTS record_message_created_event +AFTER INSERT ON messages +BEGIN + INSERT INTO message_events (channel_id, message_id, event_type) + VALUES (NEW.channel_id, NEW.id, 'created'); +END; + +CREATE TRIGGER IF NOT EXISTS record_message_deleted_event +AFTER UPDATE OF deleted_at ON messages +WHEN OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL +BEGIN + INSERT INTO message_events (channel_id, message_id, event_type) + VALUES (NEW.channel_id, NEW.id, 'deleted'); +END; + CREATE TABLE IF NOT EXISTS pending_r2_delete ( object_key TEXT PRIMARY KEY, retry_count INTEGER NOT NULL DEFAULT 0, @@ -250,6 +313,10 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_external_source ON messages(source, source_message_id) WHERE source_message_id IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS idx_messages_channel_client_message + ON messages(channel_id, sender_id, client_message_id) + WHERE client_message_id IS NOT NULL; + CREATE INDEX IF NOT EXISTS idx_message_reads_user ON message_reads(user_id, updated_at DESC); @@ -274,5 +341,25 @@ CREATE INDEX IF NOT EXISTS idx_pending_r2_delete_next_retry CREATE INDEX IF NOT EXISTS idx_uploaded_files_owner ON uploaded_files(owner_user_id, created_at DESC); +CREATE UNIQUE INDEX IF NOT EXISTS idx_uploaded_files_client_upload + ON uploaded_files(owner_user_id, client_upload_id) + WHERE client_upload_id IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_device_sessions_refresh_token + ON device_sessions(refresh_token_hash); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_device_sessions_user_installation_active + ON device_sessions(user_id, installation_id) + WHERE revoked_at IS NULL; + +CREATE INDEX IF NOT EXISTS idx_device_sessions_user_active + ON device_sessions(user_id, revoked_at, expires_at); + +CREATE INDEX IF NOT EXISTS idx_realtime_tickets_expiry + ON realtime_tickets(expires_at, consumed_at); + +CREATE INDEX IF NOT EXISTS idx_message_events_channel_sequence + ON message_events(channel_id, sequence); + CREATE INDEX IF NOT EXISTS idx_telegram_mappings_channel ON telegram_mappings(channel_id, enabled, id); diff --git a/worker/src/api/upload.js b/worker/src/api/upload.js index 27d41f9e..aec9b127 100644 --- a/worker/src/api/upload.js +++ b/worker/src/api/upload.js @@ -1,4 +1,9 @@ -import { canAccessFile, getUploadedFileMetadata, recordUploadedFile } from '../data/uploaded-files.js'; +import { + canAccessFile, + getUploadedFileByClientId, + getUploadedFileMetadata, + recordUploadedFile +} from '../data/uploaded-files.js'; import { decryptAttachment, encryptAttachment } from '../encryption.js'; import { normalizeContentType, sanitizeFilename } from '../attachment-metadata.js'; import { validateSession } from '../session.js'; @@ -81,52 +86,15 @@ export function registerUploadRoutes(app) { } try { - validateUpload(c.env, file); + const result = await saveUploadedFile(c.env, session, file); + return c.json({ file: result.file }); } catch (error) { - return errorResponse(error.message); - } - - const extension = file.name.includes('.') ? file.name.slice(file.name.lastIndexOf('.')) : ''; - const key = `${session.userId}/${Date.now()}-${crypto.randomUUID()}${extension}`; - const encryptedFile = await encryptAttachment(c.env, await file.arrayBuffer(), key); - await c.env.FILES.put(key, encryptedFile, { - httpMetadata: { - contentType: normalizeContentType(file.type) || 'application/octet-stream', - cacheControl: FILE_RESPONSE_CACHE_CONTROL - }, - customMetadata: { - filename: sanitizeFilename(file.name), - edgechatEncryption: 'v1' - } - }); - - try { - await recordUploadedFile(c.env.DB, { - key, - ownerUserId: session.userId, - filename: sanitizeFilename(file.name), - contentType: normalizeContentType(file.type) || 'application/octet-stream', - size: file.size - }); - } catch (error) { - // 元数据写入失败时删除刚上传的密文,避免生成无法归属、也无法被消息引用的孤儿对象。 - try { - await c.env.FILES.delete(key); - } catch (deleteError) { - console.warn('Failed to delete orphaned upload after metadata error', deleteError); + const message = String(error?.message || ''); + if (message.startsWith('文件大小不能超过') || message === '该文件类型不允许上传') { + return errorResponse(message); } throw error; } - - return c.json({ - file: { - key, - name: file.name, - type: file.type || 'application/octet-stream', - size: file.size, - url: `/files/${encodeURIComponent(key)}` - } - }); }); app.get('/files/:key{.+}', async (c) => { @@ -189,3 +157,55 @@ export function registerUploadRoutes(app) { return new Response(decrypted.bytes, { headers }); }); } + +export async function saveUploadedFile(env, session, file, { clientUploadId = null } = {}) { + validateUpload(env, file); + if (clientUploadId) { + const existing = await getUploadedFileByClientId(env.DB, session.userId, clientUploadId); + if (existing) return { file: existing, created: false }; + } + + const extension = file.name.includes('.') ? file.name.slice(file.name.lastIndexOf('.')) : ''; + const key = `${session.userId}/${Date.now()}-${crypto.randomUUID()}${extension}`; + const filename = sanitizeFilename(file.name); + const contentType = normalizeContentType(file.type) || 'application/octet-stream'; + const encryptedFile = await encryptAttachment(env, await file.arrayBuffer(), key); + await env.FILES.put(key, encryptedFile, { + httpMetadata: { contentType, cacheControl: FILE_RESPONSE_CACHE_CONTROL }, + customMetadata: { filename, edgechatEncryption: 'v1' } + }); + + try { + await recordUploadedFile(env.DB, { + key, + ownerUserId: session.userId, + filename, + contentType, + size: file.size, + clientUploadId + }); + } catch (error) { + // 元数据失败或幂等键竞争时移除本次新对象,避免 R2 留下没有稳定引用的副本。 + try { + await env.FILES.delete(key); + } catch (deleteError) { + console.warn('Failed to delete orphaned upload after metadata error', deleteError); + } + if (clientUploadId && String(error?.message || error).includes('UNIQUE')) { + const existing = await getUploadedFileByClientId(env.DB, session.userId, clientUploadId); + if (existing) return { file: existing, created: false }; + } + throw error; + } + + return { + created: true, + file: { + key, + name: filename, + type: contentType, + size: file.size, + url: `/files/${encodeURIComponent(key)}` + } + }; +} diff --git a/worker/src/api/v1.js b/worker/src/api/v1.js new file mode 100644 index 00000000..bf80e88e --- /dev/null +++ b/worker/src/api/v1.js @@ -0,0 +1,307 @@ +import { verifyPassword } from '../auth.js'; +import { saveUploadedFile } from './upload.js'; +import { + getRoomSyncCursor, + listMessages, + listRoomMessageEvents +} from '../data/messages.js'; +import { getSiteSettings } from '../data/site-settings.js'; +import { getUserByUsername } from '../data/users.js'; +import { + forwardInboxConnection, + forwardRoomConnection, + submitClientRoomAction +} from '../do-bridge.js'; +import { ApiError } from '../errors.js'; +import { authMiddleware } from '../middleware.js'; +import { + createMobileDeviceSession, + refreshMobileDeviceSession, + revokeMobileDeviceSession +} from '../mobile-session.js'; +import { issueRealtimeTicket, consumeRealtimeTicket } from '../realtime-tickets.js'; +import { authorizeRoom, isRoomKind } from '../room-access.js'; +import { markRoomRead } from '../data/unread.js'; +import { isUserDisabled } from '../user-status.js'; +import { + errorCodeForStatus, + parseJsonRequest, + requestBodyTooLarge, + sanitizeLimit, + v1ErrorResponse +} from '../utils.js'; + +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + +function isUuid(value) { + return UUID_PATTERN.test(String(value || '').trim()); +} + +function validRoomRequest(kind, roomId) { + return isRoomKind(kind) && Number.isInteger(roomId) && roomId > 0; +} + +async function requireRoom(c) { + const kind = String(c.req.param('kind') || ''); + const roomId = Number(c.req.param('id')); + if (!validRoomRequest(kind, roomId)) { + throw new ApiError('会话参数无效', 400, 'invalid_room'); + } + const session = c.get('session'); + const access = await authorizeRoom(c.env.DB, session, kind, roomId); + if (!access.ok) { + throw new ApiError('无权访问该会话', 403, 'forbidden'); + } + return { session, kind, roomId, room: access.room }; +} + +async function legacyProxyRequest(request, pathname) { + const url = new URL(request.url); + url.pathname = pathname; + const init = { method: request.method, headers: request.headers }; + if (!['GET', 'HEAD'].includes(request.method)) { + // 内部复用旧路由时固化请求体,避免跨运行时传递 ReadableStream 时需要 Node duplex 扩展。 + init.body = await request.arrayBuffer(); + } + return new Request(url.toString(), init); +} + +async function convertLegacyError(response) { + if (response.status < 400) return response; + const contentType = response.headers.get('content-type') || ''; + if (!contentType.includes('application/json')) return response; + const payload = await response.clone().json().catch(() => null); + if (typeof payload?.error !== 'string') return response; + return v1ErrorResponse( + errorCodeForStatus(response.status), + payload.error, + response.status + ); +} + +export function registerV1Routes(app) { + app.get('/api/v1/capabilities', async (c) => { + const site = await getSiteSettings(c.env.DB); + return c.json({ + apiVersion: 1, + site, + limits: { + maxUploadBytes: Number(c.env.MAX_FILE_SIZE || 20971520), + messageRetentionDays: Number(c.env.MESSAGE_RETENTION_DAYS || 7) + }, + features: { + deviceSessions: true, + realtimeTickets: true, + idempotentMessages: true, + idempotentUploads: Boolean(c.env.FILES), + roomSync: true, + backgroundPush: false + } + }); + }); + + app.post('/api/v1/auth/login', async (c) => { + const payload = await parseJsonRequest(c.req.raw); + const username = String(payload.username || '').trim(); + const password = String(payload.password || ''); + if (!username || !password) { + return v1ErrorResponse('invalid_credentials', '请输入用户名和密码', 400); + } + const user = await getUserByUsername(c.env.DB, username); + if ( + !user || + isUserDisabled(user) || + !(await verifyPassword(password, user.password_hash, user.password_salt)) + ) { + return v1ErrorResponse('invalid_credentials', '账号或密码错误', 401); + } + const result = await createMobileDeviceSession(c.env, user, payload.device); + return c.json(result); + }); + + app.post('/api/v1/auth/refresh', async (c) => { + const payload = await parseJsonRequest(c.req.raw); + const result = await refreshMobileDeviceSession( + c.env, + payload.refreshToken, + payload.installationId + ); + return c.json(result); + }); + + app.post('/api/v1/auth/logout', authMiddleware, async (c) => { + await revokeMobileDeviceSession(c.env, c.get('session')); + return c.json({ ok: true }); + }); + + app.post('/api/v1/realtime/tickets', authMiddleware, async (c) => { + const session = c.get('session'); + const payload = await parseJsonRequest(c.req.raw); + const scope = String(payload.scope || ''); + if (scope === 'inbox') { + return c.json(await issueRealtimeTicket(c.env, session, { scope })); + } + const roomKind = String(payload.roomKind || ''); + const roomId = Number(payload.roomId); + if (scope !== 'room' || !validRoomRequest(roomKind, roomId)) { + return v1ErrorResponse('invalid_realtime_scope', '实时连接目标无效'); + } + const access = await authorizeRoom(c.env.DB, session, roomKind, roomId); + if (!access.ok) { + return v1ErrorResponse('forbidden', '无权访问该会话', 403); + } + return c.json(await issueRealtimeTicket(c.env, session, { scope, roomKind, roomId })); + }); + + app.get('/api/v1/realtime/ws', async (c) => { + if (c.req.header('upgrade')?.toLowerCase() !== 'websocket') { + return v1ErrorResponse('websocket_required', '需要 WebSocket 连接', 426); + } + const redeemed = await consumeRealtimeTicket(c.env, c.req.query('ticket')); + if (!redeemed) { + return v1ErrorResponse('realtime_ticket_invalid', '实时票据无效或已过期', 401); + } + const url = new URL(c.req.url); + url.search = ''; + const request = new Request(url.toString(), c.req.raw); + if (redeemed.scope === 'inbox') { + return forwardInboxConnection({ + env: c.env, + request, + principal: redeemed.session + }); + } + return forwardRoomConnection({ + env: c.env, + request, + kind: redeemed.roomKind, + roomId: redeemed.roomId, + principal: redeemed.session + }); + }); + + app.get('/api/v1/rooms/:kind/:id/messages', authMiddleware, async (c) => { + const { roomId, room } = await requireRoom(c); + const messages = await listMessages( + c.env, + roomId, + c.req.query('before'), + sanitizeLimit(c.req.query('limit')) + ); + return c.json({ + room: { + id: Number(room.id), + kind: room.kind, + name: room.name, + description: room.description + }, + messages, + syncCursor: await getRoomSyncCursor(c.env.DB, roomId) + }); + }); + + app.get('/api/v1/rooms/:kind/:id/sync', authMiddleware, async (c) => { + const { roomId } = await requireRoom(c); + const cursor = Math.max(0, Number(c.req.query('cursor')) || 0); + const result = await listRoomMessageEvents( + c.env, + roomId, + cursor, + sanitizeLimit(c.req.query('limit'), 100, 100) + ).catch((error) => { + if (error?.code === 'sync_cursor_expired') { + throw new ApiError('同步游标已过期,请重新加载会话', 409, error.code); + } + throw error; + }); + return c.json(result); + }); + + app.post('/api/v1/rooms/:kind/:id/messages', authMiddleware, async (c) => { + const { session, room } = await requireRoom(c); + const payload = await parseJsonRequest(c.req.raw); + if (!isUuid(payload.clientMessageId)) { + return v1ErrorResponse('client_message_id_invalid', 'clientMessageId 必须是 UUID'); + } + return submitClientRoomAction(c.env, { + room, + principal: session, + action: { + type: 'send', + clientMessageId: payload.clientMessageId, + content: payload.content, + attachment: payload.attachment || null + } + }); + }); + + app.delete('/api/v1/rooms/:kind/:id/messages/:messageId', authMiddleware, async (c) => { + const { session, room } = await requireRoom(c); + return submitClientRoomAction(c.env, { + room, + principal: session, + action: { type: 'delete_message', messageId: Number(c.req.param('messageId')) } + }); + }); + + app.post('/api/v1/rooms/:kind/:id/read', authMiddleware, async (c) => { + const { session, roomId } = await requireRoom(c); + const payload = await parseJsonRequest(c.req.raw); + const messageId = payload.messageId === undefined ? null : Number(payload.messageId); + if (messageId !== null && (!Number.isInteger(messageId) || messageId <= 0)) { + return v1ErrorResponse('message_id_invalid', '消息 ID 无效'); + } + const lastReadMessageId = await markRoomRead(c.env.DB, { + channelId: roomId, + userId: session.userId, + messageId + }); + return c.json({ ok: true, lastReadMessageId }); + }); + + app.post('/api/v1/uploads', authMiddleware, async (c) => { + if (!c.env.FILES) { + return v1ErrorResponse('attachments_unavailable', '当前部署没有绑定 R2,无法上传附件', 503); + } + const maxFileSize = Number(c.env.MAX_FILE_SIZE || 20971520); + if (requestBodyTooLarge(c.req.raw, maxFileSize + 1024 * 1024)) { + return v1ErrorResponse( + 'payload_too_large', + `文件大小不能超过 ${Math.round(maxFileSize / 1024 / 1024)}MB`, + 413 + ); + } + const formData = await c.req.formData(); + const file = formData.get('file'); + const clientUploadId = String(formData.get('clientUploadId') || ''); + if (!(file instanceof File)) { + return v1ErrorResponse('file_required', '请选择文件'); + } + if (!isUuid(clientUploadId)) { + return v1ErrorResponse('client_upload_id_invalid', 'clientUploadId 必须是 UUID'); + } + try { + const result = await saveUploadedFile(c.env, c.get('session'), file, { clientUploadId }); + return c.json(result, result.created ? 201 : 200); + } catch (error) { + const message = String(error?.message || '上传失败'); + if (message.startsWith('文件大小不能超过') || message === '该文件类型不允许上传') { + return v1ErrorResponse('upload_rejected', message); + } + throw error; + } + }); + + app.all('/api/v1/*', async (c) => { + const currentPath = new URL(c.req.url).pathname; + const suffix = currentPath.slice('/api/v1'.length); + if (suffix.startsWith('/admin')) { + return v1ErrorResponse('not_found', '接口不存在', 404); + } + const response = await app.fetch( + await legacyProxyRequest(c.req.raw, `/api${suffix}`), + c.env + ); + return convertLegacyError(response); + }); +} diff --git a/worker/src/auth.js b/worker/src/auth.js index 890624f8..987408ea 100644 --- a/worker/src/auth.js +++ b/worker/src/auth.js @@ -81,9 +81,18 @@ export function isAdminUser(_env, user) { return Boolean(Number(user?.is_admin)); } -export async function putSession(env, session) { +function resolveSessionTtl(session, fallback) { + const expiresAt = Date.parse(String(session?.expiresAt || '')); + if (!Number.isFinite(expiresAt)) { + return fallback; + } + return Math.max(1, Math.ceil((expiresAt - Date.now()) / 1000)); +} + +export async function putSession(env, session, { ttlSeconds = SESSION_TTL_SECONDS } = {}) { await env.SESSIONS.put(session.token, JSON.stringify(session), { - expirationTtl: SESSION_TTL_SECONDS + // 移动端 access token 的寿命短于网页会话;刷新资料时必须保留原到期时间,不能被普通写回延长。 + expirationTtl: resolveSessionTtl(session, ttlSeconds) }); } diff --git a/worker/src/data/messages.js b/worker/src/data/messages.js index 4a2e2ca5..7343d9cc 100644 --- a/worker/src/data/messages.js +++ b/worker/src/data/messages.js @@ -10,12 +10,12 @@ function toNullableNumber(value) { export function mapMessage(row, content = row.content) { const isExternal = row.sender_kind === "external"; const isTelegramExternal = isExternal && row.source === "telegram"; - return { - id: Number(row.id), - content, - createdAt: row.created_at, - source: row.source || "edgechat", - sender: { + const message = { + id: Number(row.id), + content, + createdAt: row.created_at, + source: row.source || "edgechat", + sender: { kind: isExternal ? "external" : "local", id: isExternal ? String(row.external_sender_id || "") : Number(row.sender_id), username: isExternal ? "" : row.sender_username, @@ -39,6 +39,10 @@ export function mapMessage(row, content = row.content) { } : null, }; + if (row.client_message_id) { + message.clientMessageId = row.client_message_id; + } + return message; } export async function externalSenderExists(db, source, senderId) { @@ -59,21 +63,19 @@ export async function externalSenderExists(db, source, senderId) { async function mapDecryptedMessage(env, row) { const content = await decryptMessageContent(env, row.content, { - channelId: row.channel_id, - senderId: row.sender_id ?? 0, - senderContext: - row.sender_kind === "external" - ? `${row.source}:${row.external_sender_id}` - : "", - }); + channelId: row.channel_id, + senderId: row.sender_id ?? 0, + senderContext: + row.sender_kind === "external" ? `${row.source}:${row.external_sender_id}` : "", + }); return mapMessage(row, content); } const MESSAGE_SELECT = `SELECT - m.id, m.channel_id, m.content, m.attachment_key, m.attachment_name, m.attachment_type, - m.attachment_size, m.sender_kind, m.external_sender_id, m.external_sender_name, + m.id, m.channel_id, m.content, m.attachment_key, m.attachment_name, m.attachment_type, + m.attachment_size, m.sender_kind, m.external_sender_id, m.external_sender_name, m.external_sender_avatar_url, m.source, m.source_message_id, - m.source_attachment_id, m.source_attachment_unique_id, m.created_at, + m.source_attachment_id, m.source_attachment_unique_id, m.client_message_id, m.created_at, u.id AS sender_id, u.username AS sender_username, u.display_name AS sender_display_name, u.avatar_key AS sender_avatar_key FROM messages m LEFT JOIN users u ON u.id = m.sender_id`; @@ -112,6 +114,118 @@ export async function getMessageBySource(env, source, sourceMessageId) { return results[0] ? mapDecryptedMessage(env, results[0]) : null; } +export async function getMessageByClientId(env, channelId, senderId, clientMessageId) { + const { results } = await env.DB + .prepare( + `${MESSAGE_SELECT} + WHERE m.channel_id = ? + AND m.sender_id = ? + AND m.client_message_id = ? + AND m.deleted_at IS NULL + LIMIT 1`, + ) + .bind(Number(channelId), Number(senderId), String(clientMessageId)) + .all(); + return results[0] ? mapDecryptedMessage(env, results[0]) : null; +} + +async function hasConsumedClientMessageId(db, channelId, senderId, clientMessageId) { + const { results } = await db + .prepare( + `SELECT id + FROM messages + WHERE channel_id = ? AND sender_id = ? AND client_message_id = ? + LIMIT 1`, + ) + .bind(Number(channelId), Number(senderId), String(clientMessageId)) + .all(); + return Boolean(results[0]); +} + +export async function getRoomSyncCursor(db, channelId) { + const { results } = await db + .prepare( + `SELECT MAX(sequence) AS sequence + FROM ( + SELECT COALESCE(MAX(sequence), 0) AS sequence + FROM message_events + WHERE channel_id = ? + UNION ALL + SELECT COALESCE(MAX(compacted_through), 0) AS sequence + FROM message_event_compaction + WHERE channel_id = ? + )`, + ) + .bind(Number(channelId), Number(channelId)) + .all(); + return Number(results[0]?.sequence || 0); +} + +export async function getRoomCompactedCursor(db, channelId) { + const { results } = await db + .prepare( + `SELECT compacted_through + FROM message_event_compaction + WHERE channel_id = ? + LIMIT 1`, + ) + .bind(Number(channelId)) + .all(); + return Number(results[0]?.compacted_through || 0); +} + +export async function listRoomMessageEvents(env, channelId, afterSequence = 0, limit = 100) { + const normalizedCursor = Number(afterSequence) || 0; + const compactedThrough = await getRoomCompactedCursor(env.DB, channelId); + if (normalizedCursor < compactedThrough) { + const error = new Error("Room sync cursor expired"); + error.name = "RoomSyncCursorExpiredError"; + error.code = "sync_cursor_expired"; + error.status = 409; + throw error; + } + const pageSize = Math.min(Math.max(Number(limit) || 100, 1), 100); + const { results } = await env.DB + .prepare( + `SELECT sequence, message_id, event_type, created_at + FROM message_events + WHERE channel_id = ? AND sequence > ? + ORDER BY sequence ASC + LIMIT ?`, + ) + .bind(Number(channelId), normalizedCursor, pageSize + 1) + .all(); + const page = results.slice(0, pageSize); + const events = []; + for (const row of page) { + if (row.event_type === "deleted") { + events.push({ + sequence: Number(row.sequence), + type: "message_deleted", + messageId: Number(row.message_id), + createdAt: row.created_at, + }); + continue; + } + const message = await getMessageById(env, row.message_id); + if (message) { + events.push({ + sequence: Number(row.sequence), + type: "message", + message, + createdAt: row.created_at, + }); + } + } + return { + events, + nextCursor: page.length + ? Number(page[page.length - 1].sequence) + : normalizedCursor, + hasMore: results.length > pageSize, + }; +} + export async function softDeleteMessage(db, { channelId, messageId }) { const result = await db .prepare( @@ -136,6 +250,7 @@ async function persistMessage(env, { sourceMessageId = null, sourceAttachmentId = null, sourceAttachmentUniqueId = null, + clientMessageId = null, }) { const isExternal = externalSender !== null; const normalizedSenderId = isExternal ? null : Number(senderId); @@ -170,6 +285,9 @@ async function persistMessage(env, { senderId: normalizedSenderId ?? 0, senderContext: isExternal ? `${source}:${externalId}` : "", }); + const normalizedClientMessageId = isExternal + ? null + : String(clientMessageId || "").trim() || null; try { const result = await env.DB .prepare( @@ -177,8 +295,8 @@ async function persistMessage(env, { channel_id, sender_id, content, attachment_key, attachment_name, attachment_type, attachment_size, sender_kind, external_sender_id, external_sender_name, external_sender_avatar_url, source, source_message_id, - source_attachment_id, source_attachment_unique_id - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + source_attachment_id, source_attachment_unique_id, client_message_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .bind( Number(channelId), @@ -189,14 +307,15 @@ async function persistMessage(env, { cleanAttachment?.type || null, cleanAttachment?.size || null, isExternal ? "external" : "local", - isExternal ? externalId : null, - isExternal ? externalName : null, - isExternal ? String(externalSender.avatarUrl || "") : null, + isExternal ? externalId : null, + isExternal ? externalName : null, + isExternal ? String(externalSender.avatarUrl || "") : null, String(source || "edgechat"), sourceMessageId ? String(sourceMessageId) : null, sourceAttachmentId ? String(sourceAttachmentId) : null, sourceAttachmentUniqueId ? String(sourceAttachmentUniqueId) : null, - ) + normalizedClientMessageId, + ) .run(); return { message: await getMessageById(env, result.meta.last_row_id), created: true }; } catch (error) { @@ -206,20 +325,52 @@ async function persistMessage(env, { return { message: existing, created: false }; } } + if (normalizedClientMessageId && String(error?.message || error).includes("UNIQUE")) { + const existing = await getMessageByClientId( + env, + channelId, + normalizedSenderId, + normalizedClientMessageId, + ); + if (existing) { + return { message: existing, created: false }; + } + if ( + await hasConsumedClientMessageId( + env.DB, + channelId, + normalizedSenderId, + normalizedClientMessageId, + ) + ) { + throw new Error("Message idempotency key was already consumed"); + } + } throw error; } } -export async function insertMessage(env, { channelId, senderId, content, attachment }) { +export async function insertMessage(env, { + channelId, + senderId, + content, + attachment, + clientMessageId = null, +}) { const result = await persistMessage(env, { channelId, senderId, content, attachment, + clientMessageId, }); return result.message; } +export function insertMessageIdempotent(env, payload) { + return persistMessage(env, payload); +} + export function insertExternalMessage(env, payload) { return persistMessage(env, payload); } diff --git a/worker/src/data/uploaded-files.js b/worker/src/data/uploaded-files.js index f9ce7830..d7d76e93 100644 --- a/worker/src/data/uploaded-files.js +++ b/worker/src/data/uploaded-files.js @@ -1,28 +1,55 @@ export async function recordUploadedFile( db, - { key, ownerUserId, filename, contentType, size }, + { key, ownerUserId, filename, contentType, size, clientUploadId = null }, ) { await db .prepare( `INSERT INTO uploaded_files ( - object_key, owner_user_id, filename, content_type, size, created_at - ) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP) - ON CONFLICT(object_key) DO UPDATE SET - owner_user_id = excluded.owner_user_id, - filename = excluded.filename, - content_type = excluded.content_type, - size = excluded.size`, + object_key, owner_user_id, filename, content_type, size, client_upload_id, created_at + ) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP) + ON CONFLICT(object_key) DO UPDATE SET + owner_user_id = excluded.owner_user_id, + filename = excluded.filename, + content_type = excluded.content_type, + size = excluded.size, + client_upload_id = excluded.client_upload_id`, ) .bind( String(key), Number(ownerUserId), String(filename || ""), String(contentType || ""), - Number(size || 0), - ) + Number(size || 0), + clientUploadId ? String(clientUploadId) : null, + ) .run(); } +function mapUploadedFile(row) { + return row + ? { + key: row.object_key, + name: row.filename, + type: row.content_type, + size: Number(row.size || 0), + url: `/files/${encodeURIComponent(row.object_key)}`, + } + : null; +} + +export async function getUploadedFileByClientId(db, userId, clientUploadId) { + const { results } = await db + .prepare( + `SELECT object_key, filename, content_type, size + FROM uploaded_files + WHERE owner_user_id = ? AND client_upload_id = ? + LIMIT 1`, + ) + .bind(Number(userId), String(clientUploadId)) + .all(); + return mapUploadedFile(results[0]); +} + export async function getUploadedFileMetadata(db, key) { const { results } = await db .prepare( diff --git a/worker/src/do-bridge.js b/worker/src/do-bridge.js index 304e244c..b8fbfef4 100644 --- a/worker/src/do-bridge.js +++ b/worker/src/do-bridge.js @@ -69,6 +69,19 @@ export async function notifyUserInbox(env, userId, payload) { return response; } +export function submitClientRoomAction(env, { room, principal, action }) { + return forwardVerifiedRequest({ + stub: getChannelRoomStub(env, room.kind, room.id), + request: new Request(`${INTERNAL_ORIGIN}/client-action`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ room, action }) + }), + pathname: '/client-action', + principal + }); +} + export async function submitExternalRoomMessage(env, payload) { const room = payload.room; return getChannelRoomStub(env, room.kind, room.id).fetch( diff --git a/worker/src/do/ChannelRoom.js b/worker/src/do/ChannelRoom.js index 660d4a66..f2b9742b 100644 --- a/worker/src/do/ChannelRoom.js +++ b/worker/src/do/ChannelRoom.js @@ -1,4 +1,8 @@ -import { MessageSubmissionError, submitRoomMessage } from '../message-submission.js'; +import { + MessageSubmissionError, + submitRoomMessage, + submitRoomMessageIdempotent +} from '../message-submission.js'; import { deleteRoomMessage, MessageDeletionError } from '../message-deletion.js'; import { submitExternalMessage } from '../external-message-submission.js'; import { forwardEdgeChatMessageToTelegram } from '../integrations/telegram/bridge.js'; @@ -19,7 +23,7 @@ function socketMeta(token, principal, room) { function sendSocketError(ws, message) { try { - ws.send(JSON.stringify({ type: 'error', error: message })); + ws.send(JSON.stringify({ protocolVersion: 1, type: 'error', error: message })); } catch { // Ignore broken sockets. } @@ -173,6 +177,66 @@ export class ChannelRoom { return Response.json({ ok: true, created: result.created, message: result.message }); } + async receiveClientAction(request) { + if (!isVerifiedInternalRequest(request)) { + return Response.json( + { error: { code: 'authentication_required', message: '请先登录' } }, + { status: 401 } + ); + } + + const principal = parseVerifiedPrincipal(request); + const payload = await request.json(); + const room = payload.room; + const action = payload.action; + const access = principal + ? await authorizeRoom(this.env.DB, principal, room?.kind, Number(room?.id)) + : { ok: false }; + if (!access.ok) { + return Response.json( + { error: { code: 'forbidden', message: '无权访问该会话' } }, + { status: 403 } + ); + } + + const meta = { principal, room: access.room }; + try { + if (action?.type === 'send') { + const result = await submitRoomMessageIdempotent(this.env, meta, action); + if (result.created) { + await this.broadcast(result.packet); + this.runMessageProjections(access.room, result.message); + } + return Response.json({ created: result.created, message: result.message }); + } + if (action?.type === 'delete_message') { + const result = await deleteRoomMessage(this.env, meta, action); + await this.broadcast(result.packet); + return Response.json({ ok: true, messageId: result.messageId }); + } + return Response.json( + { error: { code: 'invalid_request', message: '不支持的消息操作' } }, + { status: 400 } + ); + } catch (error) { + if (error instanceof MessageSubmissionError || error instanceof MessageDeletionError) { + return Response.json( + { error: { code: error.code || 'invalid_request', message: error.message } }, + { status: error.status || 400 } + ); + } + console.error(JSON.stringify({ + message: 'client room action failed', + roomId: Number(access.room.id), + error: error instanceof Error ? error.message : String(error) + })); + return Response.json( + { error: { code: 'internal_error', message: '消息操作失败' } }, + { status: 500 } + ); + } + } + async fetch(request) { const url = new URL(request.url); @@ -180,6 +244,10 @@ export class ChannelRoom { return this.receiveExternalMessage(request); } + if (url.pathname === '/client-action' && request.method === 'POST') { + return this.receiveClientAction(request); + } + if (request.headers.get('Upgrade') !== 'websocket') { return new Response('Expected websocket', { status: 426 }); } @@ -216,6 +284,7 @@ export class ChannelRoom { this.connections.set(server, meta); server.send( JSON.stringify({ + protocolVersion: 1, type: 'ready', room: { id: Number(room.id), diff --git a/worker/src/do/UserInbox.js b/worker/src/do/UserInbox.js index 219e4268..be198274 100644 --- a/worker/src/do/UserInbox.js +++ b/worker/src/do/UserInbox.js @@ -38,7 +38,7 @@ export class UserInbox { this.state.acceptWebSocket(server); server.serializeAttachment({ userId }); this.connections.add(server); - server.send(JSON.stringify({ type: 'ready' })); + server.send(JSON.stringify({ protocolVersion: 1, type: 'ready' })); return new Response(null, { status: 101, webSocket: client }); } diff --git a/worker/src/errors.js b/worker/src/errors.js index fdaedd36..f576ac22 100644 --- a/worker/src/errors.js +++ b/worker/src/errors.js @@ -1,8 +1,9 @@ export class ApiError extends Error { - constructor(message, status = 400) { + constructor(message, status = 400, code = 'invalid_request') { super(message); this.name = 'ApiError'; this.status = status; + this.code = code; } } diff --git a/worker/src/gc.js b/worker/src/gc.js index 41b7cad2..379ff943 100644 --- a/worker/src/gc.js +++ b/worker/src/gc.js @@ -81,6 +81,9 @@ function createSummary() { usersDeleted: 0, userMessagesDeleted: 0, userMembershipsDeleted: 0, + expiredRealtimeTicketsDeleted: 0, + expiredMessageEventsDeleted: 0, + expiredDeviceSessionsDeleted: 0, r2Deleted: 0, r2DeleteFailed: 0, r2DeleteQueued: 0, @@ -88,6 +91,69 @@ function createSummary() { }; } +async function runMobileProtocolCleanupStep(env, config, summary) { + const ticketResult = await env.DB.prepare( + `DELETE FROM realtime_tickets + WHERE token_hash IN ( + SELECT token_hash FROM realtime_tickets + WHERE expires_at <= CURRENT_TIMESTAMP OR consumed_at IS NOT NULL + ORDER BY expires_at ASC + LIMIT ? + )` + ) + .bind(config.batchSize) + .run(); + summary.expiredRealtimeTicketsDeleted = Number(ticketResult.meta?.changes || 0); + + const eventCutoff = `-${config.messageRetentionDays} day`; + const [, eventResult] = await env.DB.batch([ + env.DB.prepare( + `INSERT INTO message_event_compaction (channel_id, compacted_through, updated_at) + SELECT channel_id, MAX(sequence), CURRENT_TIMESTAMP + FROM ( + SELECT sequence, channel_id + FROM message_events + WHERE created_at < datetime('now', ?) + ORDER BY sequence ASC + LIMIT ? + ) AS expired_events + WHERE true + GROUP BY channel_id + ON CONFLICT(channel_id) DO UPDATE SET + compacted_through = MAX(message_event_compaction.compacted_through, excluded.compacted_through), + updated_at = CURRENT_TIMESTAMP` + ).bind(eventCutoff, config.batchSize), + env.DB.prepare( + `DELETE FROM message_events + WHERE sequence IN ( + SELECT sequence FROM message_events + WHERE created_at < datetime('now', ?) + ORDER BY sequence ASC + LIMIT ? + )` + ).bind(eventCutoff, config.batchSize) + ]); + summary.expiredMessageEventsDeleted = Number(eventResult.meta?.changes || 0); + + const deviceResult = await env.DB.prepare( + `DELETE FROM device_sessions + WHERE id IN ( + SELECT id FROM device_sessions + WHERE expires_at < datetime('now', ?) + OR (revoked_at IS NOT NULL AND revoked_at < datetime('now', ?)) + ORDER BY expires_at ASC + LIMIT ? + )` + ) + .bind( + `-${config.softDeleteRetentionDays} day`, + `-${config.softDeleteRetentionDays} day`, + config.batchSize + ) + .run(); + summary.expiredDeviceSessionsDeleted = Number(deviceResult.meta?.changes || 0); +} + async function ensureGcSchema(db) { await db.batch([ db.prepare( @@ -536,6 +602,7 @@ export async function runScheduledGc(env) { const summary = createSummary(); await ensureGcSchema(env.DB); + await runMobileProtocolCleanupStep(env, config, summary); await runRetryQueueStep(env, config, summary); await runExpiredMessagesStep(env, config, summary); await runHardDeleteInvitesStep(env, config, summary); diff --git a/worker/src/index.js b/worker/src/index.js index 6b66e714..c9350da4 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -26,6 +26,7 @@ import { registerChannelRoutes } from './api/channels.js'; import { registerDmRoutes } from './api/dm.js'; import { registerMessageRoutes } from './api/messages.js'; import { registerUploadRoutes } from './api/upload.js'; +import { registerV1Routes } from './api/v1.js'; import { registerTelegramAdminRoutes, registerTelegramPublicRoutes @@ -36,16 +37,22 @@ import { UserInbox } from './do/UserInbox.js'; import { forwardInboxConnection, forwardRoomConnection } from './do-bridge.js'; import { runScheduledGc } from './gc.js'; import { isUserDisabled } from './user-status.js'; +import { updateCurrentDeviceSessionVersion } from './mobile-session.js'; import { + errorCodeForStatus, errorResponse, parseJsonRequest, - requestBodyTooLarge + requestBodyTooLarge, + v1ErrorResponse } from './utils.js'; const app = new Hono(); app.use('/api/*', async (c, next) => { - if (requestBodyTooLarge(c.req.raw)) { + const path = new URL(c.req.url).pathname; + const uploadLimit = Number(c.env.MAX_FILE_SIZE || 20971520) + 1024 * 1024; + const maxBytes = ['/api/upload', '/api/v1/uploads'].includes(path) ? uploadLimit : undefined; + if (requestBodyTooLarge(c.req.raw, maxBytes)) { // 提前拒绝超大请求体,避免 Worker 在 JSON 解析前消耗过多内存。 return errorResponse('请求体过大', 413); } @@ -151,6 +158,8 @@ app.post('/api/auth/login', async (c) => { }); }); +registerV1Routes(app); + app.use('/api/*', authMiddleware); app.get('/api/auth/session', async (c) => { @@ -235,6 +244,7 @@ app.post('/api/auth/change-password', async (c) => { ...session, sessionVersion: Number(session.sessionVersion || 0) + 1 }; + await updateCurrentDeviceSessionVersion(c.env, session, nextSession.sessionVersion); await putSession(c.env, nextSession); return c.json({ ok: true }); @@ -338,11 +348,18 @@ app.notFound(async (c) => { return new Response('Not Found', { status: 404 }); }); -app.onError((error) => { +app.onError((error, c) => { console.error(error); + const isV1 = new URL(c.req.url).pathname.startsWith('/api/v1/'); if (error instanceof ApiError) { + if (isV1) { + return v1ErrorResponse(error.code, error.message, error.status); + } return errorResponse(error.message, error.status); } + if (isV1) { + return v1ErrorResponse(errorCodeForStatus(500), '服务器开小差了', 500); + } return errorResponse('服务器开小差了', 500); }); diff --git a/worker/src/message-deletion.js b/worker/src/message-deletion.js index 7452f412..8414ed60 100644 --- a/worker/src/message-deletion.js +++ b/worker/src/message-deletion.js @@ -37,8 +37,8 @@ export function createMessageDeletion({ } return { - messageId, - packet: JSON.stringify({ type: "message_deleted", messageId }), + messageId, + packet: JSON.stringify({ protocolVersion: 1, type: "message_deleted", messageId }), }; }; } diff --git a/worker/src/message-submission.js b/worker/src/message-submission.js index 6f1e4800..64019fa1 100644 --- a/worker/src/message-submission.js +++ b/worker/src/message-submission.js @@ -1,32 +1,51 @@ -import { insertMessage } from "./data/messages.js"; +import { insertMessage, insertMessageIdempotent } from "./data/messages.js"; export class MessageSubmissionError extends Error { - constructor(message) { + constructor(message, code = "invalid_request", status = 400) { super(message); this.name = "MessageSubmissionError"; + this.code = code; + this.status = status; } } export function createMessageSubmission({ persistMessage = insertMessage } = {}) { return async function submitRoomMessage(env, meta, payload) { try { - const message = await persistMessage(env, { - channelId: meta.room.id, - senderId: meta.principal.userId, - content: payload.content, - attachment: payload.attachment, - }); + const persistencePayload = { + channelId: meta.room.id, + senderId: meta.principal.userId, + content: payload.content, + attachment: payload.attachment, + }; + if (payload.clientMessageId) { + persistencePayload.clientMessageId = payload.clientMessageId; + } + const persisted = await persistMessage(env, persistencePayload); + const message = persisted?.message || persisted; + const created = persisted?.message ? persisted.created !== false : true; return { - message, - packet: JSON.stringify({ type: "message", message }), + message, + created, + packet: JSON.stringify({ protocolVersion: 1, type: "message", message }), }; } catch (error) { if (error?.message === "Message content cannot be empty") { throw new MessageSubmissionError("消息内容不能为空"); } + if (error?.message === "Message idempotency key was already consumed") { + throw new MessageSubmissionError( + "该消息已删除,不能使用相同的 clientMessageId 再次发送", + "client_message_id_consumed", + 409, + ); + } throw error; } }; } export const submitRoomMessage = createMessageSubmission(); +export const submitRoomMessageIdempotent = createMessageSubmission({ + persistMessage: insertMessageIdempotent, +}); diff --git a/worker/src/middleware.js b/worker/src/middleware.js index 0283a1d3..7f0da179 100644 --- a/worker/src/middleware.js +++ b/worker/src/middleware.js @@ -1,4 +1,4 @@ -import { errorResponse } from './utils.js'; +import { errorResponse, errorCodeForStatus, v1ErrorResponse } from './utils.js'; import { validateSession } from './session.js'; function extractToken(request) { @@ -15,6 +15,9 @@ export async function authMiddleware(c, next) { const token = extractToken(c.req.raw); const result = await validateSession(c.env, token); if (!result.ok) { + if (new URL(c.req.url).pathname.startsWith('/api/v1/')) { + return v1ErrorResponse(errorCodeForStatus(result.status), result.message, result.status); + } return errorResponse(result.message, result.status); } @@ -25,6 +28,9 @@ export async function authMiddleware(c, next) { export async function adminMiddleware(c, next) { const session = c.get('session'); if (!session?.isAdmin) { + if (new URL(c.req.url).pathname.startsWith('/api/v1/')) { + return v1ErrorResponse('forbidden', '需要管理员权限', 403); + } return errorResponse('需要管理员权限', 403); } diff --git a/worker/src/mobile-session.js b/worker/src/mobile-session.js new file mode 100644 index 00000000..e1a21d0c --- /dev/null +++ b/worker/src/mobile-session.js @@ -0,0 +1,202 @@ +import { deleteSession, isAdminUser, putSession } from './auth.js'; +import { ApiError } from './errors.js'; +import { isUserDisabled } from './user-status.js'; +import { randomToken } from './utils.js'; + +export const MOBILE_ACCESS_TTL_SECONDS = 60 * 60; +export const MOBILE_REFRESH_TTL_DAYS = 90; + +function toSqlTimestamp(date) { + return date.toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, ''); +} + +function refreshExpiry() { + return toSqlTimestamp(new Date(Date.now() + MOBILE_REFRESH_TTL_DAYS * 24 * 60 * 60 * 1000)); +} + +function publicExpiry(value) { + return `${String(value).replace(' ', 'T')}Z`; +} + +function normalizeDevice(device) { + const installationId = String(device?.installationId || '').trim(); + const name = String(device?.name || '').trim().slice(0, 80); + const appVersion = String(device?.appVersion || '').trim().slice(0, 32); + if (!installationId || installationId.length > 128 || !name) { + throw new ApiError('设备信息无效', 400, 'invalid_device'); + } + return { installationId, name, appVersion }; +} + +export async function hashOpaqueToken(token) { + const bytes = new TextEncoder().encode(String(token || '')); + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); + const binary = Array.from(digest, (byte) => String.fromCharCode(byte)).join(''); + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); +} + +async function createAccessSession(env, user, deviceSessionId, installationId) { + const token = randomToken(32); + const expiresAt = new Date(Date.now() + MOBILE_ACCESS_TTL_SECONDS * 1000).toISOString(); + const session = { + token, + userId: Number(user.id), + username: user.username, + displayName: user.display_name, + avatarUrl: user.avatar_key ? `/files/${encodeURIComponent(user.avatar_key)}` : '', + isAdmin: isAdminUser(env, user), + sessionVersion: Number(user.session_version || 0), + sessionKind: 'mobile', + deviceSessionId, + installationId, + expiresAt + }; + await putSession(env, session, { ttlSeconds: MOBILE_ACCESS_TTL_SECONDS }); + return session; +} + +function sessionResponse(accessSession, refreshToken, refreshExpiresAt) { + return { + accessToken: accessSession.token, + accessTokenExpiresAt: accessSession.expiresAt, + refreshToken, + refreshTokenExpiresAt: publicExpiry(refreshExpiresAt), + session: accessSession + }; +} + +export async function createMobileDeviceSession(env, user, rawDevice) { + const device = normalizeDevice(rawDevice); + const deviceSessionId = crypto.randomUUID(); + const refreshToken = randomToken(32); + const refreshTokenHash = await hashOpaqueToken(refreshToken); + const expiresAt = refreshExpiry(); + const sessionVersion = Number(user.session_version || 0); + + await env.DB.batch([ + env.DB.prepare( + `UPDATE device_sessions + SET revoked_at = CURRENT_TIMESTAMP + WHERE user_id = ? + AND installation_id = ? + AND revoked_at IS NULL` + ).bind(Number(user.id), device.installationId), + env.DB.prepare( + `INSERT INTO device_sessions ( + id, user_id, installation_id, device_name, app_version, + refresh_token_hash, session_version, expires_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)` + ).bind( + deviceSessionId, + Number(user.id), + device.installationId, + device.name, + device.appVersion, + refreshTokenHash, + sessionVersion, + expiresAt + ) + ]); + + const accessSession = await createAccessSession( + env, + user, + deviceSessionId, + device.installationId + ); + return sessionResponse(accessSession, refreshToken, expiresAt); +} + +export async function refreshMobileDeviceSession(env, rawRefreshToken, rawInstallationId) { + const refreshToken = String(rawRefreshToken || '').trim(); + const installationId = String(rawInstallationId || '').trim(); + if (!refreshToken || !installationId) { + throw new ApiError('刷新凭据无效', 401, 'refresh_token_invalid'); + } + + const refreshTokenHash = await hashOpaqueToken(refreshToken); + const { results } = await env.DB.prepare( + `SELECT + ds.id AS device_session_id, ds.user_id, ds.installation_id, + ds.refresh_token_hash, ds.session_version AS device_session_version, + u.username, u.display_name, u.avatar_key, u.is_admin, + u.session_version, u.is_disabled, u.disabled_until, u.deleted_at + FROM device_sessions ds + JOIN users u ON u.id = ds.user_id + WHERE ds.refresh_token_hash = ? + AND ds.installation_id = ? + AND ds.revoked_at IS NULL + AND ds.expires_at > CURRENT_TIMESTAMP + LIMIT 1` + ) + .bind(refreshTokenHash, installationId) + .all(); + const row = results[0]; + if ( + !row || + row.deleted_at || + isUserDisabled(row) || + Number(row.device_session_version || 0) !== Number(row.session_version || 0) + ) { + throw new ApiError('刷新凭据已失效,请重新登录', 401, 'refresh_token_invalid'); + } + + const nextRefreshToken = randomToken(32); + const nextRefreshTokenHash = await hashOpaqueToken(nextRefreshToken); + const nextExpiresAt = refreshExpiry(); + const update = await env.DB.prepare( + `UPDATE device_sessions + SET refresh_token_hash = ?, + last_used_at = CURRENT_TIMESTAMP, + expires_at = ? + WHERE id = ? + AND refresh_token_hash = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP` + ) + .bind(nextRefreshTokenHash, nextExpiresAt, row.device_session_id, refreshTokenHash) + .run(); + if (Number(update.meta?.changes || 0) !== 1) { + throw new ApiError('刷新凭据已被使用,请重新登录', 401, 'refresh_token_reused'); + } + + const user = { + id: row.user_id, + username: row.username, + display_name: row.display_name, + avatar_key: row.avatar_key, + is_admin: row.is_admin, + session_version: row.session_version + }; + const accessSession = await createAccessSession( + env, + user, + row.device_session_id, + row.installation_id + ); + return sessionResponse(accessSession, nextRefreshToken, nextExpiresAt); +} + +export async function revokeMobileDeviceSession(env, session) { + if (session?.deviceSessionId) { + await env.DB.prepare( + `UPDATE device_sessions + SET revoked_at = CURRENT_TIMESTAMP + WHERE id = ? AND user_id = ? AND revoked_at IS NULL` + ) + .bind(String(session.deviceSessionId), Number(session.userId)) + .run(); + } + await deleteSession(env, session?.token); +} + +export async function updateCurrentDeviceSessionVersion(env, session, sessionVersion) { + if (!session?.deviceSessionId) return; + await env.DB.prepare( + `UPDATE device_sessions + SET session_version = ?, last_used_at = CURRENT_TIMESTAMP + WHERE id = ? AND user_id = ? AND revoked_at IS NULL` + ) + .bind(Number(sessionVersion), String(session.deviceSessionId), Number(session.userId)) + .run(); +} diff --git a/worker/src/realtime-tickets.js b/worker/src/realtime-tickets.js new file mode 100644 index 00000000..e20cec13 --- /dev/null +++ b/worker/src/realtime-tickets.js @@ -0,0 +1,85 @@ +import { decryptSecretValue, encryptSecretValue } from './encryption.js'; +import { ApiError } from './errors.js'; +import { hashOpaqueToken } from './mobile-session.js'; +import { validateSession } from './session.js'; +import { randomToken } from './utils.js'; + +export const REALTIME_TICKET_TTL_SECONDS = 60; + +function ticketContext(tokenHash) { + return `realtime-ticket:${tokenHash}`; +} + +export async function issueRealtimeTicket(env, session, target) { + if (!session?.deviceSessionId || session.sessionKind !== 'mobile') { + throw new ApiError('当前会话不支持实时票据', 400, 'mobile_session_required'); + } + const ticket = randomToken(32); + const tokenHash = await hashOpaqueToken(ticket); + const accessTokenCiphertext = await encryptSecretValue( + env, + session.token, + ticketContext(tokenHash) + ); + const expiresAt = new Date(Date.now() + REALTIME_TICKET_TTL_SECONDS * 1000) + .toISOString() + .replace('T', ' ') + .replace(/\.\d{3}Z$/, ''); + await env.DB.prepare( + `INSERT INTO realtime_tickets ( + token_hash, access_token_ciphertext, user_id, device_session_id, + scope, room_kind, room_id, expires_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)` + ) + .bind( + tokenHash, + accessTokenCiphertext, + Number(session.userId), + String(session.deviceSessionId), + target.scope, + target.roomKind || null, + target.roomId || null, + expiresAt + ) + .run(); + return { ticket, expiresAt: `${expiresAt.replace(' ', 'T')}Z` }; +} + +export async function consumeRealtimeTicket(env, ticket) { + const cleanTicket = String(ticket || '').trim(); + if (!cleanTicket) return null; + const tokenHash = await hashOpaqueToken(cleanTicket); + const { results } = await env.DB.prepare( + `UPDATE realtime_tickets + SET consumed_at = CURRENT_TIMESTAMP + WHERE token_hash = ? + AND consumed_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + RETURNING access_token_ciphertext, user_id, device_session_id, + scope, room_kind, room_id` + ) + .bind(tokenHash) + .all(); + const row = results[0]; + if (!row) return null; + + const accessToken = await decryptSecretValue( + env, + row.access_token_ciphertext, + ticketContext(tokenHash) + ); + const auth = await validateSession(env, accessToken); + if ( + !auth.ok || + Number(auth.session.userId) !== Number(row.user_id) || + String(auth.session.deviceSessionId || '') !== String(row.device_session_id) + ) { + return null; + } + return { + session: auth.session, + scope: row.scope, + roomKind: row.room_kind || '', + roomId: row.room_id === null ? null : Number(row.room_id) + }; +} diff --git a/worker/src/session.js b/worker/src/session.js index 0a14bb2e..5a766079 100644 --- a/worker/src/session.js +++ b/worker/src/session.js @@ -27,6 +27,25 @@ export async function validateSession(env, token) { return { ok: false, status: 401, message: '账号已不可用' }; } + if (session.deviceSessionId) { + const device = await env.DB.prepare( + `SELECT session_version + FROM device_sessions + WHERE id = ? + AND user_id = ? + AND revoked_at IS NULL + AND expires_at > CURRENT_TIMESTAMP + LIMIT 1` + ) + .bind(String(session.deviceSessionId), session.userId) + .all(); + const deviceSession = device.results[0]; + if (!deviceSession || toNumber(deviceSession.session_version) !== toNumber(user.session_version)) { + await deleteSession(env, token); + return { ok: false, status: 401, message: '设备登录已失效,请重新登录' }; + } + } + const dbVersion = toNumber(user.session_version); const sessionVersion = toNumber(session.sessionVersion); if (sessionVersion !== dbVersion) { diff --git a/worker/src/unread-projection.js b/worker/src/unread-projection.js index 04ca8f04..7bce25d3 100644 --- a/worker/src/unread-projection.js +++ b/worker/src/unread-projection.js @@ -17,8 +17,9 @@ export function createUnreadProjection({ channelId: room.id, userId, }); - await notifyInbox(env, userId, { - type: "room_message", + await notifyInbox(env, userId, { + protocolVersion: 1, + type: "room_message", room: { id: Number(room.id), kind: room.kind, diff --git a/worker/src/utils.js b/worker/src/utils.js index c887f95f..d1dbe545 100644 --- a/worker/src/utils.js +++ b/worker/src/utils.js @@ -12,6 +12,20 @@ export function errorResponse(message, status = 400) { return jsonResponse({ error: message }, { status }); } +export function v1ErrorResponse(code, message, status = 400) { + return jsonResponse({ error: { code, message } }, { status }); +} + +export function errorCodeForStatus(status) { + if (status === 401) return 'authentication_required'; + if (status === 403) return 'forbidden'; + if (status === 404) return 'not_found'; + if (status === 413) return 'payload_too_large'; + if (status === 503) return 'service_unavailable'; + if (status >= 500) return 'internal_error'; + return 'invalid_request'; +} + export const MAX_JSON_BODY_SIZE = 10 * 1024 * 1024; export function requestBodyTooLarge(request, maxBytes = MAX_JSON_BODY_SIZE) { From 2952f427a1a86702773ee65ea4d9fcc6e33aa9c9 Mon Sep 17 00:00:00 2001 From: gdz66601 Date: Sun, 30 Aug 2026 08:09:01 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E9=87=8D=E6=9E=84=E8=81=8A=E5=A4=A9?= =?UTF-8?q?=E9=A1=B5=E4=B8=BA=E6=A8=A1=E5=9D=97=E5=8C=96=E7=BC=96=E6=8E=92?= =?UTF-8?q?=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/components/chat/ConversationList.vue | 264 +++++++-- .../src/components/chat/MessageComposer.vue | 306 ++++++++--- frontend/src/composables/useActiveRoom.js | 70 +-- frontend/src/composables/useChatRoom.js | 15 - frontend/src/composables/useChatSidebar.js | 29 +- .../composables/useConversationCreation.js | 17 +- .../src/composables/useConversationFlow.ts | 64 +++ .../src/composables/useMessageContextMenu.ts | 105 ++++ frontend/src/composables/useRoomManagement.js | 13 +- frontend/src/pages/ChatPage.vue | 503 ++---------------- test/chat-page-composables.test.js | 128 +++++ test/chat-ui-scale.test.js | 30 +- test/conversation-creation.test.js | 23 +- test/room-management.test.js | 16 +- 14 files changed, 901 insertions(+), 682 deletions(-) create mode 100644 frontend/src/composables/useConversationFlow.ts create mode 100644 frontend/src/composables/useMessageContextMenu.ts create mode 100644 test/chat-page-composables.test.js diff --git a/frontend/src/components/chat/ConversationList.vue b/frontend/src/components/chat/ConversationList.vue index c5ba7098..49d84da9 100644 --- a/frontend/src/components/chat/ConversationList.vue +++ b/frontend/src/components/chat/ConversationList.vue @@ -1,52 +1,230 @@ + + diff --git a/frontend/src/components/chat/MessageComposer.vue b/frontend/src/components/chat/MessageComposer.vue index 4b85b3fb..521f37cb 100644 --- a/frontend/src/components/chat/MessageComposer.vue +++ b/frontend/src/components/chat/MessageComposer.vue @@ -1,78 +1,256 @@ + + diff --git a/frontend/src/composables/useActiveRoom.js b/frontend/src/composables/useActiveRoom.js index 265e1b7f..dfa1a552 100644 --- a/frontend/src/composables/useActiveRoom.js +++ b/frontend/src/composables/useActiveRoom.js @@ -19,41 +19,12 @@ export function useActiveRoom({ activeRoom }) { Boolean(activeRoom.value && activeRoom.value.kind !== "dm"), ); - const activeRoomSubtitle = computed(() => { - if (!activeRoom.value) { - return t('chat.selectConversation'); - } - - if (activeRoom.value.kind === "dm") { - return t('chat.directMessageWith', { - username: activeRoom.value.otherUser?.username || activeRoom.value.name, - }); - } - - if (activeRoom.value.isGeneral) { - const memberCount = activeRoom.value.memberCount - ? ` · ${t('chat.memberCount', { count: activeRoom.value.memberCount })}` - : ""; - return `${t('chat.generalGroup')}${memberCount}`; - } - - const visibility = - activeRoom.value.kind === "private" ? t('chat.privateGroup') : t('chat.publicGroup'); - const owner = activeRoom.value.ownerDisplayName - ? ` · ${t('chat.owner', { name: activeRoom.value.ownerDisplayName })}` - : ""; - const memberCount = activeRoom.value.memberCount - ? ` · ${t('chat.memberCount', { count: activeRoom.value.memberCount })}` - : ""; - return `${visibility}${owner}${memberCount}`; - }); - function applyActiveChannel(channel) { - activeRoom.value = { - id: channel.id, - kind: channel.kind, - name: channel.name, - isGeneral: Boolean(channel.isGeneral), + activeRoom.value = { + id: channel.id, + kind: channel.kind, + name: channel.name, + isGeneral: Boolean(channel.isGeneral), description: channel.description, avatarUrl: channel.avatarUrl || "", avatarKey: channel.avatarKey || "", @@ -62,11 +33,6 @@ export function useActiveRoom({ activeRoom }) { myRole: channel.myRole || "", memberCount: Number(channel.memberCount || 0), }; - - } - - function selectChannel(channel) { - applyActiveChannel(channel); } function selectDm(dm) { @@ -80,24 +46,38 @@ export function useActiveRoom({ activeRoom }) { function roomLabel(room) { if (!room) { - return t('chat.noConversationSelected'); + return t("chat.noConversationSelected"); } - if (room.kind === "dm") { return room.otherUser?.displayName || room.name; } - return room.name; } + function roomSubtitle(room, connected = false) { + if (!room) { + return ""; + } + if (room.kind === "dm") { + return room.otherUser?.username + ? `@${room.otherUser.username}` + : connected + ? t("chat.online") + : t("chat.connecting"); + } + if (room.memberCount) { + return t("chat.memberCount", { count: room.memberCount }); + } + return room.isGeneral ? t("chat.generalGroup") : t("chat.groupConversation"); + } + return { activeRoomKey, canManageActiveRoom, hasManageLayer, - activeRoomSubtitle, applyActiveChannel, - selectChannel, selectDm, - roomLabel, + roomLabel, + roomSubtitle, }; } diff --git a/frontend/src/composables/useChatRoom.js b/frontend/src/composables/useChatRoom.js index 23ae1219..62f81d57 100644 --- a/frontend/src/composables/useChatRoom.js +++ b/frontend/src/composables/useChatRoom.js @@ -27,7 +27,6 @@ export function useChatRoom({ const pendingAttachment = ref(null); const sending = ref(false); const messagesEl = ref(null); - const fileInputEl = ref(null); let messageLoadGeneration = 0; function roomKey(room = activeRoom.value) { @@ -236,17 +235,6 @@ export function useChatRoom({ ); } - function handleComposerKeydown(event) { - if (event.key === "Enter" && !event.shiftKey) { - event.preventDefault(); - sendMessage(); - } - } - - function openFilePicker() { - fileInputEl.value?.click(); - } - async function uploadAttachment(event) { const file = event.target.files?.[0]; if (!file) { @@ -298,7 +286,6 @@ export function useChatRoom({ pendingAttachment, sending, messagesEl, - fileInputEl, isOwnMessage, loadMessages, activateRoom, @@ -307,8 +294,6 @@ export function useChatRoom({ disconnectSocket, sendMessage, deleteMessage, - handleComposerKeydown, - openFilePicker, uploadAttachment, clearAttachment, loadOlder, diff --git a/frontend/src/composables/useChatSidebar.js b/frontend/src/composables/useChatSidebar.js index e397d9fa..7c7c4531 100644 --- a/frontend/src/composables/useChatSidebar.js +++ b/frontend/src/composables/useChatSidebar.js @@ -2,6 +2,13 @@ import { computed, ref } from "vue"; import api from "../api.js"; import { compareLocalized, formatDate, t } from "../i18n.js"; +function formatListTime(value) { + if (!value) { + return ""; + } + return formatDate(value, { month: "short", day: "numeric" }); +} + function mapChannelItem(channel, subtitle) { return { key: `${channel.kind}:${channel.id}`, @@ -13,6 +20,7 @@ function mapChannelItem(channel, subtitle) { avatarUrl: channel.avatarUrl || "", fallback: channel.name ? channel.name.slice(0, 1) : t('publicGroups.fallback'), lastMessageAt: channel.lastMessageAt || "", + dateLabel: formatListTime(channel.lastMessageAt), unreadCount: Number(channel.unreadCount || 0), source: channel, }; @@ -32,9 +40,10 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api title: dm.otherUser.displayName, subtitle: t('chat.contact', { username: dm.otherUser.username }), avatarUrl: dm.otherUser.avatarUrl, - fallback: dm.otherUser.displayName, - lastMessageAt: dm.lastMessageAt || "", - unreadCount: Number(dm.unreadCount || 0), + fallback: dm.otherUser.displayName, + lastMessageAt: dm.lastMessageAt || "", + dateLabel: formatListTime(dm.lastMessageAt), + unreadCount: Number(dm.unreadCount || 0), source: dm, })); @@ -78,13 +87,6 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api .sort((left, right) => compareLocalized(left.title, right.title)), ); - function formatListTime(value) { - if (!value) { - return ""; - } - return formatDate(value, { month: 'short', day: 'numeric' }); - } - function findConversationSource(kind, roomId) { const list = kind === "dm" ? dms.value : channels.value; return list.find( @@ -137,10 +139,6 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api } } - function selectChannel(channel) { - applyActiveChannel(channel); - } - async function joinPublicChannel(channel) { await sidebarApi.joinChannel(channel.id); const joinedChannel = channels.value.find( @@ -160,7 +158,7 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api return; } - await selectChannel(item.source); + applyActiveChannel(item.source); markConversationRead(item.kind, item.id); void sidebarApi.markRoomRead(item.kind, item.id).catch(() => {}); } @@ -172,7 +170,6 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api sidebarLoading, conversationItems, publicGroupItems, - formatListTime, markConversationRead, applyConversationActivity, refreshSidebar, diff --git a/frontend/src/composables/useConversationCreation.js b/frontend/src/composables/useConversationCreation.js index 5f69feb3..bc0fdb47 100644 --- a/frontend/src/composables/useConversationCreation.js +++ b/frontend/src/composables/useConversationCreation.js @@ -5,9 +5,7 @@ export function useConversationCreation({ users, dms, error, - refreshSidebar, - conversationItems, - openConversation, + refreshAndOpen, openGroupDialog, conversationApi = api, }) { @@ -46,16 +44,9 @@ export function useConversationCreation({ error.value = ""; try { const payload = await conversationApi.openDm(user.id); - await refreshSidebar(); - const item = conversationItems.value.find( - (conversation) => - conversation.kind === "dm" && - Number(conversation.id) === Number(payload.dm.id), - ); - - // 刷新后的侧栏投影通常包含新私聊;保留返回值兜底,避免投影延迟阻断用户进入会话。 - await openConversation( - item || { kind: "dm", id: payload.dm.id, source: payload.dm }, + await refreshAndOpen( + { kind: "dm", id: payload.dm.id }, + { kind: "dm", id: payload.dm.id, source: payload.dm }, ); closeAddConversation(); } catch (currentError) { diff --git a/frontend/src/composables/useConversationFlow.ts b/frontend/src/composables/useConversationFlow.ts new file mode 100644 index 00000000..6efe1963 --- /dev/null +++ b/frontend/src/composables/useConversationFlow.ts @@ -0,0 +1,64 @@ +import type { Ref } from "vue"; + +export type ConversationIdentity = { + id: number | string; + kind: string; +}; + +export type ConversationItem = ConversationIdentity & { + [key: string]: unknown; +}; + +type ConversationFlowOptions = { + conversationItems: Readonly>; + refreshSidebar: () => Promise; + openConversation: (item: ConversationItem) => Promise; + openConversationView: () => void; +}; + +export function useConversationFlow({ + conversationItems, + refreshSidebar, + openConversation, + openConversationView, +}: ConversationFlowOptions) { + function findByIdentity(identity: ConversationIdentity) { + return conversationItems.value.find( + (item) => + item.kind === identity.kind && Number(item.id) === Number(identity.id), + ); + } + + async function openConversationItem(item: ConversationItem) { + await openConversation(item); + openConversationView(); + } + + async function openByIdentity( + identity: ConversationIdentity, + fallback?: ConversationItem, + ) { + const item = findByIdentity(identity) || fallback; + if (!item) { + return false; + } + + await openConversationItem(item); + return true; + } + + async function refreshAndOpen( + identity: ConversationIdentity, + fallback?: ConversationItem, + ) { + await refreshSidebar(); + return openByIdentity(identity, fallback); + } + + return { + findByIdentity, + openConversationItem, + openByIdentity, + refreshAndOpen, + }; +} diff --git a/frontend/src/composables/useMessageContextMenu.ts b/frontend/src/composables/useMessageContextMenu.ts new file mode 100644 index 00000000..e97240b1 --- /dev/null +++ b/frontend/src/composables/useMessageContextMenu.ts @@ -0,0 +1,105 @@ +import { ref, type Ref } from "vue"; + +type ContextMessage = { + id: number | string; +}; + +type MessageMenuState = { + message: ContextMessage | null; + x: number; + y: number; +}; + +type LongPressOrigin = { + pointerId: number; + x: number; + y: number; +}; + +type MessageContextMenuOptions = { + canModerateMessages: Readonly>; +}; + +const LONG_PRESS_DELAY_MS = 500; +const LONG_PRESS_MOVE_TOLERANCE_PX = 10; + +export function useMessageContextMenu({ + canModerateMessages, +}: MessageContextMenuOptions) { + const messageMenu = ref({ + message: null, + x: 0, + y: 0, + }); + let longPressTimer: ReturnType | null = null; + let longPressOrigin: LongPressOrigin | null = null; + + function closeMessageMenu() { + messageMenu.value = { message: null, x: 0, y: 0 }; + } + + function openMessageMenuAt(message: ContextMessage, x: number, y: number) { + if (!canModerateMessages.value) { + return; + } + messageMenu.value = { message, x, y }; + } + + function cancelMessageLongPress() { + if (longPressTimer !== null) { + globalThis.clearTimeout(longPressTimer); + longPressTimer = null; + } + longPressOrigin = null; + } + + function openMessageContextMenu(event: MouseEvent, message: ContextMessage) { + if (!canModerateMessages.value) { + return; + } + event.preventDefault(); + cancelMessageLongPress(); + openMessageMenuAt(message, event.clientX, event.clientY); + } + + function startMessageLongPress(event: PointerEvent, message: ContextMessage) { + cancelMessageLongPress(); + if (!canModerateMessages.value || event.pointerType === "mouse") { + return; + } + + const origin = { + pointerId: event.pointerId, + x: event.clientX, + y: event.clientY, + }; + longPressOrigin = origin; + longPressTimer = globalThis.setTimeout(() => { + openMessageMenuAt(message, origin.x, origin.y); + longPressTimer = null; + }, LONG_PRESS_DELAY_MS); + } + + function trackMessageLongPress(event: PointerEvent) { + if (!longPressOrigin || event.pointerId !== longPressOrigin.pointerId) { + return; + } + if ( + Math.abs(event.clientX - longPressOrigin.x) > + LONG_PRESS_MOVE_TOLERANCE_PX || + Math.abs(event.clientY - longPressOrigin.y) > + LONG_PRESS_MOVE_TOLERANCE_PX + ) { + cancelMessageLongPress(); + } + } + + return { + messageMenu, + closeMessageMenu, + cancelMessageLongPress, + openMessageContextMenu, + startMessageLongPress, + trackMessageLongPress, + }; +} diff --git a/frontend/src/composables/useRoomManagement.js b/frontend/src/composables/useRoomManagement.js index 620f2c4b..75737d20 100644 --- a/frontend/src/composables/useRoomManagement.js +++ b/frontend/src/composables/useRoomManagement.js @@ -8,8 +8,7 @@ export function useRoomManagement({ users, error, refreshSidebar, - conversationItems, - openConversation, + refreshAndOpen, canManageActiveRoom, onRoomDeleted = () => {}, returnToConversationList = () => {}, @@ -83,15 +82,7 @@ export function useRoomManagement({ kind: createGroupForm.kind, memberUserIds: createGroupForm.memberUserIds, }); - await refreshSidebar(); - const item = conversationItems.value.find( - (conversation) => - conversation.kind === payload.channel.kind && - Number(conversation.id) === Number(payload.channel.id), - ); - if (item) { - await openConversation(item); - } + await refreshAndOpen(payload.channel); closeCreateGroup(); } catch (currentError) { error.value = currentError.message; diff --git a/frontend/src/pages/ChatPage.vue b/frontend/src/pages/ChatPage.vue index 1b1effc3..fcf6c0c8 100644 --- a/frontend/src/pages/ChatPage.vue +++ b/frontend/src/pages/ChatPage.vue @@ -4,25 +4,27 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'; import { useRouter } from 'vue-router'; import { isDemoMode } from '../runtime.js'; import AddConversationDialog from '../components/chat/AddConversationDialog.vue'; +import ConversationList from '../components/chat/ConversationList.vue'; import CreateGroupDialog from '../components/chat/CreateGroupDialog.vue'; import GroupSettingsDialog from '../components/chat/GroupSettingsDialog.vue'; import MemberPanel from '../components/chat/MemberPanel.vue'; import MessageAttachment from '../components/chat/MessageAttachment.vue'; +import MessageComposer from '../components/chat/MessageComposer.vue'; import MessageContextMenu from '../components/chat/MessageContextMenu.vue'; import MobileNavigationDrawer from '../components/chat/MobileNavigationDrawer.vue'; import SenderSourceBadge from '../components/chat/SenderSourceBadge.vue'; -import PendingAttachmentPreview from '../components/chat/PendingAttachmentPreview.vue'; import PublicGroupDiscovery from '../components/chat/PublicGroupDiscovery.vue'; import PublicGroupJoinDialog from '../components/chat/PublicGroupJoinDialog.vue'; import UiAvatar from '../components/ui/Avatar.vue'; import LanguageSwitch from '../components/ui/LanguageSwitch.vue'; -import UiTextarea from '../components/ui/Textarea.vue'; import { useActiveRoom } from '../composables/useActiveRoom.js'; import { useBrowserNotifications } from '../composables/useBrowserNotifications.js'; import { useChatRoom } from '../composables/useChatRoom.js'; import { useChatSidebar } from '../composables/useChatSidebar.js'; import { useChatViewport } from '../composables/useChatViewport.js'; +import { useConversationFlow } from '../composables/useConversationFlow.ts'; import { useConversationCreation } from '../composables/useConversationCreation.js'; +import { useMessageContextMenu } from '../composables/useMessageContextMenu.ts'; import { useRoomManagement } from '../composables/useRoomManagement.js'; import { useUnreadInbox } from '../composables/useUnreadInbox.js'; import store from '../store.js'; @@ -38,7 +40,7 @@ const joiningPublicGroup = ref(false); const session = computed(() => store.session); const showAdminEntry = computed(() => Boolean(session.value?.isAdmin)); -const { activeRoomKey, canManageActiveRoom, applyActiveChannel, selectDm, roomLabel } = +const { activeRoomKey, canManageActiveRoom, applyActiveChannel, selectDm, roomLabel, roomSubtitle } = useActiveRoom({ activeRoom }); const { isMobileViewport, @@ -56,9 +58,15 @@ const activeRoomAvatar = computed(() => { }); const { - channels, dms, users, sidebarLoading, conversationItems, publicGroupItems, formatListTime, + channels, dms, users, sidebarLoading, conversationItems, publicGroupItems, refreshSidebar, openConversation, joinPublicChannel, markConversationRead, applyConversationActivity } = useChatSidebar({ applyActiveChannel, selectDm }); +const { openConversationItem, openByIdentity, refreshAndOpen } = useConversationFlow({ + conversationItems, + refreshSidebar, + openConversation, + openConversationView +}); const { notificationsEnabled, @@ -98,9 +106,9 @@ function handleRoomAccessRevoked(room) { const { messages, loading, wsStatus, composerText, pendingAttachment, sending, - messagesEl, fileInputEl, isOwnMessage, - loadMessages, activateRoom, deactivateRoom, disconnectSocket, sendMessage, deleteMessage, handleComposerKeydown, - openFilePicker, uploadAttachment, clearAttachment, loadOlder + messagesEl, isOwnMessage, + loadMessages, activateRoom, deactivateRoom, disconnectSocket, sendMessage, deleteMessage, + uploadAttachment, clearAttachment, loadOlder } = useChatRoom({ activeRoom, session, @@ -117,78 +125,21 @@ const { connectUnreadInbox, disconnectUnreadInbox } = useUnreadInbox({ }); const wsConnected = computed(() => wsStatus.value === 'open'); -const activeRoomSubtitle = computed(() => { - if (!activeRoom.value) return ''; - if (activeRoom.value.kind === 'dm') { - return activeRoom.value.otherUser?.username - ? `@${activeRoom.value.otherUser.username}` - : wsConnected.value ? t('chat.online') : t('chat.connecting'); - } - if (activeRoom.value.memberCount) { - return t('chat.memberCount', { count: activeRoom.value.memberCount }); - } - return activeRoom.value.isGeneral ? t('chat.generalGroup') : t('chat.groupConversation'); -}); +const activeRoomSubtitle = computed(() => roomSubtitle(activeRoom.value, wsConnected.value)); const canModerateMessages = computed( () => Boolean(session.value?.isAdmin || canManageActiveRoom.value) ); -const messageMenu = ref({ message: null, x: 0, y: 0 }); -let longPressTimer = null; -let longPressOrigin = null; - -function closeMessageMenu() { - messageMenu.value = { message: null, x: 0, y: 0 }; -} - -function openMessageMenuAt(message, x, y) { - if (!canModerateMessages.value) return; - messageMenu.value = { message, x, y }; -} - -function cancelMessageLongPress() { - if (longPressTimer !== null) { - window.clearTimeout(longPressTimer); - longPressTimer = null; - } - longPressOrigin = null; -} - -function openMessageContextMenu(event, message) { - if (!canModerateMessages.value) return; - event.preventDefault(); - cancelMessageLongPress(); - openMessageMenuAt(message, event.clientX, event.clientY); -} - -function startMessageLongPress(event, message) { - cancelMessageLongPress(); - if (!canModerateMessages.value || event.pointerType === 'mouse') return; - - const origin = { - pointerId: event.pointerId, - x: event.clientX, - y: event.clientY - }; - longPressOrigin = origin; - longPressTimer = window.setTimeout(() => { - openMessageMenuAt(message, origin.x, origin.y); - longPressTimer = null; - }, 500); -} - -function trackMessageLongPress(event) { - if (!longPressOrigin || event.pointerId !== longPressOrigin.pointerId) return; - if ( - Math.abs(event.clientX - longPressOrigin.x) > 10 || - Math.abs(event.clientY - longPressOrigin.y) > 10 - ) { - cancelMessageLongPress(); - } -} +const { + messageMenu, + closeMessageMenu, + cancelMessageLongPress, + openMessageContextMenu, + startMessageLongPress, + trackMessageLongPress +} = useMessageContextMenu({ canModerateMessages }); const roomManagement = useRoomManagement({ - activeRoom, channels, users, error, refreshSidebar, conversationItems, - openConversation, canManageActiveRoom, + activeRoom, channels, users, error, refreshSidebar, refreshAndOpen, canManageActiveRoom, returnToConversationList, onRoomDeleted: () => { disconnectSocket(); @@ -217,9 +168,7 @@ const { users, dms, error, - refreshSidebar, - conversationItems, - openConversation, + refreshAndOpen, openGroupDialog: openCreateGroup }); const { @@ -247,8 +196,7 @@ const { async function selectConversation(item) { try { - await openConversation(item); - openConversationView(); + await openConversationItem(item); } catch (currentError) { error.value = currentError.message; } @@ -270,11 +218,8 @@ async function confirmPublicGroupJoin() { error.value = ''; try { await joinPublicChannel(channel); - const item = conversationItems.value.find( - (conversation) => conversation.kind === channel.kind && Number(conversation.id) === Number(channel.id) - ); publicGroupPreview.value = null; - if (item) await selectConversation(item); + await openByIdentity(channel); } catch (currentError) { error.value = currentError.message; } finally { @@ -282,11 +227,12 @@ async function confirmPublicGroupJoin() { } } -function openRoomFromNotification(room) { - const item = conversationItems.value.find( - (conversation) => conversation.kind === room.kind && Number(conversation.id) === Number(room.id) - ); - if (item) void selectConversation(item); +async function openRoomFromNotification(room) { + try { + await openByIdentity(room); + } catch (currentError) { + error.value = currentError.message; + } } function toggleActiveRoomMute() { @@ -470,38 +416,13 @@ onBeforeUnmount(() => { - + @@ -624,46 +545,16 @@ onBeforeUnmount(() => { @delete="confirmDeleteMessage" /> -
-
- -
-
{{ error }}
-
- - - - -
-
+
@@ -835,10 +726,7 @@ onBeforeUnmount(() => { } .header-action:active, -.sidebar-item:active, -.chat-header__button:active, -.composer-btn:active:not(:disabled), -.composer-send:active:not(:disabled) { +.chat-header__button:active { background: rgba(0, 0, 0, 0.08); } @@ -846,127 +734,12 @@ onBeforeUnmount(() => { flex-shrink: 0; } -.sidebar-list { - flex: 1; - min-height: 0; - overflow-y: auto; - overflow-x: hidden; - padding: 0; - touch-action: pan-y; -} - -.sidebar-list::-webkit-scrollbar { width: 4px; } -.sidebar-list::-webkit-scrollbar-thumb { background: rgba(0, 0, 0, 0.15); border-radius: 2px; } - .sidebar-divider { flex-shrink: 0; height: 1px; background: #f0f2f5; } -.sidebar-hint { - display: flex; - align-items: center; - justify-content: center; - padding: 24px 8px; - font-size: 13px; - color: #8696a0; -} - -.sidebar-item svg { - flex-shrink: 0; -} - -.sidebar-label-group { - flex: 1; - min-width: 0; -} - -/* biome-ignore lint/correctness/noUnknownPseudoClass: Vue deep selector */ -.sidebar-item :deep(.ui-avatar) { - flex-shrink: 0; -} - -.sidebar-item { - display: flex; - align-items: center; - gap: 12px; - width: calc(100% - 16px); - margin: 4px 8px; - padding: 12px 16px; - border: none; - border-radius: 12px; - background: transparent; - cursor: pointer; - text-align: left; - transition: background 150ms; - touch-action: manipulation; -} - -.sidebar-item:hover { - background: #f5f6f6; -} - -.sidebar-item--active { - background: #f0f2f5; -} - -.sidebar-item__top { - display: flex; - justify-content: space-between; - align-items: center; - gap: 8px; -} - -.sidebar-item__top strong { - font-size: 15px; - font-weight: 500; - color: #111b21; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -.sidebar-item__time { - font-size: 12px; - color: #667781; - flex-shrink: 0; -} - -.sidebar-item__preview { - margin: 0; - font-size: 13px; - color: #667781; - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; -} - -.sidebar-item__bottom { - display: flex; - align-items: center; - gap: 8px; - margin-top: 4px; - min-width: 0; -} - -.sidebar-unread-badge { - display: inline-flex; - align-items: center; - justify-content: center; - flex-shrink: 0; - min-width: 20px; - height: 20px; - padding: 0 6px; - border-radius: 999px; - background: #25d366; - color: #ffffff; - font-size: 11px; - font-weight: 700; - line-height: 1; - font-variant-numeric: tabular-nums; -} - .right-sidebar { flex-shrink: 0; width: 68px; @@ -1018,14 +791,6 @@ onBeforeUnmount(() => { touch-action: manipulation; } -.sidebar-muted-indicator { - display: inline-flex; - flex: 0 0 auto; - align-items: center; - justify-content: center; - color: #8696a0; -} - .right-sidebar-action:hover, .right-sidebar-user:hover { background: rgba(0, 0, 0, 0.05); @@ -1341,123 +1106,6 @@ onBeforeUnmount(() => { height: 0; } -.chat-composer { - margin-top: auto; - margin-bottom: 0; - padding: 10px 16px; - background: #f0f2f5; - border-top: 1px solid #e9edef; - position: relative; - z-index: 2; - margin-left: 0; - margin-right: 0; - border-radius: 0; -} - -.composer-attachment { - min-width: 0; - margin-bottom: 10px; -} - -.composer-error { - margin-bottom: 8px; - font-size: 12px; - color: #dc2626; - text-align: center; -} - -.composer-row { - display: flex; - align-items: center; - gap: 12px; - min-width: 0; -} - -.composer-file-input { - display: none; -} - -.composer-btn { - display: flex; - align-items: center; - justify-content: center; - width: 40px; - height: 40px; - border: none; - border-radius: 50%; - background: transparent; - color: #54656f; - cursor: pointer; - flex-shrink: 0; - transition: background 150ms, color 150ms; - touch-action: manipulation; -} - -.composer-btn:hover:not(:disabled) { - background: rgba(0, 0, 0, 0.05); - color: #111b21; -} - -.composer-btn:disabled { - opacity: 0.4; - cursor: not-allowed; -} - -.composer-input { - flex: 1; - min-width: 0; -} - -/* biome-ignore lint/correctness/noUnknownPseudoClass: Vue deep selector */ -:deep(.composer-input.ui-textarea) { - width: 100%; - min-width: 0; - border: none; - background: #ffffff; - box-shadow: none; - min-height: 40px; - border-radius: 8px; - padding: 10px 16px; - color: #111b21; - font-size: 15px; - resize: none; -} - -/* biome-ignore lint/correctness/noUnknownPseudoClass: Vue deep selector */ -:deep(.composer-input.ui-textarea:focus) { - border-color: transparent; - box-shadow: none; -} - -/* biome-ignore lint/correctness/noUnknownPseudoClass: Vue deep selector */ -:deep(.composer-input.ui-textarea::placeholder) { - color: #8696a0; -} - -.composer-send { - display: flex; - align-items: center; - justify-content: center; - width: 40px; - height: 40px; - border: none; - border-radius: 50%; - background: transparent; - cursor: pointer; - flex-shrink: 0; - transition: background 150ms; - touch-action: manipulation; -} - -.composer-send:hover:not(:disabled) { - background: rgba(0, 0, 0, 0.05); -} - -.composer-send:disabled { - opacity: 0.3; - cursor: not-allowed; -} - .chat-empty { position: relative; flex: 1; @@ -1577,23 +1225,6 @@ onBeforeUnmount(() => { display: inline-grid; } - .sidebar-list { - padding-bottom: max(8px, env(safe-area-inset-bottom)); - overscroll-behavior: contain; - } - - .sidebar-item { - width: 100%; - min-height: 68px; - margin: 0; - padding: 11px max(16px, env(safe-area-inset-right)) 11px max(16px, env(safe-area-inset-left)); - border-radius: 0; - } - - .sidebar-item + .sidebar-item { - border-top: 1px solid #f0f2f5; - } - .chat-header { min-height: 64px; gap: 8px; @@ -1676,31 +1307,6 @@ onBeforeUnmount(() => { max-width: 88%; } - .chat-composer { - padding: - 8px - max(8px, env(safe-area-inset-right)) - max(8px, env(safe-area-inset-bottom)) - max(8px, env(safe-area-inset-left)); - } - - .composer-row { - gap: 4px; - } - - .composer-btn, - .composer-send { - width: 44px; - height: 44px; - } - - /* biome-ignore lint/correctness/noUnknownPseudoClass: Vue deep selector */ - :deep(.composer-input.ui-textarea) { - min-height: 44px; - padding: 11px 12px; - font-size: 16px; - } - .room-management-layer { position: fixed; inset: 0; @@ -1739,10 +1345,7 @@ onBeforeUnmount(() => { @media (prefers-reduced-motion: reduce) { .header-action, - .sidebar-item, - .chat-header__button, - .composer-btn, - .composer-send { + .chat-header__button { transition: none; } } diff --git a/test/chat-page-composables.test.js b/test/chat-page-composables.test.js new file mode 100644 index 00000000..13109b83 --- /dev/null +++ b/test/chat-page-composables.test.js @@ -0,0 +1,128 @@ +import assert from "node:assert/strict"; +import { fileURLToPath } from "node:url"; +import test, { after, before } from "node:test"; +import { ref } from "vue"; +import { createServer } from "vite"; + +const projectRoot = fileURLToPath(new URL("..", import.meta.url)); +let vite; +let useConversationFlow; +let useMessageContextMenu; + +before(async () => { + vite = await createServer({ + root: projectRoot, + configFile: false, + appType: "custom", + logLevel: "silent", + server: { middlewareMode: true }, + }); + ({ useConversationFlow } = await vite.ssrLoadModule( + "/frontend/src/composables/useConversationFlow.ts", + )); + ({ useMessageContextMenu } = await vite.ssrLoadModule( + "/frontend/src/composables/useMessageContextMenu.ts", + )); +}); + +after(async () => { + await vite?.close(); +}); + +test("会话流程统一按 kind 和 id 查找并在打开后切换聊天视图", async () => { + const calls = []; + const conversationItems = ref([ + { id: 7, kind: "private", source: { id: 7 } }, + ]); + const flow = useConversationFlow({ + conversationItems, + async refreshSidebar() { + calls.push(["refreshSidebar"]); + conversationItems.value = [{ id: 9, kind: "dm", source: { id: 9 } }]; + }, + async openConversation(item) { + calls.push(["openConversation", item]); + }, + openConversationView() { + calls.push(["openConversationView"]); + }, + }); + + assert.equal(await flow.openByIdentity({ kind: "private", id: "7" }), true); + assert.equal(await flow.openByIdentity({ kind: "private", id: 8 }), false); + assert.equal(await flow.refreshAndOpen({ kind: "dm", id: 9 }), true); + assert.deepEqual(calls, [ + ["openConversation", { id: 7, kind: "private", source: { id: 7 } }], + ["openConversationView"], + ["refreshSidebar"], + ["openConversation", { id: 9, kind: "dm", source: { id: 9 } }], + ["openConversationView"], + ]); +}); + +test("消息菜单只允许有管理权限的右键和触摸长按打开", () => { + const canModerateMessages = ref(true); + const menu = useMessageContextMenu({ canModerateMessages }); + let prevented = false; + menu.openMessageContextMenu( + { + clientX: 12, + clientY: 18, + preventDefault() { + prevented = true; + }, + }, + { id: 1 }, + ); + assert.equal(prevented, true); + assert.deepEqual(menu.messageMenu.value, { + message: { id: 1 }, + x: 12, + y: 18, + }); + + menu.closeMessageMenu(); + canModerateMessages.value = false; + menu.openMessageContextMenu( + { clientX: 30, clientY: 40, preventDefault() {} }, + { id: 2 }, + ); + assert.equal(menu.messageMenu.value.message, null); + + canModerateMessages.value = true; + const nativeSetTimeout = globalThis.setTimeout; + const nativeClearTimeout = globalThis.clearTimeout; + let scheduledCallback; + let clearedTimer = null; + globalThis.setTimeout = (callback) => { + scheduledCallback = callback; + return 41; + }; + globalThis.clearTimeout = (timer) => { + clearedTimer = timer; + }; + try { + menu.startMessageLongPress( + { pointerType: "touch", pointerId: 3, clientX: 20, clientY: 24 }, + { id: 3 }, + ); + scheduledCallback(); + assert.deepEqual(menu.messageMenu.value, { + message: { id: 3 }, + x: 20, + y: 24, + }); + + menu.closeMessageMenu(); + menu.startMessageLongPress( + { pointerType: "touch", pointerId: 4, clientX: 10, clientY: 10 }, + { id: 4 }, + ); + menu.trackMessageLongPress({ pointerId: 4, clientX: 21, clientY: 10 }); + assert.equal(clearedTimer, 41); + assert.equal(menu.messageMenu.value.message, null); + } finally { + globalThis.setTimeout = nativeSetTimeout; + globalThis.clearTimeout = nativeClearTimeout; + } +}); diff --git a/test/chat-ui-scale.test.js b/test/chat-ui-scale.test.js index ddd301cb..84ab25f3 100644 --- a/test/chat-ui-scale.test.js +++ b/test/chat-ui-scale.test.js @@ -15,6 +15,14 @@ const mobileDrawer = readFileSync( new URL("../frontend/src/components/chat/MobileNavigationDrawer.vue", import.meta.url), "utf8", ).replaceAll("\r\n", "\n"); +const conversationList = readFileSync( + new URL("../frontend/src/components/chat/ConversationList.vue", import.meta.url), + "utf8", +).replaceAll("\r\n", "\n"); +const messageComposer = readFileSync( + new URL("../frontend/src/components/chat/MessageComposer.vue", import.meta.url), + "utf8", +).replaceAll("\r\n", "\n"); function getStyleRule(source, selector) { const marker = `${selector} {`; @@ -40,15 +48,15 @@ test("聊天界面使用原始控件尺寸铺满整个视口", () => { }); test("移动端附件预览不会挤出发送按钮", () => { - assert.match(chatPage, /\.composer-attachment\s*{[^}]*min-width:\s*0;/s); - assert.match(chatPage, /\.composer-row\s*{[^}]*min-width:\s*0;/s); - assert.match(chatPage, /\.composer-send\s*{[^}]*flex-shrink:\s*0;/s); + assert.match(messageComposer, /\.composer-attachment\s*{[^}]*min-width:\s*0;/s); + assert.match(messageComposer, /\.composer-row\s*{[^}]*min-width:\s*0;/s); + assert.match(messageComposer, /\.composer-btn,\s*\.composer-send\s*{[^}]*flex-shrink:\s*0;/s); assert.match(attachmentStyles, /\.pending-attachment\s*{[^}]*width:\s*100%;[^}]*min-width:\s*0;/s); assert.match(attachmentStyles, /\.pending-attachment__name\s*{[^}]*min-width:\s*0;[^}]*text-overflow:\s*ellipsis;/s); }); test("移动端前台滚动区允许纵向触摸滑动", () => { - assert.match(chatPage, /\.sidebar-list\s*{[^}]*overflow-y:\s*auto;[^}]*touch-action:\s*pan-y;/s); + assert.match(conversationList, /\.sidebar-list\s*{[^}]*overflow-y:\s*auto;[^}]*touch-action:\s*pan-y;/s); assert.match(chatPage, /\.chat-messages\s*{[^}]*overflow-y:\s*auto;[^}]*touch-action:\s*pan-y;/s); assert.match(mobileDrawer, /\.mobile-navigation-drawer\s*{[^}]*overflow-y:\s*auto;[^}]*touch-action:\s*pan-y;/s); }); @@ -68,8 +76,8 @@ test("移动端主要图标按钮保留四十四像素触控区域", () => { assert.match(chatPage, /\.mobile-menu-action\s*{[^}]*width:\s*44px;[^}]*height:\s*44px;/s); assert.match(chatPage, /\.chat-header__back\s*{[^}]*width:\s*44px;[^}]*height:\s*44px;/s); assert.match(chatPage, /\.chat-header__button\s*{[^}]*width:\s*44px;[^}]*height:\s*44px;/s); - assert.match(chatPage, /\.composer-btn,\s*\.composer-send\s*{\s*width:\s*44px;\s*height:\s*44px;/s); - assert.match(chatPage, /font-size:\s*16px;/); + assert.match(messageComposer, /\.composer-btn,\s*\.composer-send\s*{\s*width:\s*44px;\s*height:\s*44px;/s); + assert.match(messageComposer, /font-size:\s*16px;/); }); test("聊天侧栏跟随全屏根节点且不污染后台根节点", () => { @@ -111,4 +119,12 @@ test("聊天侧栏跟随全屏根节点且不污染后台根节点", () => { assert.match(chatPage, //); assert.match(chatPage, //); assert.match(chatPage, /\.chat-empty__language-switch\s*{[^}]*position:\s*absolute;[^}]*right:\s*16px;/s); - }); + }); + +test("聊天页面通过专用组件编排会话列表和消息输入区", () => { + assert.match(chatPage, / calls.push(["refreshSidebar"]), - openConversation: async (item) => calls.push(["openConversation", item]), + refreshAndOpen: async (identity, fallback) => + calls.push(["refreshAndOpen", identity, fallback]), openGroupDialog: () => calls.push(["openGroupDialog"]), conversationApi, }); - return { creation, users, error, calls, conversationItems }; + return { creation, users, error, calls }; } test("添加人员入口同时保留新私聊和创建群聊动作", () => { @@ -64,8 +62,19 @@ test("发起新私聊后刷新侧栏并自动打开对应会话", async () => { assert.deepEqual(calls, [ ["openDm", 1], - ["refreshSidebar"], - ["openConversation", { id: 21, kind: "dm", source: { id: 21, kind: "dm" } }], + [ + "refreshAndOpen", + { kind: "dm", id: 21 }, + { + kind: "dm", + id: 21, + source: { + id: 21, + kind: "dm", + otherUser: users.value[0], + }, + }, + ], ]); assert.equal(creation.show.value, false); assert.equal(creation.openingDmUserId.value, null); diff --git a/test/room-management.test.js b/test/room-management.test.js index 7622652e..4087fb43 100644 --- a/test/room-management.test.js +++ b/test/room-management.test.js @@ -54,20 +54,16 @@ function createHarness(overrides = {}) { }, ...overrides.roomApi, }; - const conversationItems = ref([ - { id: 9, kind: "private" }, - { id: 9, kind: "public" }, - ]); const refreshSidebar = async () => calls.push(["refreshSidebar"]); - const openConversation = async (item) => calls.push(["openConversation", item]); + const refreshAndOpen = async (identity) => + calls.push(["refreshAndOpen", identity]); const management = useRoomManagement({ activeRoom, channels, users, error, refreshSidebar, - conversationItems, - openConversation, + refreshAndOpen, canManageActiveRoom: computed(() => Boolean(activeRoom.value?.canManage)), onRoomDeleted: () => calls.push(["onRoomDeleted"]), returnToConversationList: () => calls.push(["returnToConversationList"]), @@ -89,8 +85,7 @@ test("创建群组状态和导航由 room management module 统一拥有", async assert.deepEqual(calls, [ ["createGroup", { name: "New team", kind: "private", memberUserIds: [2] }], - ["refreshSidebar"], - ["openConversation", { id: 9, kind: "private" }], + ["refreshAndOpen", { id: 9, kind: "private" }], ]); assert.equal(management.creation.show.value, false); assert.deepEqual(management.creation.form, { @@ -109,8 +104,7 @@ test("公开群组创建会保留类型并允许不预先邀请成员", async () assert.deepEqual(calls, [ ["createGroup", { name: "公开讨论", kind: "public", memberUserIds: [] }], - ["refreshSidebar"], - ["openConversation", { id: 9, kind: "public" }], + ["refreshAndOpen", { id: 9, kind: "public" }], ]); });