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 00000000..e6441136 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..b82aa23a --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 00000000..1aa94a42 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${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/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/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/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/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/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" }], ]); }); 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) {