diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..e104ae1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +version: 2 +updates: + - package-ecosystem: pub + directory: / + schedule: + interval: weekly + open-pull-requests-limit: 5 + + - package-ecosystem: gradle + directory: /android + schedule: + interval: monthly + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/build_and_release.yml b/.github/workflows/build_and_release.yml index 84dff6b..c1a92c4 100644 --- a/.github/workflows/build_and_release.yml +++ b/.github/workflows/build_and_release.yml @@ -6,7 +6,11 @@ on: - main jobs: + e2e: + uses: ./.github/workflows/flutter-e2e.yml + build: + needs: e2e runs-on: ubuntu-latest permissions: contents: write @@ -30,36 +34,45 @@ jobs: - name: Get dependencies run: flutter pub get - # Creating Firebase configuration files from base64 encoded secret keys - - name: Create Firebase configuration files +# # Creating Firebase configuration files from base64 encoded secret keys +# - name: Create Firebase configuration files +# run: | +# if [ -n "${{ secrets.FIREBASE_JSON_BASE64 }}" ]; then +# echo "${{ secrets.FIREBASE_JSON_BASE64 }}" | base64 -d > firebase.json +# else +# echo "Error: FIREBASE_JSON_BASE64 secret is required" +# exit 1 +# fi +# +# if [ -n "${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }}" ]; then +# echo "${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }}" | base64 -d > lib/firebase_options.dart +# else +# echo "Error: FIREBASE_OPTIONS_DART_BASE64 secret is required" +# exit 1 +# fi +# +# if [ -n "${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }}" ]; then +# echo "${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }}" | base64 -d > android/app/google-services.json +# else +# echo "Error: GOOGLE_SERVICES_JSON_BASE64 secret is required" +# exit 1 +# fi +# +# # if [ -n "${{ secrets.GOOGLE_SERVICE_INFO_PLIST_BASE64 }}" ]; then +# # echo "${{ secrets.GOOGLE_SERVICE_INFO_PLIST_BASE64 }}" | base64 -d > ios/Runner/GoogleService-Info.plist +# #else +# # echo "Error: GOOGLE_SERVICE_INFO_PLIST_BASE64 secret is required" +# # exit 1 +# #fi + + # Fail fast when the version was not bumped for this release + - name: Check version bump run: | - if [ -n "${{ secrets.FIREBASE_JSON_BASE64 }}" ]; then - echo "${{ secrets.FIREBASE_JSON_BASE64 }}" | base64 -d > firebase.json - else - echo "Error: FIREBASE_JSON_BASE64 secret is required" - exit 1 - fi - - if [ -n "${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }}" ]; then - echo "${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }}" | base64 -d > lib/firebase_options.dart - else - echo "Error: FIREBASE_OPTIONS_DART_BASE64 secret is required" - exit 1 - fi - - if [ -n "${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }}" ]; then - echo "${{ secrets.GOOGLE_SERVICES_JSON_BASE64 }}" | base64 -d > android/app/google-services.json - else - echo "Error: GOOGLE_SERVICES_JSON_BASE64 secret is required" + VERSION=$(grep 'version:' pubspec.yaml | sed 's/version: //' | cut -d+ -f1 | tr -d '[:space:]') + if git rev-parse -q --verify "refs/tags/v$VERSION" >/dev/null; then + echo "::error::v$VERSION is already released, bump version in pubspec.yaml" exit 1 fi - - # if [ -n "${{ secrets.GOOGLE_SERVICE_INFO_PLIST_BASE64 }}" ]; then - # echo "${{ secrets.GOOGLE_SERVICE_INFO_PLIST_BASE64 }}" | base64 -d > ios/Runner/GoogleService-Info.plist - #else - # echo "Error: GOOGLE_SERVICE_INFO_PLIST_BASE64 secret is required" - # exit 1 - #fi # Building Android APK - name: Build Android APK @@ -69,13 +82,13 @@ jobs: - name: Get version id: version run: | - VERSION=$(grep 'version:' pubspec.yaml | sed 's/version: //' | tr -d '[:space:]') + VERSION=$(grep 'version:' pubspec.yaml | sed 's/version: //' | cut -d+ -f1 | tr -d '[:space:]') echo "version=$VERSION" >> $GITHUB_OUTPUT # Rename APK file - name: Rename APK run: | - mv build/app/outputs/flutter-apk/app-release.apk build/app/outputs/flutter-apk/whisper_v${{ steps.version.outputs.version }}.apk + mv build/app/outputs/flutter-apk/app-release.apk build/app/outputs/flutter-apk/shept_v${{ steps.version.outputs.version }}.apk # Creating GitHub release - name: Create Release @@ -89,4 +102,4 @@ jobs: draft: false prerelease: false files: | - build/app/outputs/flutter-apk/whisper_v${{ steps.version.outputs.version }}.apk \ No newline at end of file + build/app/outputs/flutter-apk/shept_v${{ steps.version.outputs.version }}.apk \ No newline at end of file diff --git a/.github/workflows/flutter-ci.yml b/.github/workflows/flutter-ci.yml new file mode 100644 index 0000000..500fe51 --- /dev/null +++ b/.github/workflows/flutter-ci.yml @@ -0,0 +1,62 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + ci: + name: Analyze and test + # Fork pull requests cannot read repository secrets, so analysis cannot run. + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + + # Firebase is retired: no generated options file is needed any more. + # - name: Create Firebase options + # env: + # FIREBASE_OPTIONS_DART_BASE64: ${{ secrets.FIREBASE_OPTIONS_DART_BASE64 }} + # run: | + # if [ -z "$FIREBASE_OPTIONS_DART_BASE64" ]; then + # echo "FIREBASE_OPTIONS_DART_BASE64 secret is required for analysis" + # exit 1 + # fi + # echo "$FIREBASE_OPTIONS_DART_BASE64" | base64 -d > lib/firebase_options.dart + + - name: Get dependencies + run: flutter pub get + + - name: Format (changed files) + run: | + BASE="origin/${{ github.base_ref || 'main' }}" + git fetch origin "${{ github.base_ref || 'main' }}" 2>/dev/null || true + FILES=$(git diff --name-only --diff-filter=ACMR "$BASE"...HEAD -- '*.dart' | tr '\n' ' ') + if [ -z "$FILES" ]; then + echo "No changed Dart files." + exit 0 + fi + dart format --output=none --set-exit-if-changed $FILES + + - name: Analyze + # Infos are not fatal: the legacy UI has known lints. Errors and warnings block. + run: flutter analyze --no-fatal-infos + + - name: Test + run: flutter test + + - name: Secret scan + uses: gitleaks/gitleaks-action@v2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/flutter-e2e.yml b/.github/workflows/flutter-e2e.yml new file mode 100644 index 0000000..8633bff --- /dev/null +++ b/.github/workflows/flutter-e2e.yml @@ -0,0 +1,44 @@ +name: Flutter E2E + +on: + schedule: + - cron: '0 2 * * *' + workflow_dispatch: + workflow_call: + +permissions: + contents: read + +jobs: + e2e: + name: Linux desktop integration tests + runs-on: ubuntu-latest + steps: + - name: Checkout app + uses: actions/checkout@v7 + with: + path: shept + + # Both Dart clients come from their release tags (pubspec.yaml), so no + # sibling checkouts are needed. + + - name: Install Linux desktop dependencies + run: | + sudo apt-get update + sudo apt-get install -y clang cmake ninja-build pkg-config xvfb \ + libgtk-3-dev liblzma-dev libsecret-1-dev + + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + + - name: Get dependencies + working-directory: shept + run: | + flutter config --enable-linux-desktop + flutter pub get + + - name: Run E2E + working-directory: shept + run: xvfb-run -a flutter test integration_test -d linux diff --git a/.gitignore b/.gitignore index 74190ac..d002995 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,8 @@ migrate_working_dir/ .dart_tool/ .flutter-plugins .flutter-plugins-dependencies +.flutter_mcp/ +.mcp_screenshots/ .pub-cache/ .pub/ /build/ @@ -46,4 +48,5 @@ app.*.map.json firebase.json lib/firebase_options.dart android/app/google-services.json -ios/Runner/GoogleService-Info.plist \ No newline at end of file +ios/Runner/GoogleService-Info.plist +pubspec_overrides.yaml diff --git a/.metadata b/.metadata index 4f14196..02c33e9 100644 --- a/.metadata +++ b/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled and should not be manually edited. version: - revision: "be698c48a6750c8cb8e61c740ca9991bb947aba2" + revision: "db50e20168db8fee486b9abf32fc912de3bc5b6a" channel: "stable" project_type: app @@ -13,14 +13,11 @@ project_type: app migration: platforms: - platform: root - create_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - base_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - - platform: android - create_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - base_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - - platform: ios - create_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 - base_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 + create_revision: db50e20168db8fee486b9abf32fc912de3bc5b6a + base_revision: db50e20168db8fee486b9abf32fc912de3bc5b6a + - platform: linux + create_revision: db50e20168db8fee486b9abf32fc912de3bc5b6a + base_revision: db50e20168db8fee486b9abf32fc912de3bc5b6a # User provided section diff --git a/.vscode/launch.json b/.vscode/launch.json index dc95bd7..eb80aeb 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -2,18 +2,18 @@ "version": "0.2.0", "configurations": [ { - "name": "whisper", + "name": "shept", "request": "launch", "type": "dart" }, { - "name": "whisper (profile mode)", + "name": "shept (profile mode)", "request": "launch", "type": "dart", "flutterMode": "profile" }, { - "name": "whisper (release mode)", + "name": "shept (release mode)", "request": "launch", "type": "dart", "flutterMode": "release" diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..052e0c7 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,73 @@ +# shept — agent contract + +Flutter 3.47 / Dart 3.13 client for Shept. Talks to `shept-server` over HTTP (generated `shept_openapi_client_dart`) +and WebSocket (`shept_websocket_client_dart`). + +## Commands + +- deps: `flutter pub get` +- analyze: `flutter analyze --no-fatal-infos` (errors and warnings block, infos do not) +- format: `dart format` on the files you touched +- test: `flutter test` +- e2e: `flutter test integration_test -d linux` (needs Linux desktop toolchain) +- build: `flutter build apk --release` (no Firebase files needed; Firebase is retired) + +## AI / MCP tooling + +OpenCode has two Flutter MCP servers wired globally (config in `~/.config/opencode/opencode.json`, +not in this repository). Use them for the fast loop, but the shell gates below still define done. + +| Server | Role | +|---|---| +| `dart` | `analyze_files`, symbol resolution, `run_tests`, `pub`, hot reload/restart, DTD connection, widget inspector | +| `flutter-mcp-toolkit` | screenshots, semantic snapshot, tap/type, recent logs — UI verification of a running debug build | + +1. At session start register roots: `shept`, `../shept_openapi_client_dart`, `../shept_websocket_client_dart`. +2. MCP-driven runs use a fixed port so the toolkit can attach: `flutter run -d linux --device-vmservice-port=8181`. One running instance only. +3. UI work: `fmt_semantic_snapshot` → `ref` → `fmt_tap_widget`/`fmt_enter_text`, then hot reload after every widget change. Pixel capture is unsupported on Linux desktop (needs the app permission bridge), so use `fmt_hot_reload_flutter`, not `fmt_hot_reload_and_capture`. +4. Never call `fmt_evaluate_dart_expression`; it is denied in the OpenCode `permissions` config and there is no server-side flag for it. +5. Toolkit and debug builds only with test data — never with a real account. +6. `pub add`/`pub remove` and any `pubspec.yaml` change need explicit confirmation. `dart_fix` is disabled on purpose: it would rewrite the generated clients. +7. `flutter analyze --no-fatal-infos` from the shell remains the definition-of-done gate; MCP analysis does not replace it. + +## Hard rules + +1. Never commit secrets, keys, `.env*`, `firebase_options.dart`, `google-services.json` or `firebase.json`. +2. Do not edit `shept_openapi_client_dart/lib` or `shept_websocket_client_dart/lib` by hand. Contract changes go through `shept-server` and regeneration (skill `contract-change`). +3. `lib/media_download.dart` is a hand-written extension of the generated client — when the download changes, edit this file, not the generated `downloadMedia`. +4. Crypto: never lower RSA 4096, AES-256-GCM or PBKDF2 parameters. No key may leave the device in plaintext and no seed may be constant. +5. Do not weaken the app lock (password, biometrics), not even "temporarily for debugging". +6. Never disable a test, lint or the analyzer to get CI green. Fix it, or file an issue and escalate. +7. Force-push only to your own feature branch, never to `main`. + +## Where it hurts + +- **Media upload**: `uploadMedia(file, receiverId)` — the argument order comes from the generator, not from logic. Verify call sites after regenerating the client. +- **Pinned clients**: `pubspec.yaml` pulls both Dart clients from their `v0.5.0` tags, so the build records the contract it was made against. `pubspec_overrides.yaml` (gitignored) points at the sibling checkouts for local work; never commit it. +- **Firebase**: retired. Dependencies and the Google Services plugin are commented out, FCM code is kept dead in comments; do not re-enable without a new Firebase project. +- **Login needs a challenge**: `CryptoUtils.generateRsaJwt` requires a `nonce` + fetched from `AuthenticationApi.authChallenge()`; the server spends it on use. + A login without it is refused. +- **Privacy defaults**: notifications may show the decrypted text; the setting + lives in the `settings` box (`CacheUtils.getNotificationPreview`). Plaintext + temp media is swept on startup (`MediaUtils.clearTempFiles`) and must stay + that way — the temp dir may never hold readable media after a restart. +- **Server URL**: `Utils.isAllowedServerUrl` allows HTTP only in debug builds. +- **Delivery ack**: `ChatSender` keeps a message `sending` until the server acks it + (`WsResponseType.ack`), and `Utils.onWsMessageReceived` acks what it stored. Do + not mark a message `sent` on the socket write; that hides lost messages. +- **Message storage**: one Hive key per message (`|`), + so a new message never rewrites a chat. Do not go back to a list per chat. +- **Media is single-delivery**: the server deletes the file on confirm, so a + second device or a reinstall shows `MediaDownloadStatus.expired`. + +## Definition of done + +- New non-trivial logic has a test (`test/`). +- `flutter analyze --no-fatal-infos` reports no errors and no warnings. +- Formatting is clean on the files you touched. +- A contract change ships the regenerated client and the updated call sites in one PR. + +## When unsure + +Stop and ask. Security decisions (keys, encryption, auth) are not up for guessing. diff --git a/README.md b/README.md index 9e242ae..669568c 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,80 @@ -# whisper +# shept Secure private self-hosted end-to-end encryption messaging app. -For Whisper server, see [whisper-server](https://github.com/jsfraz/whisper-server) repository. +For Shept server, see [shept-server](https://github.com/jsfraz/shept-server) repository. -Also see [Wiki](https://github.com/jsfraz/whisper/wiki)! +Also see [Wiki](https://github.com/jsfraz/shept/wiki)! | | | | |---|---|---| |![Screenshot 1](screenshots/1.png)|![Screenshot 2](screenshots/2.png)|![Screenshot 3](screenshots/3.png)| +## Delivery, history and devices + +The server keeps one encrypted copy of each message in a PostgreSQL archive: +that row is the history, the offline buffer and the delta a reconnecting device +fetches. Nothing is pushed on connect — the app sends the highest `seq` it has +stored and receives only what it missed, so a phone that was offline for a week +syncs in one round trip. A resend of the same message is deduplicated by +(sender, receiver, timestamp). + +How long the ciphertext stays is a per-account setting (7, 30, 90 or 365 days); +the shorter setting of the two participants wins, and an hourly sweeper deletes +what expired. Media is deleted from the server when the receiver confirms the +download, so an attachment that was never fetched before its TTL shows as +expired rather than being re-downloadable. + +Every installation registers a device (id, label, platform). Revoking one in +Settings locks it out immediately: it loses its socket, its refresh sessions and +every API call, even though it still holds the account key. A new login warns +the other devices. The app reports its version (`X-Client-Version`) and refuses +to sign in to a server that requires a newer client. + ## Download -You can download the app [here in the releases](https://github.com/jsfraz/whisper/releases). +You can download the app [here in the releases](https://github.com/jsfraz/shept/releases). + +## AI / MCP tooling + +This project is developed with [OpenCode](https://opencode.ai). MCP servers are configured +globally in `~/.config/opencode/opencode.json` — there is no MCP config in this repository. + +| Server | What it gives the agent | +|---|---| +| `dart` (official Dart & Flutter MCP server) | analyzer diagnostics, symbol resolution, tests, `pub`, hot reload/restart, DTD connection to a running app, widget inspector | +| `flutter-mcp-toolkit` | screenshots, semantic snapshot, tap/type, recent logs — UI verification against a running debug build | +| `context7` | library documentation lookup | + +Pins: `dart mcp-server` comes with Dart 3.13.7; `flutter-mcp-toolkit` **v7.0.1** is the +linux-x64 release binary in `~/.local/bin` (sha256 verified against `checksums.txt`); +`mcp_toolkit` is pinned to **7.0.1** in `pubspec.yaml`. Releases 7.0.2 and 7.1.0 ship no +binaries yet, so upgrade the server and the package together. + +```jsonc +"dart": { + "type": "local", + "command": ["dart", "mcp-server", "--enable", "all", "--disable", "create_project,dart_fix"] +}, +"flutter-mcp-toolkit": { + "type": "local", + "command": ["flutter-mcp-toolkit-server", "--resources", "--images", "--save-images", + "--no-dynamics", "--scan-ports", "8181"] +} +``` + +Verify with `opencode mcp list` (both `connected`); restart the session after config changes. +For a runtime session: `flutter run -d linux --device-vmservice-port=8181`, then discover the app +with `fmt_discover_debug_apps` and pass its `targetId`/`uri` to the toolkit tools. + +Known limitations (Linux desktop, verified): +- Pixel capture is app-owned and off: `fmt_get_screenshots` / `fmt_capture_ui_snapshot` / + `fmt_hot_reload_and_capture` return `visual_capture_unsupported` unless the app wires the + optional permission bridge (`initializeFlutterPermissionToolkit`). Semantic snapshot, tap/type, + logs and `fmt_hot_reload_flutter` work regardless. +- `fmt_evaluate_dart_expression` is denied in the OpenCode `permissions` config; the toolkit has + no server flag for it, so the deny rule is the only enforcement. +- The toolkit only runs in debug builds and must never be used with a real account. ## Dependencies @@ -44,12 +106,8 @@ You can download the app [here in the releases](https://github.com/jsfraz/whispe - used for HTTP requests - [json_annotation](https://pub.dev/packages/json_annotation) - used for JSON serialization annotations -- [jwt_decoder](https://pub.dev/packages/jwt_decoder) - - used for JWT token decoding - [local_auth](https://pub.dev/packages/local_auth) - used for biometric authentication -- [mobile_scanner](https://pub.dev/packages/mobile_scanner) - - used for QR code scanning - [page_transition](https://pub.dev/packages/page_transition) - used for custom page transitions - [path_provider](https://pub.dev/packages/path_provider) @@ -66,10 +124,10 @@ You can download the app [here in the releases](https://github.com/jsfraz/whispe - used for launching URLs - [vibration](https://pub.dev/packages/vibration) - used for device vibration feedback -- [whisper_openapi_client_dart](https://github.com/jsfraz/whisper_openapi_client_dart) - - used for API communication with Whisper server -- [whisper_websocket_client_dart](https://github.com/jsfraz/whisper_websocket_client_dart) - - used for real-time WebSocket communication with Whisper server +- [shept_openapi_client_dart](https://github.com/jsfraz/shept_openapi_client_dart) + - used for API communication with Shept server +- [shept_websocket_client_dart](https://github.com/jsfraz/shept_websocket_client_dart) + - used for real-time WebSocket communication with Shept server ### Dev dependencies @@ -92,25 +150,78 @@ You can download the app [here in the releases](https://github.com/jsfraz/whispe - run `dart run flutter_launcher_icons` to generate icons - see configuration file [flutter_launcher_icons.yaml](flutter_launcher_icons.yaml) -## Firebase Messaging +## Firebase Messaging (retired) + +> Firebase has been retired. `firebase_core`/`firebase_messaging` are commented out in +> `pubspec.yaml`, the Google Services Gradle plugin is disabled and the FCM code is kept +> dead in comments. The notes below describe what it took to enable it and are kept for a +> possible revival. - [Firebase](https://firebase.google.com/) - used for push notifications when user is offline - see [Firebase setup for Flutter](https://firebase.google.com/docs/flutter/setup) and [Firebase Cloud Messaging for Flutter](https://firebase.google.com/docs/cloud-messaging/flutter/client) for more details how to implement this - - app specific configuration files [are not included](.gitignore) in the repository, you need to create them yourself if you plan self host Whisper (refer to [whisper-server](https://github.com/jsfraz/whisper-server) repository for more details) + - app specific configuration files [are not included](.gitignore) in the repository, you need to create them yourself if you plan self host Shept (refer to [shept-server](https://github.com/jsfraz/shept-server) repository for more details) + +### Development + +To setup Firebase using Flutterfire you can run: + +```bash +flutterfire configure +``` + +Or run this for the development environment: + +```bash +flutterfire configure \ + --android-package-name cz.josefraz.shept.debug \ + --ios-bundle-id cz.josefraz.shept.debug +``` + +Then select your Firebase project. This will generate the necessary `firebase.json` and `lib/firebase_options.dart` files. + +## Continuous Integration and Deployment (CI/CD) + +Two GitHub Actions workflows run in this repository: + +- `flutter-ci.yml` — on pull requests and on pushes to `main`: format check on changed files, `flutter analyze`, `flutter test`, secret scan. +- `build_and_release.yml` — on pushes to `main`: builds the release APK and publishes a GitHub Release tagged `v`, where the version comes from `pubspec.yaml`. + +Required repository secrets (Settings > Secrets and variables > Actions): + +| Secret | Used by | Description | +| --- | --- | --- | +| `FIREBASE_OPTIONS_DART_BASE64` | unused | Retired with Firebase. | +| `FIREBASE_JSON_BASE64` | unused | Retired with Firebase. | +| `GOOGLE_SERVICES_JSON_BASE64` | unused | Retired with Firebase. | +| `GOOGLE_SERVICE_INFO_PLIST_BASE64` | unused | Retired with Firebase. | +| `GITHUB_TOKEN` | both | Provided automatically by GitHub. Used by the secret scan. | + +### Release signing + +Release builds are signed with the debug key unless `android/key.properties` +exists (copy `android/key.properties.example`). A keystore is never committed: + +```bash +keytool -genkeypair -v -keystore shept-release.jks -keyalg RSA -keysize 4096 \ + -validity 10000 -alias shept +cp android/key.properties.example android/key.properties # then fill it in +``` + +CI has no keystore, so the APK it publishes is debug-signed; add the keystore as +a secret and decode it in the workflow before shipping real releases. The +release workflow fails when the `v` tag for the current +`pubspec.yaml` version already exists, which is the reminder to bump `version` +(and the build number after `+`) before every release. -## Continuous Integration a Deployment (CI/CD) +iOS push notifications need the *Push Notifications* capability on the +`cz.josefraz.shept` App ID; `ios/Runner/Runner.entitlements` is already wired +into the project. -The application uses GitHub Actions to automatically build and release the APK file when pushing to the `main` branch. For this process to work correctly, the following secret keys must be set in the repository settings (Settings > Secrets and variables > Actions): +Pull requests from forks cannot read repository secrets, so CI is skipped for them. -- `FIREBASE_JSON_BASE64` - base64 encoded contents of the `firebase.json` file -- `FIREBASE_OPTIONS_DART_BASE64` - base64 encoded contents of the `lib/firebase_options.dart` file (required) -- `GOOGLE_SERVICES_JSON_BASE64` - base64 encoded contents of the `android/app/google-services.json` file - +These files are not included in the repository for security reasons. The base64 encoding ensures safe transmission and prevents issues with special characters. -These secret keys will be used during application build to generate the necessary Firebase configuration files, which are not included in the repository for security reasons. The base64 encoding ensures safe transmission and prevents issues with special characters. ### Procedure for setting up CI/CD diff --git a/analysis_options.yaml b/analysis_options.yaml index 0d29021..b0dab33 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -7,6 +7,14 @@ # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. +analyzer: + exclude: + - build/** + - android/** + - ios/** + - linux/** + # Generated by build_runner. + - "**/*.g.dart" include: package:flutter_lints/flutter.yaml linter: diff --git a/android/.gitignore b/android/.gitignore index be3943c..73b6f93 100644 --- a/android/.gitignore +++ b/android/.gitignore @@ -1,5 +1,6 @@ gradle-wrapper.jar /.gradle +/build/ /captures/ /gradlew /gradlew.bat diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index a5ea66e..5666403 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -1,33 +1,43 @@ +import java.io.FileInputStream +import java.util.Properties + plugins { id("com.android.application") // START: FlutterFire Configuration - id("com.google.gms.google-services") + // Firebase retired: id("com.google.gms.google-services") // END: FlutterFire Configuration id("kotlin-android") // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. id("dev.flutter.flutter-gradle-plugin") } +// Release signing: create android/key.properties (gitignored) with storeFile, +// storePassword, keyAlias and keyPassword. Without it the release build falls +// back to the debug keystore so `flutter run --release` keeps working locally. +val keystoreProperties = Properties() +val keystorePropertiesFile = rootProject.file("key.properties") +val hasReleaseKeystore = keystorePropertiesFile.exists() +if (hasReleaseKeystore) { + keystoreProperties.load(FileInputStream(keystorePropertiesFile)) +} + android { - namespace = "cz.josefraz.whisper" - compileSdk = flutter.compileSdkVersion + namespace = "cz.josefraz.shept" + // flutter_local_notifications 23 requires compiling against API 37. + compileSdk = 37 ndkVersion = flutter.ndkVersion // ndkVersion = "27.0.12077973" compileOptions { // Flag to enable support for the new language APIs isCoreLibraryDesugaringEnabled = true - // Sets Java compatibility to Java 8 - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - } - - kotlinOptions { - jvmTarget = JavaVersion.VERSION_1_8.toString() + // Sets Java compatibility to Java 11 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 } defaultConfig { - applicationId = "cz.josefraz.whisper" + applicationId = "cz.josefraz.shept" // You can update the following values to match your application needs. // For more information, see: https://flutter.dev/to/review-gradle-config. minSdk = flutter.minSdkVersion @@ -36,15 +46,42 @@ android { versionName = flutter.versionName } + signingConfigs { + if (hasReleaseKeystore) { + create("release") { + keyAlias = keystoreProperties["keyAlias"] as String + keyPassword = keystoreProperties["keyPassword"] as String + storeFile = file(keystoreProperties["storeFile"] as String) + storePassword = keystoreProperties["storePassword"] as String + } + } + } + buildTypes { + debug { + // Different applicationId for debug version + applicationIdSuffix = ".debug" + // Add suffix + resValue("string", "app_name", "Shept Debug") + } release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig = signingConfigs.getByName("debug") + signingConfig = if (hasReleaseKeystore) { + signingConfigs.getByName("release") + } else { + logger.warn("key.properties not found, the release APK is signed with the debug key") + signingConfigs.getByName("debug") + } + resValue("string", "app_name", "Shept") } } } +kotlin { + compilerOptions { + jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_11) + } +} + dependencies { coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5") } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index f0cbe8b..0dc541c 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,16 +1,44 @@ + + + + + + + + + + + + + + + + + + + - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -64,10 +118,13 @@ - - + - - + + + + + + \ No newline at end of file diff --git a/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt b/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt deleted file mode 100644 index 585fe9a..0000000 --- a/android/app/src/main/kotlin/com/example/whisper/MainActivity.kt +++ /dev/null @@ -1,5 +0,0 @@ -package cz.josefraz.whisper - -import io.flutter.embedding.android.FlutterFragmentActivity - -class MainActivity : FlutterFragmentActivity() diff --git a/android/app/src/main/kotlin/cz/josefraz/shept/MainActivity.kt b/android/app/src/main/kotlin/cz/josefraz/shept/MainActivity.kt new file mode 100644 index 0000000..bf77f84 --- /dev/null +++ b/android/app/src/main/kotlin/cz/josefraz/shept/MainActivity.kt @@ -0,0 +1,76 @@ +package cz.josefraz.shept + +import android.database.ContentObserver +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.provider.MediaStore +import android.view.WindowManager +import io.flutter.embedding.android.FlutterFragmentActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel + +/** + * Hosts the app and the one piece of it that has to live in the platform: + * blocking screenshots of a view-once attachment and noticing ones taken of + * ordinary messages. Android is the only target with an enforceable block. + */ +class MainActivity : FlutterFragmentActivity() { + private var channel: MethodChannel? = null + + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + val methodChannel = + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "shept/secure_screen") + channel = methodChannel + methodChannel.setMethodCallHandler { call, result -> + when (call.method) { + "enableSecure" -> { + window.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + result.success(true) + } + "disableSecure" -> { + window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) + result.success(true) + } + else -> result.notImplemented() + } + } + watchScreenshots() + } + + /** The media store gains a row in Pictures/Screenshots when one is taken. */ + private fun watchScreenshots() { + val observer = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean, uri: Uri?) { + super.onChange(selfChange, uri) + if (uri != null && isScreenshot(uri)) { + channel?.invokeMethod("onScreenshot", null) + } + } + } + contentResolver.registerContentObserver( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + true, + observer, + ) + } + + private fun isScreenshot(uri: Uri): Boolean { + return try { + contentResolver.query( + uri, + arrayOf(MediaStore.Images.Media.RELATIVE_PATH), + null, + null, + null, + )?.use { cursor -> + cursor.moveToFirst() && + (cursor.getString(0) ?: "").contains("Screenshot", ignoreCase = true) + } ?: false + } catch (_: Exception) { + // A provider that does not answer is not worth crashing over. + false + } + } +} diff --git a/android/app/src/main/res/drawable-hdpi/ic_stat_shept.png b/android/app/src/main/res/drawable-hdpi/ic_stat_shept.png new file mode 100644 index 0000000..f924b62 Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_stat_shept.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_stat_shept.png b/android/app/src/main/res/drawable-mdpi/ic_stat_shept.png new file mode 100644 index 0000000..5575b53 Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_stat_shept.png differ diff --git a/android/app/src/main/res/drawable-xhdpi/ic_stat_shept.png b/android/app/src/main/res/drawable-xhdpi/ic_stat_shept.png new file mode 100644 index 0000000..13163be Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_stat_shept.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_stat_shept.png b/android/app/src/main/res/drawable-xxhdpi/ic_stat_shept.png new file mode 100644 index 0000000..01d8d92 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_stat_shept.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_stat_shept.png b/android/app/src/main/res/drawable-xxxhdpi/ic_stat_shept.png new file mode 100644 index 0000000..754eea6 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_stat_shept.png differ 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 0000000..f1ffb0e --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + Shept + \ No newline at end of file diff --git a/android/gradle.properties b/android/gradle.properties index f018a61..814264e 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -1,3 +1,8 @@ +org.gradle.java.home=/usr/lib/jvm/java-21-openjdk org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true -android.enableJetifier=true +# This builtInKotlin flag was added automatically by Flutter migrator +android.builtInKotlin=false +# This newDsl flag was added automatically by Flutter migrator +android.newDsl=false +android.defaults.buildfeatures.resvalues=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index ac3b479..1e395d3 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip diff --git a/android/key.properties.example b/android/key.properties.example new file mode 100644 index 0000000..a5cc517 --- /dev/null +++ b/android/key.properties.example @@ -0,0 +1,12 @@ +# Copy to key.properties and fill in before building a release APK. +# key.properties is gitignored; never commit the keystore or these values. +# +# Generate a keystore once: +# keytool -genkeypair -v -keystore shept-release.jks -keyalg RSA \ +# -keysize 4096 -validity 10000 -alias shept +# +# storeFile is relative to android/. +storeFile=../shept-release.jks +storePassword=CHANGE_ME +keyAlias=shept +keyPassword=CHANGE_ME diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts index bd7522f..efdf2ab 100644 --- a/android/settings.gradle.kts +++ b/android/settings.gradle.kts @@ -18,11 +18,11 @@ pluginManagement { plugins { id("dev.flutter.flutter-plugin-loader") version "1.0.0" - id("com.android.application") version "8.7.3" apply false + id("com.android.application") version "9.5.1" apply false // START: FlutterFire Configuration - id("com.google.gms.google-services") version("4.3.15") apply false + // Firebase retired: id("com.google.gms.google-services") version("4.6.0") apply false // END: FlutterFire Configuration - id("org.jetbrains.kotlin.android") version "2.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.21" apply false } include(":app") diff --git a/assets/images/chat_bg.png b/assets/images/chat_bg.png new file mode 100644 index 0000000..f464551 Binary files /dev/null and b/assets/images/chat_bg.png differ diff --git a/assets/images/chat_bg.svg b/assets/images/chat_bg.svg new file mode 100644 index 0000000..7823a2c --- /dev/null +++ b/assets/images/chat_bg.svg @@ -0,0 +1,138 @@ + + + + diff --git a/assets/translations/cs.json b/assets/translations/cs.json index bd9a14b..5a22c96 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -1,88 +1,333 @@ { - "xMessagesFromYChats": "%d nových zpráv z %d chatů", - "urlError": "Chyba při otevířání URL %s", - "passwordPlsWait": "Ověřování hesla, čekejte prosím...", - "useBiometrics": "Použít otisk prstu", - "biometricAuthReason": "Prosím, ověřte svou identitu otiskem prstu", - "biometricAuthPrompt": "Přiložte prst k senzoru", - "biometricSetupReason": "Nastavení ověřování otiskem prstu", - "biometricSetupAuth": "Přiložte prst k senzoru pro aktivaci", - "biometricAuthFailed": "Ověření otiskem prstu selhalo", - "biometricSetupFailed": "Nastavení otisku prstu selhalo", - "enableBiometrics": "Povolit přihlašování otiskem prstu", - "biometricsEnabled": "Přihlašování otiskem prstu povoleno", - "biometricsDisabled": "Přihlašování otiskem prstu vypnuto", - "yesText": "Ano", - "noText": "Ne", - "okText": "Budiž", - "msgPage": "Zprávy", - "settingsButton": "Nastavení", - "addChat": "Nový chat", - "newInvite": "Nová pozvánka", - "adminPage": "Správa", - "serverUsersPage": "Uživatelé serveru", - "serverInvitesPage": "Pozvánky na server", - "deleteUserConfirm": "Potvrdit smazání uživatele", - "deleteUserConfirmText": "Opravdu chcete smazat tohoto uživatele? Tato akce je nevratná.", - "deleteUser": "Smazat uživatele", - "chatInfoPage": "Informace o chatu", - "deleteChatConfirm": "Potvrdit smazání chatu", - "deleteChatConfirmText": "Opravdu chcete smazat tento chat?", - "deleteChat": "Smazat chat", - "legendaryChat": "Toto je začátek vaší legendární konverzace. Nebo něco na ten způsob, těžko říct.", - "infoButton": "Informace o chatu", - "yourMessage": "Vaše úžasná zpráva...", - "invalidPassword": "Neplatné heslo", - "invalidLocalPassword": "Neplatné heslo", - "localPasswordPlaceholder": "Vaše tajné heslo", - "localPasswordButton": "Přihlásit", - "invalidUsername": "Neplatné uživatelské jméno", - "waitPls": "Vyčkejte...", - "usernamePlaceholder": "Vaše magické uživatelské jméno", - "inviteExpired": "Pozvánka vypršela", - "inviteValidFor": "Platnost pozvánky", - "registerButton": "Zaregistrovat", - "scanQrButton": "Naskenovat QR kód", - "invalidQr": "Neplatný QR kód", - "scanQr": "Naskenujte QR kód pozvánky", - "searchUserPage": "Hledat uživatele", - "enterUsername": "Uživatelské jméno vaší oběti", - "settingsPage": "Nastavení", - "themeSettings": "Motiv", - "notificationSettings": "Oznámení", - "biometrySettings": "Ověření otiskem prstu", - "wikiLink": "Wiki", - "repoLink": "Zdrojový kód", - "dangerZone": "Nebezpečná zóna", - "deleteAllChatsConfirm": "Potvrdit smazání všech chatů", - "deleteAllChatsConfirmText": "Opravdu chcete smazat všechny své chaty?", - "deleteAllChats": "Smazat všechny chaty", - "logoutConfirm": "Potvrdit odhlášení", - "logoutConfirmText": "Opravdu se chcete odhlásit? Všechna vaše data budou smazána a váš účet bude odstraněn i ze serveru.", - "logout": "Odhlásit se", - "accountDeleted1": "Byli jste odhlášeni a váš účet byl smazán", - "logoutAndDelete": "Odhlásit se a smazat účet", - "invalidMail": "Neplatný e-mail", - "userMail": "E-mail uživatele", - "themeMode": "Režim motivu", - "systemText": "Systémový", - "lightText": "Světlý", - "darkText": "Tmavý", - "themeColor": "Barva motivu", - "chooseColor": "Vybrat barvu", - "useMat3": "Material Design 3", - "pickColor": "Vyberte barvu", - "newMessagesTitle": "Nové zprávy", - "newMessagesBody": "Máte nové zprávy v chatu", - "notificationChannelDesc": "Oznámení pro nové zprávy v chatu", - "tickerLocalNotifications": "Nové zprávy v chatu", - "whisperLocalNotificationSingleMessage": "Máte novou zprávu v chatu", - "offlineTrue": "Jste offline :(", - "offlineFalse": "Jste zpět online :)", - "decryptionFailed": "Dešifrování selhalo", - "yesterdayText": "Včera", - "todayText": "Dnes", - "meText": "Já", - "accountDeleted2": "Váš účet byl smazán :P", - "wsOffline": "WebSocket je offline" -} \ No newline at end of file + "xMessagesFromYChats": "%d nových zpráv z %d chatů", + "urlError": "Chyba při otevířání URL %s", + "passwordPlsWait": "Ověřování hesla, čekejte prosím...", + "useBiometrics": "Použít otisk prstu", + "biometricAuthReason": "Prosím, ověřte svou identitu otiskem prstu", + "biometricAuthPrompt": "Přiložte prst k senzoru", + "biometricSetupReason": "Nastavení ověřování otiskem prstu", + "biometricSetupAuth": "Přiložte prst k senzoru pro aktivaci", + "biometricAuthFailed": "Ověření otiskem prstu selhalo", + "biometricSetupFailed": "Nastavení otisku prstu selhalo", + "enableBiometrics": "Povolit přihlašování otiskem prstu", + "biometricsEnabled": "Přihlašování otiskem prstu povoleno", + "biometricsDisabled": "Přihlašování otiskem prstu vypnuto", + "yesText": "Ano", + "noText": "Ne", + "okText": "Budiž", + "msgPage": "Zprávy", + "settingsButton": "Nastavení", + "addChat": "Nový chat", + "newInvite": "Nová pozvánka", + "adminPage": "Správa", + "serverUsersPage": "Uživatelé serveru", + "serverInvitesPage": "Pozvánky na server", + "deleteUserConfirm": "Potvrdit smazání uživatele", + "deleteUserConfirmText": "Opravdu chcete smazat tohoto uživatele? Tato akce je nevratná.", + "deleteUser": "Smazat uživatele", + "adminBadge": "ADMIN", + "noUsers": "Žádní uživatelé", + "noInvites": "Žádné pozvánky", + "loadError": "Nepodařilo se načíst data", + "userDeleted": "Uživatel smazán", + "deleteUserConfirmTextName": "Opravdu chcete smazat uživatele %s? Tato akce je nevratná.", + "inviteExpiresIn": "vyprší za %s %s", + "chatInfoPage": "Informace o chatu", + "deleteChatConfirm": "Potvrdit smazání chatu", + "deleteChatConfirmText": "Opravdu chcete smazat tento chat?", + "deleteChat": "Smazat chat", + "legendaryChat": "Toto je začátek vaší legendární konverzace. Nebo něco na ten způsob, těžko říct.", + "infoButton": "Informace o chatu", + "yourMessage": "Vaše úžasná zpráva...", + "invalidPassword": "Neplatné heslo", + "invalidLocalPassword": "Neplatné heslo", + "localPasswordPlaceholder": "Vaše tajné heslo", + "localPasswordButton": "Přihlásit", + "invalidUsername": "Neplatné uživatelské jméno", + "waitPls": "Vyčkejte...", + "usernamePlaceholder": "Vaše magické uživatelské jméno", + "inviteExpired": "Pozvánka vypršela", + "inviteValidFor": "Platnost pozvánky", + "registerButton": "Zaregistrovat", + "scanQrButton": "Naskenovat QR kód", + "invalidQr": "Neplatný QR kód", + "scanQr": "Naskenujte QR kód pozvánky", + "searchUserPage": "Hledat uživatele", + "enterUsername": "Uživatelské jméno vaší oběti", + "clearSearch": "Vymazat hledání", + "noUsersFound": "Uživatel nenalezen", + "userSearchFailed": "Hledání se nezdařilo", + "settingsPage": "Nastavení", + "themeSettings": "Motiv", + "languageSettings": "Jazyk aplikace", + "chatTheme": "Téma chatu", + "useGlobalTheme": "Použít globální motiv", + "notificationSettings": "Oznámení", + "biometrySettings": "Ověření otiskem prstu", + "wikiLink": "Wiki", + "repoLink": "Zdrojový kód", + "deleteAllChatsConfirm": "Potvrdit smazání všech chatů", + "deleteAllChatsConfirmText": "Opravdu chcete smazat všechny své chaty?", + "deleteAllChats": "Smazat všechny chaty", + "logoutConfirm": "Potvrdit odhlášení", + "logoutConfirmText": "Opravdu se chcete odhlásit? Všechna vaše data budou smazána a váš účet bude odstraněn i ze serveru.", + "logout": "Odhlásit se", + "accountDeleted1": "Byli jste odhlášeni a váš účet byl smazán", + "logoutAndDelete": "Odhlásit se a smazat účet", + "invalidMail": "Neplatný e-mail", + "userMail": "E-mail uživatele", + "themeMode": "Režim motivu", + "systemText": "Systémový", + "lightText": "Světlý", + "darkText": "Tmavý", + "themeColor": "Barva motivu", + "themePreviewPeer": "Ahoj, jak to vypadá?", + "themePreviewOwn": "Takto bude vypadat tvůj chat", + "themePreviewButton": "Odeslat", + "chooseColor": "Vybrat barvu", + "pickColor": "Vyberte barvu", + "newMessagesTitle": "Nové zprávy", + "newMessagesBody": "Máte nové zprávy v chatu", + "notificationChannelDesc": "Oznámení pro nové zprávy v chatu", + "tickerLocalNotifications": "Nové zprávy v chatu", + "sheptLocalNotificationSingleMessage": "Máte novou zprávu v chatu", + "offlineTrue": "Jste offline :(", + "offlineFalse": "Jste zpět online :)", + "decryptionFailed": "Dešifrování selhalo", + "yesterdayText": "Včera", + "todayText": "Dnes", + "meText": "Já", + "reactionsTitle": "Reakce", + "accountDeleted2": "Váš účet byl smazán :P", + "wsOffline": "WebSocket je offline", + "attachButton": "Přiložit", + "attachCamera": "Foťák", + "attachGallery": "Galerie fotek a videí", + "gifFromKeyboardFailed": "GIF z klávesnice se nepodařilo načíst", + "attachFile": "Soubor", + "holdToRecord": "Podržením nahrajete hlasovou zprávu", + "slideToCancel": "Posunutím zrušíte", + "releaseToCancel": "Uvolněním zrušíte", + "voiceTooShort": "Nahrávka je příliš krátká", + "micPermissionDenied": "Přístup k mikrofonu byl odepřen", + "mediaUploadFailed": "Nahrání přílohy selhalo", + "mediaDownloadFailed": "Stažení selhalo", + "mediaError": "Médium se nepodařilo otevřít", + "retry": "Zkusit znovu", + "mediaPhoto": "Fotka", + "mediaGif": "GIF", + "mediaVideo": "Video", + "mediaTitle": "Média", + "noMedia": "V tomto chatu zatím nejsou žádná média", + "mediaVoice": "Hlasová zpráva", + "changePassword": "Změnit heslo", + "currentPassword": "Současné heslo", + "newPassword": "Nové heslo", + "confirmPassword": "Potvrďte nové heslo", + "passwordMismatch": "Hesla se neshodují", + "wrongCurrentPassword": "Současné heslo není správné", + "passwordChanged": "Heslo změněno", + "passwordChangeFailed": "Heslo se nepodařilo změnit", + "biometricsDisabledAfterMigration": "Biometrika byla vypnuta. Odemkni heslem a znovu ji zapni v nastavení.", + "passwordMigrationFailed": "Lokální data se nepodařilo otevřít. Heslo neodpovídá uloženým datům.", + "copyMessage": "Kopírovat", + "forwardMessage": "Přeposlat", + "saveAttachment": "Uložit přílohu", + "deleteMessageForMe": "Smazat pro mě", + "deleteMessageForEveryone": "Smazat pro všechny", + "deleteMessageConfirm": "Smazat zprávu", + "deleteMessageConfirmText": "Zpráva se smaže ze všech tvých zařízení. Druhá strana si ji nechá.", + "deleteMessageForEveryoneConfirm": "Smazat pro všechny", + "deleteMessageForEveryoneConfirmText": "Zpráva se smaže na serveru a druhá strana o ni přijde. Co už měla stažené, jí zůstane.", + "deleteMessageForEveryoneFailed": "Pro všechny lze smazat jen zprávu, která je v archivu", + "deleteChatFailed": "Smazání chatu se nepovedlo", + "copiedText": "Zkopírováno", + "attachmentSaved": "Příloha uložena", + "attachmentSaveFailed": "Uložení přílohy se nepovedlo", + "forwardTo": "Přeposlat komu", + "forwarded": "Přeposláno", + "showFull": "Zobrazit více", + "showLess": "Zobrazit méně", + "newMessages": "Nové zprávy", + "selectedCount": "Vybráno: %d", + "moreActions": "Další akce", + "jumpToLatest": "Skočit na nejnovější", + "searchInChat": "Hledat v tomto chatu", + "searchHint": "Hledat v lokální historii", + "searchEmptyHint": "Napiš text. Hledá se jen v této konverzaci a jen v tomto zařízení.", + "noSearchResults": "Nic nenalezeno", + "jumpToDate": "Skočit na datum", + "noMessagesOnDate": "Žádné zprávy od toho dne", + "allChats": "Vše", + "unreadChats": "Nepřečtené", + "pinnedChats": "Připnuté", + "noChatsInFilter": "Tady nic není", + "chatPinned": "Chat připnut", + "chatUnpinned": "Chat odebrán z připnutých", + "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", + "mediaFile": "Soubor", + "fileTooLarge": "Soubor je příliš velký, maximum je", + "send": "Odeslat", + "cancel": "Zrušit", + "sendAttachment": "Odeslat přílohu", + "sendAlbum": "Odeslat album", + "addCaption": "Přidat popisek", + "fileTypeNotAllowed": "Fotky a videa posílej přes Galerii nebo Fotoaparát", + "mediaAlbum": "Album", + "messageSending": "Odesílá se", + "messageSendFailed": "Odeslání se nezdařilo", + "resendMessage": "Odeslat znovu", + "messageUndecryptable": "Tuto zprávu se nepodařilo dešifrovat", + "mediaExpired": "Příloha už není na serveru dostupná", + "notificationPreview": "Zobrazovat text zpráv v notifikacích", + "typingIndicator": "Ukazovat, když píšu", + "presence": "Sdílet stav online a naposledy viděn", + "typing": "píše…", + "online": "online", + "lastSeenAt": "naposledy viděn {}", + "noConversation": "S tímto člověkem jste si ještě nenapsali", + "newMessageBody": "Máte novou zprávu", + "insecureServerUrl": "Server musí používat HTTPS", + "internalError": "Na serveru se něco pokazilo", + "invalidRequest": "Neplatný požadavek", + "notAuthorized": "Na tohle nemáte oprávnění", + "tooManyRequests": "Příliš mnoho požadavků, zkuste to za minutu", + "accountWillBeDeleted": "Tento účet se právě maže", + "currentUserDoesNotExist": "Váš účet už neexistuje", + "userNotFound": "Uživatel neexistuje", + "userAlreadyInDeleteList": "Uživatel už je na seznamu ke smazání", + "cannotDeleteSelf": "Sám sebe smazat nemůžete", + "usernameRequired": "Uživatelské jméno je povinné", + "usernameAlreadyTaken": "Uživatelské jméno je už obsazené", + "accessTokenRequired": "Chybí přístupový token", + "accessTokenNotFound": "WebSocket přístupový token nebyl nalezen", + "accessTokenMismatch": "WebSocket přístupový token nesouhlasí", + "invalidToken": "Neplatný nebo prošlý token", + "loginChallengeMissing": "Přihlašovací token neobsahuje výzvu", + "loginChallengeUsed": "Přihlašovací výzva je neznámá nebo už použitá", + "refreshTokenNotRevocable": "Relaci nelze obnovit, přihlaste se znovu", + "refreshSessionRevoked": "Relace byla zrušena nebo už použitá, přihlaste se znovu", + "inviteDoesNotExist": "Pozvánka neexistuje", + "invalidEmailAddress": "Neplatná e-mailová adresa", + "tooManyActiveInvites": "Příliš mnoho aktivních pozvánek", + "mediaFileTooLarge": "Příloha je příliš velká", + "mediaNotFound": "Příloha neexistuje", + "invalidMediaId": "Neplatné ID přílohy", + "tooManyPendingMediaFiles": "Příliš mnoho nevyzvednutých příloh", + "cannotSendToSelf": "Sám sobě poslat nemůžete", + "cannotSendToUser": "Tomuto uživateli poslat nemůžete", + "receiverQueueFull": "Příjemce má příliš mnoho nedoručených zpráv", + "accountInactive": "Účet už není aktivní", + "tooManyMessages": "Příliš mnoho zpráv, zpomalte", + "invalidMessage": "Zpráva není platná", + "invalidMessageType": "Podporované jsou jen binární zprávy", + "unsupportedMessageType": "Nepodporovaný typ zprávy", + "implausibleTimestamp": "Čas zprávy je mimo rozsah", + "serverError": "Neočekávaná chyba serveru", + "httpError": "HTTP chyba {}", + "devicesPage": "Zařízení", + "devicesSettings": "Zařízení a relace", + "thisDevice": "toto zařízení", + "deviceLastSeen": "Naposledy aktivní {}", + "deviceRevokedAt": "Zablokováno {}", + "revoke": "Zablokovat", + "unrevoke": "Povolit znovu", + "revokeDevice": "Zablokovat zařízení", + "unrevokeDevice": "Povolit zařízení znovu", + "revokeDeviceConfirm": "Zablokovat „{}“? Nebude se moci přihlásit, posílat ani přijímat, dokud ho jiné zařízení znovu nepovolí.", + "unrevokeDeviceConfirm": "Povolit „{}“ znovu přihlášení?", + "deviceRevokedToast": "Zařízení zablokováno", + "deviceUnrevokedToast": "Zařízení znovu povoleno", + "retentionSettings": "Retence historie na serveru", + "retentionTitle": "Jak dlouho server drží historii", + "retentionExplain": "Šifrovaný obsah zpráv zůstává na serveru, aby se offline zařízení dohnalo. Platí kratší nastavení z obou stran konverzace.", + "retentionDays": "{} dní", + "retentionSaved": "Retence upravena", + "deviceRevoked": "Toto zařízení bylo zablokováno. Povolit ho znovu lze z jiného zařízení.", + "clientVersionUnsupported": "Aplikace je pro server příliš stará. Aktualizujte ji.", + "invalidDevice": "Zařízení se nepodařilo zaregistrovat.", + "deviceNotFound": "Zařízení nenalezeno.", + "invalidRetention": "Nepodporovaná hodnota retence.", + "invalidCursor": "Neplatný požadavek na historii.", + "confirm": "Potvrdit", + "newLoginTitle": "Nové přihlášení", + "editMessage": "Upravit zprávu", + "pinMessage": "Připnout", + "unpinMessage": "Odepnout", + "selectMessage": "Vybrat", + "messageEdited": "upraveno", + "pinnedMessages": "Připnuté zprávy", + "noPinnedMessages": "Zatím žádná připnutá zpráva", + "forwardedMessage": "Přeposláno", + "readReceipts": "Potvrzení o přečtení", + "messageDelivered": "Doručeno", + "messageRead": "Přečteno", + "attachmentCaptionUneditable": "Tetó příloze nelze upravit popisek", + "disappearingSettings": "Mizející zprávy", + "disappearingHint": "Musí souhlasit obě strany: vaše volba je návrh, dokud ji protistrana nepřijme.", + "disappearingAccept": "Přijmout {}", + "disappearingDecline": "Odmítnout", + "disappearingProposalShort": "návrh {}", + "disappearingOff": "vypnuto", + "disappearingChanged": "Mizející zprávy se změnily", + "disappearingProposalPill": "Navrženy mizející zprávy: {}", + "disappearingEnabledPill": "Mizející zprávy: {}", + "disappearingDeclinedPill": "Návrh mizejících zpráv odmítnut", + "attachViewOnce": "Zobrazit jednou", + "viewOnceOpen": "Klepnutím zobrazit jednou", + "viewOnceLoad": "Klepnutím stáhnout", + "viewOnceMedia": "Jednorázová příloha", + "screenshotDetected": "Screenshot zaznamenán", + "locationMessage": "Poloha", + "openInMaps": "Otevřít v Mapách", + "attachLocation": "Poslat polohu", + "attachLiveLocation": "Sdílet živou polohu", + "liveLocationShare": "Sdílet živou polohu", + "liveLocationFor": "Na {}", + "liveLocationMine": "Sdílím polohu", + "liveLocationTheirs": "Sdílí polohu", + "liveLocationStop": "Ukončit sdílení", + "locationUnavailable": "Poloha není dostupná", + "viewOnceSent": "Jednorázová příloha odeslána", + "viewOnceOpened": "Zobrazeno", + "viewOnceOpenedByPeer": "Otevřeno", + "messageDeleted": "Zpráva byla smazána", + "viewOnceHint": "Po prvním otevření zmizí oběma stranám", + "liveLocationEnded": "Sdílení skončilo", + "storageTitle": "Úložiště a data", + "storageTotal": "Média na tomto zařízení", + "storageMediaCount": "příloh", + "storageAutoDelete": "Mazat média po", + "storageDaysSuffix": "dní", + "storageNever": "Nikdy", + "storageSingleDelivery": "Média jsou jednorázová: co se tady smaže, už nelze znovu stáhnout.", + "storageClearCache": "Vymazat mezipaměť", + "storageCacheCleared": "Mezipaměť vymazána", + "storagePurged": "Uvolněno", + "storageEmpty": "Zatím žádná média", + "recordingLocked": "Nahrávání zamčeno, zastavte ho tlačítkem", + "mediaSticker": "Nálepka", + "autoDownloadTitle": "Stahování médií", + "autoDownloadAlways": "Vždy", + "autoDownloadWifi": "Jen Wi-Fi", + "autoDownloadNever": "Nikdy", + "downloadMedia": "Stáhnout", + "editAttachment": "Upravit", + "editImage": "Upravit fotku", + "rotate": "Otočit", + "crop": "Ořez", + "draw": "Kreslit", + "undo": "Zpět", + "applyCrop": "Použít ořez", + "trimVideo": "Oříznout video", + "attachStickers": "Nálepky", + "stickerUnsupported": "Tenhle soubor nejde použít jako nálepku", + "deleteSticker": "Smazat nálepku", + "deleteStickerConfirm": "Nálepka se z tohoto zařízení smaže. Opravdu?", + "shareMessage": "Sdílet do jiné aplikace", + "shareToChat": "Sdílet do chatu", + "shareFailed": "Sdílení se nepovedlo", + "cameraUnavailable": "Kamera není dostupná", + "applyTrim": "Oříznout", + "captureFailed": "Nepodařilo se vyfotit" +} diff --git a/assets/translations/en.json b/assets/translations/en.json index f2c4902..6a71477 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -1,88 +1,333 @@ { - "xMessagesFromYChats": "%d new messages from %d chats", - "urlError": "Error opening URL %s", - "passwordPlsWait": "Verifying password, please wait...", - "useBiometrics": "Use fingerprint", - "biometricAuthReason": "Please verify your identity with fingerprint", - "biometricAuthPrompt": "Place your finger on the sensor", - "biometricSetupReason": "Setting up fingerprint authentication", - "biometricSetupAuth": "Place your finger on the sensor to activate", - "biometricAuthFailed": "Fingerprint authentication failed", - "biometricSetupFailed": "Fingerprint setup failed", - "enableBiometrics": "Enable fingerprint login", - "biometricsEnabled": "Fingerprint login enabled", - "biometricsDisabled": "Fingerprint login disabled", - "yesText": "Yes", - "noText": "No", - "okText": "OK", - "msgPage": "Messages", - "settingsButton": "Settings", - "addChat": "New chat", - "newInvite": "New Invite", - "adminPage": "Administration", - "serverUsersPage": "Server Users", - "serverInvitesPage": "Server Invites", - "deleteUserConfirm": "Confirm User Deletion", - "deleteUserConfirmText": "Are you sure you want to delete this user? This action cannot be undone.", - "deleteUser": "Delete User", - "chatInfoPage": "Chat Info", - "deleteChatConfirm": "Confirm Chat Deletion", - "deleteChatConfirmText": "Are you sure you want to delete this chat?", - "deleteChat": "Delete chat", - "legendaryChat": "This is the beginning of your legendary conversation. Or something like that, hard to say.", - "infoButton": "Chat info", - "yourMessage": "Your awesome message...", - "invalidPassword": "Invalid password", - "invalidLocalPassword": "Invalid password", - "localPasswordPlaceholder": "Your secret password", - "localPasswordButton": "Sign in", - "invalidUsername": "Invalid username", - "waitPls": "Please wait...", - "usernamePlaceholder": "Your magical username", - "inviteExpired": "Invitation expired", - "inviteValidFor": "Invitation validity", - "registerButton": "Register", - "scanQrButton": "Scan QR code", - "invalidQr": "Invalid QR code", - "scanQr": "Scan the invitation QR code", - "searchUserPage": "Search for users", - "enterUsername": "Your victim's username", - "settingsPage": "Settings", - "themeSettings": "Theme", - "notificationSettings": "Notifications", - "biometrySettings": "Fingerprint authentication", - "wikiLink": "Wiki", - "repoLink": "Source code", - "dangerZone": "Danger zone", - "deleteAllChatsConfirm": "Confirm deletion of all chats", - "deleteAllChatsConfirmText": "Are you sure you want to delete all your chats?", - "deleteAllChats": "Delete all chats", - "logoutConfirm": "Confirm logout", - "logoutConfirmText": "Are you sure you want to log out? All your data will be deleted and your account will be removed from the server.", - "logout": "Log out", - "accountDeleted1": "You have been logged out and your account has been deleted", - "logoutAndDelete": "Log out and delete account", - "invalidMail": "Invalid email", - "userMail": "User email", - "themeMode": "Theme mode", - "systemText": "System", - "lightText": "Light", - "darkText": "Dark", - "themeColor": "Theme color", - "chooseColor": "Choose color", - "useMat3": "Material Design 3", - "pickColor": "Pick color", - "newMessagesTitle": "New messages", - "newMessagesBody": "You have new messages in chat", - "notificationChannelDesc": "Notifications for new messages in chat", - "tickerLocalNotifications": "New messages in chat", - "whisperLocalNotificationSingleMessage": "You have a new message in chat", - "offlineTrue": "You are offline :(", - "offlineFalse": "You are back online :)", - "decryptionFailed": "Decryption failed", - "yesterdayText": "Yesterday", - "todayText": "Today", - "meText": "Me", - "accountDeleted2": "Your account has been deleted :P", - "wsOffline": "WebSocket is offline" -} \ No newline at end of file + "xMessagesFromYChats": "%d new messages from %d chats", + "urlError": "Error opening URL %s", + "passwordPlsWait": "Verifying password, please wait...", + "useBiometrics": "Use fingerprint", + "biometricAuthReason": "Please verify your identity with fingerprint", + "biometricAuthPrompt": "Place your finger on the sensor", + "biometricSetupReason": "Setting up fingerprint authentication", + "biometricSetupAuth": "Place your finger on the sensor to activate", + "biometricAuthFailed": "Fingerprint authentication failed", + "biometricSetupFailed": "Fingerprint setup failed", + "enableBiometrics": "Enable fingerprint login", + "biometricsEnabled": "Fingerprint login enabled", + "biometricsDisabled": "Fingerprint login disabled", + "yesText": "Yes", + "noText": "No", + "okText": "So be it", + "msgPage": "Messages", + "settingsButton": "Settings", + "addChat": "New chat", + "newInvite": "New Invite", + "adminPage": "Administration", + "serverUsersPage": "Server Users", + "serverInvitesPage": "Server Invites", + "deleteUserConfirm": "Confirm User Deletion", + "deleteUserConfirmText": "Are you sure you want to delete this user? This action cannot be undone.", + "deleteUser": "Delete User", + "adminBadge": "ADMIN", + "noUsers": "No users", + "noInvites": "No invites", + "loadError": "Failed to load data", + "userDeleted": "User deleted", + "deleteUserConfirmTextName": "Are you sure you want to delete %s? This action cannot be undone.", + "inviteExpiresIn": "expires in %s %s", + "chatInfoPage": "Chat Info", + "deleteChatConfirm": "Confirm Chat Deletion", + "deleteChatConfirmText": "Are you sure you want to delete this chat?", + "deleteChat": "Delete chat", + "legendaryChat": "This is the beginning of your legendary conversation. Or something like that, hard to say.", + "infoButton": "Chat info", + "yourMessage": "Your awesome message...", + "invalidPassword": "Invalid password", + "invalidLocalPassword": "Invalid password", + "localPasswordPlaceholder": "Your secret password", + "localPasswordButton": "Sign in", + "invalidUsername": "Invalid username", + "waitPls": "Please wait...", + "usernamePlaceholder": "Your magical username", + "inviteExpired": "Invitation expired", + "inviteValidFor": "Invitation validity", + "registerButton": "Register", + "scanQrButton": "Scan QR code", + "invalidQr": "Invalid QR code", + "scanQr": "Scan the invitation QR code", + "searchUserPage": "Search for users", + "enterUsername": "Your victim's username", + "clearSearch": "Clear search", + "noUsersFound": "No users found", + "userSearchFailed": "Search failed", + "settingsPage": "Settings", + "themeSettings": "Theme", + "languageSettings": "App language", + "chatTheme": "Chat theme", + "useGlobalTheme": "Use global theme", + "notificationSettings": "Notifications", + "biometrySettings": "Fingerprint authentication", + "wikiLink": "Wiki", + "repoLink": "Source code", + "deleteAllChatsConfirm": "Confirm deletion of all chats", + "deleteAllChatsConfirmText": "Are you sure you want to delete all your chats?", + "deleteAllChats": "Delete all chats", + "logoutConfirm": "Confirm logout", + "logoutConfirmText": "Are you sure you want to log out? All your data will be deleted and your account will be removed from the server.", + "logout": "Log out", + "accountDeleted1": "You have been logged out and your account has been deleted", + "logoutAndDelete": "Log out and delete account", + "invalidMail": "Invalid email", + "userMail": "User email", + "themeMode": "Theme mode", + "systemText": "System", + "lightText": "Light", + "darkText": "Dark", + "themeColor": "Theme color", + "themePreviewPeer": "Hi, how does it look?", + "themePreviewOwn": "Your chat will look like this", + "themePreviewButton": "Send", + "chooseColor": "Choose color", + "pickColor": "Pick color", + "newMessagesTitle": "New messages", + "newMessagesBody": "You have new messages in chat", + "notificationChannelDesc": "Notifications for new messages in chat", + "tickerLocalNotifications": "New messages in chat", + "sheptLocalNotificationSingleMessage": "You have a new message in chat", + "offlineTrue": "You are offline :(", + "offlineFalse": "You are back online :)", + "decryptionFailed": "Decryption failed", + "yesterdayText": "Yesterday", + "todayText": "Today", + "meText": "Me", + "reactionsTitle": "Reactions", + "accountDeleted2": "Your account has been deleted :P", + "wsOffline": "WebSocket is offline", + "attachButton": "Attach", + "attachCamera": "Camera", + "attachGallery": "Photo & video gallery", + "gifFromKeyboardFailed": "This keyboard GIF could not be read", + "attachFile": "File", + "holdToRecord": "Hold to record a voice message", + "slideToCancel": "Slide to cancel", + "releaseToCancel": "Release to cancel", + "voiceTooShort": "Recording too short", + "micPermissionDenied": "Microphone permission denied", + "mediaUploadFailed": "Failed to upload attachment", + "mediaDownloadFailed": "Download failed", + "mediaError": "Could not open media", + "retry": "Retry", + "mediaPhoto": "Photo", + "mediaGif": "GIF", + "mediaVideo": "Video", + "mediaTitle": "Media", + "noMedia": "No media in this chat yet", + "mediaVoice": "Voice message", + "changePassword": "Change password", + "currentPassword": "Current password", + "newPassword": "New password", + "confirmPassword": "Confirm new password", + "passwordMismatch": "Passwords do not match", + "wrongCurrentPassword": "Current password is incorrect", + "passwordChanged": "Password changed", + "passwordChangeFailed": "Password could not be changed", + "biometricsDisabledAfterMigration": "Biometrics were turned off. Unlock with your password and enable them again in settings.", + "passwordMigrationFailed": "Local data could not be opened. The password does not match the stored data.", + "copyMessage": "Copy", + "forwardMessage": "Forward", + "saveAttachment": "Save attachment", + "deleteMessageForMe": "Delete for me", + "deleteMessageForEveryone": "Delete for everyone", + "deleteMessageConfirm": "Delete message", + "deleteMessageConfirmText": "The message will be deleted from all your devices. The other side keeps it.", + "deleteMessageForEveryoneConfirm": "Delete for everyone", + "deleteMessageForEveryoneConfirmText": "The message will be erased on the server and the other side loses it. Anything they already downloaded stays with them.", + "deleteMessageForEveryoneFailed": "Only an archived message can be deleted for everyone", + "deleteChatFailed": "Deleting the chat failed", + "copiedText": "Copied", + "attachmentSaved": "Attachment saved", + "attachmentSaveFailed": "Saving the attachment failed", + "forwardTo": "Forward to", + "forwarded": "Forwarded", + "showFull": "Show full message", + "showLess": "Show less", + "newMessages": "New messages", + "selectedCount": "%d selected", + "moreActions": "More actions", + "jumpToLatest": "Jump to latest", + "searchInChat": "Search in this chat", + "searchHint": "Search the local history", + "searchEmptyHint": "Type to search this conversation. Messages are searched on this device only.", + "noSearchResults": "Nothing found", + "jumpToDate": "Jump to date", + "noMessagesOnDate": "No messages from that day or later", + "allChats": "All", + "unreadChats": "Unread", + "pinnedChats": "Pinned", + "noChatsInFilter": "Nothing here", + "chatPinned": "Chat pinned", + "chatUnpinned": "Chat unpinned", + "noChatsToForward": "No chats yet, search for a user", + "mediaFile": "File", + "fileTooLarge": "File is too large, the maximum is", + "send": "Send", + "cancel": "Cancel", + "sendAttachment": "Send attachment", + "sendAlbum": "Send album", + "addCaption": "Add a caption", + "fileTypeNotAllowed": "Photos and videos go through Gallery or Camera", + "mediaAlbum": "Album", + "messageSending": "Sending", + "messageSendFailed": "Sending failed", + "resendMessage": "Send again", + "messageUndecryptable": "This message could not be decrypted", + "mediaExpired": "The attachment is no longer available on the server", + "notificationPreview": "Show message text in notifications", + "typingIndicator": "Share when I am typing", + "presence": "Share online status and last seen", + "typing": "typing…", + "online": "online", + "lastSeenAt": "last seen {}", + "noConversation": "You have not exchanged a message with this person yet", + "newMessageBody": "You have a new message", + "insecureServerUrl": "The server must use HTTPS", + "internalError": "Something went wrong on the server", + "invalidRequest": "Invalid request", + "notAuthorized": "You are not allowed to do this", + "tooManyRequests": "Too many requests, try again in a minute", + "accountWillBeDeleted": "This account is being deleted", + "currentUserDoesNotExist": "Your account no longer exists", + "userNotFound": "User does not exist", + "userAlreadyInDeleteList": "The user is already scheduled for deletion", + "cannotDeleteSelf": "You cannot delete yourself", + "usernameRequired": "Username is required", + "usernameAlreadyTaken": "Username is already taken", + "accessTokenRequired": "Access token is required", + "accessTokenNotFound": "WebSocket access token not found", + "accessTokenMismatch": "WebSocket access token does not match", + "invalidToken": "Invalid or expired token", + "loginChallengeMissing": "The login token has no challenge", + "loginChallengeUsed": "The login challenge is unknown or already used", + "refreshTokenNotRevocable": "The session cannot be renewed, sign in again", + "refreshSessionRevoked": "The session was revoked or already used, sign in again", + "inviteDoesNotExist": "Invitation does not exist", + "invalidEmailAddress": "Invalid email address", + "tooManyActiveInvites": "Too many active invitations", + "mediaFileTooLarge": "The attachment is too large", + "mediaNotFound": "The attachment does not exist", + "invalidMediaId": "Invalid attachment id", + "tooManyPendingMediaFiles": "Too many pending attachments", + "cannotSendToSelf": "You cannot send to yourself", + "cannotSendToUser": "You cannot send to this user", + "receiverQueueFull": "The recipient has too many undelivered messages", + "accountInactive": "The account is no longer active", + "tooManyMessages": "Too many messages, slow down", + "invalidMessage": "The message is not valid", + "invalidMessageType": "Only binary messages are supported", + "unsupportedMessageType": "Unsupported message type", + "implausibleTimestamp": "The message timestamp is out of range", + "serverError": "Unexpected server error", + "httpError": "HTTP error {}", + "devicesPage": "Devices", + "devicesSettings": "Devices and sessions", + "thisDevice": "this device", + "deviceLastSeen": "Last seen {}", + "deviceRevokedAt": "Revoked {}", + "revoke": "Revoke", + "unrevoke": "Allow again", + "revokeDevice": "Revoke device", + "unrevokeDevice": "Allow device again", + "revokeDeviceConfirm": "Revoke \"{}\"? It cannot sign in, send or receive until another device allows it again.", + "unrevokeDeviceConfirm": "Allow \"{}\" to sign in again?", + "deviceRevokedToast": "Device revoked", + "deviceUnrevokedToast": "Device allowed again", + "retentionSettings": "Server history retention", + "retentionTitle": "How long the server keeps history", + "retentionExplain": "Ciphertext of your messages stays on the server so an offline device can catch up. The shorter setting of the two participants wins.", + "retentionDays": "{} days", + "retentionSaved": "Retention updated", + "deviceRevoked": "This device was revoked. Sign in on another device to allow it again.", + "clientVersionUnsupported": "This app is too old for the server. Update it.", + "invalidDevice": "This device could not be registered.", + "deviceNotFound": "Device not found.", + "invalidRetention": "Unsupported retention value.", + "invalidCursor": "The history request was invalid.", + "confirm": "Confirm", + "newLoginTitle": "New login", + "editMessage": "Edit message", + "pinMessage": "Pin", + "unpinMessage": "Unpin", + "selectMessage": "Select", + "messageEdited": "edited", + "pinnedMessages": "Pinned messages", + "noPinnedMessages": "No pinned messages yet", + "forwardedMessage": "Forwarded", + "readReceipts": "Read receipts", + "messageDelivered": "Delivered", + "messageRead": "Read", + "attachmentCaptionUneditable": "This attachment's caption can't be edited", + "disappearingSettings": "Disappearing messages", + "disappearingHint": "Both sides have to agree: your choice is a proposal until the other side accepts it.", + "disappearingAccept": "Accept {}", + "disappearingDecline": "Decline", + "disappearingProposalShort": "proposal {}", + "disappearingOff": "off", + "disappearingChanged": "Disappearing messages changed", + "disappearingProposalPill": "Disappearing messages proposed: {}", + "disappearingEnabledPill": "Disappearing messages: {}", + "disappearingDeclinedPill": "Disappearing messages proposal declined", + "attachViewOnce": "View once", + "viewOnceOpen": "Tap to view once", + "viewOnceLoad": "Tap to download", + "viewOnceMedia": "View-once attachment", + "screenshotDetected": "Screenshot detected", + "locationMessage": "Location", + "openInMaps": "Open in maps", + "attachLocation": "Send location", + "attachLiveLocation": "Share live location", + "liveLocationShare": "Share live location", + "liveLocationFor": "For {}", + "liveLocationMine": "Sharing location", + "liveLocationTheirs": "Sharing location", + "liveLocationStop": "Stop sharing", + "locationUnavailable": "Location is not available", + "viewOnceSent": "View-once attachment sent", + "viewOnceOpened": "Opened", + "viewOnceOpenedByPeer": "Opened", + "messageDeleted": "Message deleted", + "viewOnceHint": "Gone for both sides after it is opened once", + "liveLocationEnded": "Sharing ended", + "storageTitle": "Storage and data", + "storageTotal": "Media on this device", + "storageMediaCount": "attachments", + "storageAutoDelete": "Delete media after", + "storageDaysSuffix": "days", + "storageNever": "Never", + "storageSingleDelivery": "Media is single delivery: what is deleted here cannot be downloaded again.", + "storageClearCache": "Clear cache", + "storageCacheCleared": "Cache cleared", + "storagePurged": "Freed", + "storageEmpty": "No media yet", + "recordingLocked": "Recording locked, stop it with the button", + "mediaSticker": "Sticker", + "autoDownloadTitle": "Media download", + "autoDownloadAlways": "Always", + "autoDownloadWifi": "Wi-Fi only", + "autoDownloadNever": "Never", + "downloadMedia": "Download", + "editAttachment": "Edit", + "editImage": "Edit photo", + "rotate": "Rotate", + "crop": "Crop", + "draw": "Draw", + "undo": "Undo", + "applyCrop": "Apply crop", + "trimVideo": "Trim video", + "attachStickers": "Stickers", + "stickerUnsupported": "This file cannot be used as a sticker", + "deleteSticker": "Delete sticker", + "deleteStickerConfirm": "The sticker is removed from this device. Continue?", + "shareMessage": "Share to another app", + "shareToChat": "Share to a chat", + "shareFailed": "Sharing failed", + "cameraUnavailable": "Camera is not available", + "applyTrim": "Trim", + "captureFailed": "Could not capture" +} diff --git a/docs/adr/0001-local-encryption.md b/docs/adr/0001-local-encryption.md new file mode 100644 index 0000000..e6dae48 --- /dev/null +++ b/docs/adr/0001-local-encryption.md @@ -0,0 +1,18 @@ +# 0001 - Encrypt on the device, server sees ciphertext + +Status: accepted (2026-11-11) + +## Context +Messages and media pass through a self-hosted server that must not read them. +There is no key escrow and no password reset that could recover content. + +## Decision +Messages use AES-256-GCM content with the AES key wrapped by the recipient's +RSA-4096 public key. Media uses a random per-file AES-256-GCM key that travels +inside the encrypted message; the download is decrypted on the device and +stored encrypted at rest with the PBKDF2-derived app key. Biometrics only +unlock that key from secure storage. + +## Consequences +A lost private key means unreadable history; the server cannot scan or +transcode attachments; RSA-4096, AES-256-GCM and PBKDF2 are a hard floor. diff --git a/docs/adr/0002-client-versioning.md b/docs/adr/0002-client-versioning.md new file mode 100644 index 0000000..5585d41 --- /dev/null +++ b/docs/adr/0002-client-versioning.md @@ -0,0 +1,17 @@ +# 0002 - Pin clients to tags once releases exist + +Status: superseded by [0003](0003-client-pinning.md) (2026-11-17) + +## Context +`pubspec.yaml` pulls both Dart clients through `path: ../...`. CI must check out +sibling repositories and nothing records which client version the app used. + +## Decision +Keep `path:` while the clients have no release tags; local and CI checkouts put +them next to the app. After the first server `v*` tag, tag the clients and pin +the app to those tags. Generated code is still regenerated in one sequence with +the server spec. + +## Consequences +CI depends on sibling checkouts and the branch name today; the Flutter E2E +workflow already mirrors what a tag pin will replace. diff --git a/docs/adr/0003-client-pinning.md b/docs/adr/0003-client-pinning.md new file mode 100644 index 0000000..d512451 --- /dev/null +++ b/docs/adr/0003-client-pinning.md @@ -0,0 +1,23 @@ +# 0003 - Clients are pinned by release tag + +Status: accepted (2026-11-17) + +## Context +`pubspec.yaml` pulled both Dart clients through `path: ../...`. Nothing recorded +which client the app was built against, CI had to check out two sibling +repositories, and a local change to a client silently changed the app. + +## Decision +Both clients are tagged `v0.1.0` (pre-1.0: the products tag `v1.0.0` only after +F1-F10) and the app depends on them as git dependencies at that tag. Local work +on a client and the app together uses `pubspec_overrides.yaml`, which is +gitignored, so CI and release builds always resolve the tags. + +The OpenAPI client carries `lib/version.dart` with `clientVersion`, the WS client +`lib/version.dart`, and the app `lib/utils/version.dart` with `appVersion`, which +it sends as `X-Client-Version`. The server refuses a login below its +`minClientVersion` (`GET /api/version`). + +## Consequences +A contract change needs a new tag on the client before the app can use it, and +the app version bump lands in the same series. CI no longer checks out siblings. diff --git a/docs/adr/README.md b/docs/adr/README.md new file mode 100644 index 0000000..e6760f8 --- /dev/null +++ b/docs/adr/README.md @@ -0,0 +1,9 @@ +# Architecture Decision Records + +| ADR | Decision | +| --- | --- | +| [0001](0001-local-encryption.md) | Encrypt on the device; the server sees ciphertext only | +| [0002](0002-client-versioning.md) | Pin clients to tags once releases exist (superseded by 0003) | +| [0003](0003-client-pinning.md) | Clients are pinned by release tag, app sends its version | + +Cross-cutting decisions live in the Notion Engineering Standard. diff --git a/integration_test/app_e2e_test.dart b/integration_test/app_e2e_test.dart new file mode 100644 index 0000000..fc1d4d1 --- /dev/null +++ b/integration_test/app_e2e_test.dart @@ -0,0 +1,176 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:integration_test/integration_test.dart'; +import 'package:pointycastle/export.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/crypto_utils.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/utils.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import 'package:shept_websocket_client_dart/models/new_private_message.dart'; +import 'package:shept_websocket_client_dart/models/private_message.dart'; +import 'package:shept_websocket_client_dart/models/ws_message.dart'; +import 'package:shept_websocket_client_dart/models/ws_response.dart'; +import 'package:shept_websocket_client_dart/ws_client.dart'; + +import 'fake_server.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + late FakeServer server; + late AsymmetricKeyPair keys; + + setUpAll(() async { + server = await FakeServer.start(); + Directory cacheDir = Directory(await Utils.getCacheDir()); + await cacheDir.create(recursive: true); + Hive.init(cacheDir.path); + keys = await CryptoUtils.getRSAKeyPair(); + }); + + tearDownAll(() async { + Box box = await Hive.openBox('hash'); + await box.clear(); + await Hive.close(); + await server.stop(); + }); + + ApiClient client(String? accessToken) { + HttpBearerAuth? auth; + if (accessToken != null) { + auth = HttpBearerAuth()..accessToken = accessToken; + } + return ApiClient(basePath: server.url, authentication: auth); + } + + testWidgets('invite registration creates a user', (tester) async { + final apiClient = client(null); + final user = await AuthenticationApi(apiClient).createUser( + createUserInput: CreateUserInput( + inviteCode: 'i' * 64, + publicKey: bu.CryptoUtils.encodeRSAPublicKeyToPem( + keys.publicKey as bu.RSAPublicKey), + username: 'e2euser', + ), + ); + + expect(user, isNotNull); + expect(user!.username, 'e2euser'); + expect(user.id, isNotEmpty); + }); + + testWidgets('login with RSA JWT and refresh', (tester) async { + final apiClient = client(null); + final authApi = AuthenticationApi(apiClient); + // The login token must carry the one-time challenge. + final challenge = await authApi.authChallenge(); + final jwt = await CryptoUtils.generateRsaJwt( + '1', keys.privateKey as bu.RSAPrivateKey, + nonce: challenge!.challenge, deviceId: 'e2e-device'); + final auth = await authApi.authUser( + authUserInput: AuthUserInput( + token: jwt, + deviceId: 'e2e-device', + label: 'e2e', + platform: 'linux', + ), + ); + + expect(auth!.accessToken, isNotEmpty); + expect(auth.refreshToken, isNotEmpty); + + final refreshed = await authApi.refreshUserAccessToken( + refreshUserAccessTokenInput: + RefreshUserAccessTokenInput(refreshToken: auth.refreshToken), + ); + expect(refreshed!.accessToken, isNotEmpty); + }); + + testWidgets('message is encrypted, sent over WS and decrypted by receiver', + (tester) async { + final receiverToken = + await WebSocketAuthenticationApi(client('access-1')).webSocketAuth(); + final senderToken = + await WebSocketAuthenticationApi(client('access-2')).webSocketAuth(); + + final received = Completer(); + final receiver = WsClient(server.wsUrl, onReceived: received.complete); + await receiver.connect( + receiverToken!.accessToken, const Duration(seconds: 5)); + final sender = WsClient(server.wsUrl); + await sender.connect(senderToken!.accessToken, const Duration(seconds: 5)); + + final encrypted = await CryptoUtils.encryptMessageData( + Uint8List.fromList(utf8.encode('hello over websocket')), + keys.publicKey as RSAPublicKey); + sender.sendMessage(WsMessage.privateMessage(NewPrivateMessage( + '1', + encrypted['encryptedData']!, + encrypted['encryptedKey']!, + encrypted['nonce']!, + encrypted['mac']!, + ))); + + final response = await received.future.timeout(const Duration(seconds: 5)); + final message = (response.payload as List).single; + expect(message.senderId, '2'); + + final plaintext = await CryptoUtils.decryptMessageData( + message.content!, + message.key!, + message.nonce!, + message.mac!, + keys.privateKey as RSAPrivateKey, + ); + expect(utf8.decode(plaintext), 'hello over websocket'); + sender.disconnect(); + receiver.disconnect(); + }); + + testWidgets('media upload sends only ciphertext and receiver decrypts it', + (tester) async { + final plaintext = Uint8List.fromList(utf8.encode('top secret attachment')); + final encrypted = await MediaUtils.encryptForTransport(plaintext); + + final upload = await MediaApi(client('access-1')).uploadMedia( + http.MultipartFile.fromBytes('file', encrypted.blob, + filename: 'blob.bin'), + '2', + ); + expect(upload!.id, isNotEmpty); + + final download = await http.get( + Uri.parse('${server.url}/api/media/${upload.id}'), + headers: {'Authorization': 'Bearer access-2'}, + ); + expect(download.statusCode, 200); + expect(download.bodyBytes, isNot(equals(plaintext))); + expect(download.bodyBytes, encrypted.blob); + expect(await MediaUtils.decryptTransport(download.bodyBytes, encrypted.key), + plaintext); + + await MediaApi(client('access-2')).confirmMediaDownload(upload.id); + }); + + testWidgets('local password unlocks with a stable derived key', + (tester) async { + const password = 'correct horse battery staple'; + await CacheUtils.setPasswordHash(password); + + expect(await CacheUtils.isCorrectPassword(password), isTrue); + expect(await CacheUtils.isCorrectPassword('wrong password'), isFalse); + + final salt = CryptoUtils.generateSalt(); + final first = await CryptoUtils.pbkdf2(password, salt); + final second = await CryptoUtils.pbkdf2(password, salt); + expect(first, second); + }); +} diff --git a/integration_test/fake_server.dart b/integration_test/fake_server.dart new file mode 100644 index 0000000..588de0d --- /dev/null +++ b/integration_test/fake_server.dart @@ -0,0 +1,189 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:mime/mime.dart'; + +/// Minimal in-process backend for the Flutter E2E scenarios. It mirrors the +/// server contract closely enough to exercise the real generated API client, +/// the WebSocket client and the app crypto. +class FakeServer { + FakeServer._(this._server); + + final HttpServer _server; + final Map _wsTokens = {}; + final Map _sockets = {}; + final Map _media = {}; + final Map _mediaReceivers = {}; + int _nextUserId = 1; + int _nextMediaId = 1; + + String get url => 'http://127.0.0.1:${_server.port}'; + String get wsUrl => 'ws://127.0.0.1:${_server.port}/ws'; + + static Future start() async { + final server = FakeServer._( + await HttpServer.bind(InternetAddress.loopbackIPv4, 0), + ); + server._server.listen(server._handle); + return server; + } + + Future stop() async { + for (final socket in _sockets.values) { + await socket.close(); + } + await _server.close(force: true); + } + + Future _handle(HttpRequest request) async { + final path = request.uri.path; + if (path == '/ws') { + await _handleWebSocket(request); + return; + } + try { + if (path == '/api/auth/register') { + final body = await _readJson(request); + _json(request.response, { + 'id': 'user-${_nextUserId++}', + 'username': body['username'], + 'publicKey': body['publicKey'], + 'admin': false, + }); + } else if (path == '/api/auth/challenge') { + _json(request.response, {'challenge': 'challenge-1', 'expiresIn': 30}); + } else if (path == '/api/auth') { + _json(request.response, { + 'accessToken': 'access-1', + 'refreshToken': 'refresh-1', + }); + } else if (path == '/api/auth/refresh') { + _json(request.response, {'accessToken': 'access-1'}); + } else if (path == '/api/wsauth') { + final userId = _userId(request); + final token = 'ws-$userId-${_wsTokens.length}'; + _wsTokens[token] = userId; + _json(request.response, {'accessToken': token}); + } else if (path == '/api/media' && request.method == 'POST') { + await _handleUpload(request); + } else if (path.startsWith('/api/media/')) { + final id = path.substring('/api/media/'.length); + if (request.method == 'GET') { + _handleDownload(request, id); + } else if (request.method == 'DELETE') { + _media.remove(id); + _mediaReceivers.remove(id); + request.response.statusCode = HttpStatus.noContent; + } else { + request.response.statusCode = HttpStatus.methodNotAllowed; + } + } else { + request.response.statusCode = HttpStatus.notFound; + } + } catch (e) { + request.response.statusCode = HttpStatus.internalServerError; + request.response.write('$e'); + } finally { + await request.response.close(); + } + } + + Future _handleUpload(HttpRequest request) async { + final boundary = request.headers.contentType?.parameters['boundary']; + if (boundary == null) { + request.response.statusCode = HttpStatus.badRequest; + return; + } + Uint8List? file; + var receiverId = ''; + await for (final part in MimeMultipartTransformer(boundary).bind(request)) { + final disposition = part.headers['content-disposition'] ?? ''; + final bytes = await part + .fold>([], (buffer, chunk) => buffer..addAll(chunk)); + if (disposition.contains('name="receiverId"')) { + receiverId = utf8.decode(bytes); + } else if (disposition.contains('name="file"') && + disposition.contains('filename=')) { + file = Uint8List.fromList(bytes); + } + } + if (file == null) { + request.response.statusCode = HttpStatus.badRequest; + return; + } + final id = 'media-${_nextMediaId++}'; + _media[id] = file; + _mediaReceivers[id] = receiverId; + _json(request.response, {'id': id}); + } + + void _handleDownload(HttpRequest request, String id) { + final file = _media[id]; + if (file == null) { + request.response.statusCode = HttpStatus.notFound; + return; + } + if (_userId(request) != _mediaReceivers[id]) { + request.response.statusCode = HttpStatus.forbidden; + return; + } + request.response.headers.contentType = ContentType.binary; + request.response.add(file); + } + + Future _handleWebSocket(HttpRequest request) async { + final token = request.uri.queryParameters['wsAccessToken']; + final userId = _wsTokens.remove(token); + if (userId == null) { + request.response.statusCode = HttpStatus.unauthorized; + return; + } + final socket = await WebSocketTransformer.upgrade(request); + _sockets[userId] = socket; + socket.listen((data) { + final text = data is String ? data : utf8.decode(data as List); + final message = jsonDecode(text) as Map; + if (message['type'] != 'message') { + return; + } + final payload = message['payload'] as Map; + final receiverId = payload['receiverId'] as String; + final response = jsonEncode({ + 'type': 'messages', + 'payload': [ + { + 'senderId': userId, + 'content': payload['content'], + 'key': payload['key'], + 'nonce': payload['nonce'], + 'mac': payload['mac'], + 'sentAt': payload['sentAt'], + 'recipientOnline': true, + } + ], + }); + final receiver = _sockets[receiverId]; + if (receiver != null) { + receiver.add(utf8.encode(response)); + } + }, onDone: () => _sockets.remove(userId)); + } + + Future> _readJson(HttpRequest request) async { + final body = await utf8.decoder.bind(request).join(); + return jsonDecode(body) as Map; + } + + String _userId(HttpRequest request) { + final header = request.headers.value(HttpHeaders.authorizationHeader) ?? ''; + final token = header.replaceFirst('Bearer ', ''); + return token.replaceFirst('access-', ''); + } + + void _json(HttpResponse response, Object body) { + response.headers.contentType = ContentType.json; + response.write(jsonEncode(body)); + } +} diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 4de624b..6526cd9 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -55,6 +55,8 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A1B2C3D41CF9000F007C117D /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -113,6 +115,7 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, + A1B2C3D41CF9000F007C117D /* Runner.entitlements */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, @@ -364,11 +367,12 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -384,7 +388,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -401,7 +405,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; @@ -416,7 +420,7 @@ CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; @@ -543,11 +547,12 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -565,11 +570,12 @@ CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.whisper; + PRODUCT_BUNDLE_IDENTIFIER = cz.josefraz.shept; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 540ed39..a09d74a 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -5,7 +5,7 @@ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleDisplayName - Whisper + Shept CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -13,7 +13,7 @@ CFBundleInfoDictionaryVersion 6.0 CFBundleName - whisper + shept CFBundlePackageType APPL CFBundleShortVersionString @@ -41,6 +41,23 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + NSCameraUsageDescription + Shept needs camera access to capture photos and videos you send in chats. + NSMicrophoneUsageDescription + Shept needs microphone access to record voice messages. + NSPhotoLibraryUsageDescription + Shept needs photo library access to attach images and videos to your messages. + NSFaceIDUsageDescription + Shept uses Face ID to unlock your encrypted messages. + LSApplicationQueriesSchemes + + https + http + + UIBackgroundModes + + remote-notification + CADisableMinimumFrameDurationOnPhone UIApplicationSupportsIndirectInputEvents diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements new file mode 100644 index 0000000..903def2 --- /dev/null +++ b/ios/Runner/Runner.entitlements @@ -0,0 +1,8 @@ + + + + + aps-environment + development + + diff --git a/lefthook.yml b/lefthook.yml new file mode 100644 index 0000000..9518c3d --- /dev/null +++ b/lefthook.yml @@ -0,0 +1,5 @@ +pre-commit: + parallel: true + commands: + gitleaks: + run: gitleaks git --pre-commit --staged --redact --no-banner diff --git a/lib/main.dart b/lib/main.dart index ac43a4d..41c2e44 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,41 +1,74 @@ +import 'dart:io'; + import 'package:easy_localization/easy_localization.dart'; -import 'package:firebase_core/firebase_core.dart'; +// intl is pinned through easy_localization; declaring it a second time would +// only duplicate that pin. +// ignore: depend_on_referenced_packages +import 'package:intl/date_symbol_data_local.dart'; +// Firebase is retired; dependency and init are commented out on purpose. +// import 'package:firebase_core/firebase_core.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hive/hive.dart'; +import 'package:mcp_toolkit/mcp_toolkit.dart'; import 'package:provider/provider.dart'; -import 'package:whisper/firebase_options.dart'; +// import 'firebase_options.dart'; import '../utils/message_notifier.dart'; import '../utils/cache_utils.dart'; import 'models/app_theme.dart'; import 'models/private_message.dart'; import 'models/profile.dart'; import 'models/user.dart'; -import 'pages/whisper_page.dart'; +import 'pages/shept_page.dart'; +import 'utils/media_utils.dart'; +import 'utils/storage_utils.dart'; import 'utils/notification_service.dart'; import 'utils/singleton.dart'; import 'utils/theme_notifier.dart'; import 'utils/utils.dart'; -// TODO tor? - void main() async { // Initialize Flutter widgets WidgetsFlutterBinding.ensureInitialized(); - // Firebase initialization - await Firebase.initializeApp( - options: DefaultFirebaseOptions.currentPlatform, - ); + // MCP toolkit exposes app internals over the debug VM service. Debug only; + // never use it with a real account (see AGENTS.md). + if (kDebugMode) { + try { + MCPToolkitBinding.instance + ..initialize() + ..initializeFlutterToolkit(); + } catch (e) { + debugPrint('MCP toolkit init failed: $e'); + } + } - // Local notifications - NotificationService().init(); + // if (Platform.isAndroid || Platform.isIOS) { + // await Firebase.initializeApp( + // options: DefaultFirebaseOptions.currentPlatform, + // ); + // } - // Load locale + // Load locale (the notification service needs it for the channel texts) await EasyLocalization.ensureInitialized(); - - // Lock orientation (https://stackoverflow.com/a/52720581/19371130) - SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + // Date patterns and month names for the languages the app ships with. Without + // them DateFormat falls back to English for everything. + for (final locale in ['en', 'cs']) { + await initializeDateFormatting(locale); + } + + // Local notifications. A failure here must not block the app. + try { + await NotificationService().init(); + } catch (e) { + debugPrint('Notification init failed: $e'); + } + + if (Platform.isAndroid || Platform.isIOS) { + // Lock orientation (https://stackoverflow.com/a/52720581/19371130) + SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); + } // Hive adapters Hive @@ -45,9 +78,20 @@ void main() async { ..registerAdapter(AppThemeAdapter()) ..registerAdapter(PrivateMessageAdapter()); + // Plaintext media from an interrupted playback or send must not survive a + // restart. + await MediaUtils.clearTempFiles(); + + // A disappearing message that expired while the app was closed is gone + // before the first frame: it must not flash up on start. + await CacheUtils.purgeExpiredMessages(); + + // Same for attachments the user asked to drop after a while. + await StorageUtils.purgeIfDue(); + // Default theme Singleton().appTheme = await CacheUtils.getTheme() ?? - AppTheme.fromValues(ThemeMode.system, Colors.blue, true); + AppTheme.fromValues(ThemeMode.system, Colors.blue); // Save theme await CacheUtils.setTheme(Singleton().appTheme); @@ -64,7 +108,7 @@ void main() async { supportedLocales: const [Locale('en'), Locale('cs')], path: 'assets/translations', fallbackLocale: const Locale('en'), - child: WhisperPage(), + child: SheptPage(), ), ), ); diff --git a/lib/models/app_theme.dart b/lib/models/app_theme.dart index b56e7bd..eca44bd 100644 --- a/lib/models/app_theme.dart +++ b/lib/models/app_theme.dart @@ -7,19 +7,16 @@ part 'app_theme.g.dart'; @HiveType(typeId: 2) class AppTheme { /// Constructor for Hive - AppTheme(this.themeModeStr, this.colorHex, this.useMaterial3); + AppTheme(this.themeModeStr, this.colorHex); @HiveField(0) String themeModeStr; // String of ThemeMode enum @HiveField(1) String colorHex; // Color hex - @HiveField(2) - bool useMaterial3; /// Factory constructor for user friendly usage - factory AppTheme.fromValues( - ThemeMode themeMode, Color color, bool material3) { - return AppTheme(themeMode.name, ColorUtils.colorToHex(color), material3); + factory AppTheme.fromValues(ThemeMode themeMode, Color color) { + return AppTheme(themeMode.name, ColorUtils.colorToHex(color)); } /// Get ThemeMode from themeModeStr diff --git a/lib/models/app_theme.g.dart b/lib/models/app_theme.g.dart index cd3c92a..75f40c0 100644 --- a/lib/models/app_theme.g.dart +++ b/lib/models/app_theme.g.dart @@ -19,20 +19,17 @@ class AppThemeAdapter extends TypeAdapter { return AppTheme( fields[0] as String, fields[1] as String, - fields[2] as bool, ); } @override void write(BinaryWriter writer, AppTheme obj) { writer - ..writeByte(3) + ..writeByte(2) ..writeByte(0) ..write(obj.themeModeStr) ..writeByte(1) - ..write(obj.colorHex) - ..writeByte(2) - ..write(obj.useMaterial3); + ..write(obj.colorHex); } @override diff --git a/lib/models/invite_data.dart b/lib/models/invite_data.dart index 20f0ec8..6697962 100644 --- a/lib/models/invite_data.dart +++ b/lib/models/invite_data.dart @@ -12,5 +12,6 @@ class InviteData { String code; DateTime validUntil; - factory InviteData.fromJson(Map json) => _$InviteDataFromJson(json); -} \ No newline at end of file + factory InviteData.fromJson(Map json) => + _$InviteDataFromJson(json); +} diff --git a/lib/models/invite_data.g.dart b/lib/models/invite_data.g.dart index 383e75d..86b0ef2 100644 --- a/lib/models/invite_data.g.dart +++ b/lib/models/invite_data.g.dart @@ -12,7 +12,6 @@ InviteData _$InviteDataFromJson(Map json) => InviteData( DateTime.parse(json['validUntil'] as String), ); -// ignore: unused_element Map _$InviteDataToJson(InviteData instance) => { 'url': instance.url, diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index d17289c..4a58b21 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -1,13 +1,120 @@ +import 'dart:convert'; + +import 'package:easy_localization/easy_localization.dart'; import 'package:hive/hive.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../utils/singleton.dart'; +import '../utils/text_envelope.dart'; part 'private_message.g.dart'; +/// Download status of a media attachment stored locally. +class MediaDownloadStatus { + /// Not yet downloaded/decrypted (recipient side, in progress). + static const int pending = 0; + + /// Downloaded, decrypted and stored encrypted-at-rest locally. + static const int ready = 1; + + /// Download or decryption failed; can be retried. + static const int failed = 2; + + /// The server no longer has the file: it was confirmed on another device, + /// expired, or the sender's account was cleaned up. Retrying cannot help. + static const int expired = 3; +} + +/// Outbound send state, shown as an icon in the bubble. +class SendStatus { + /// Written to the cache, not yet handed to the WebSocket. + static const int sending = 0; + + /// Handed to the WebSocket (there is no delivery receipt). + static const int sent = 1; + + /// The send failed; the message stays local with a failed marker. + static const int failed = 2; +} + +/// One attachment of an album message. Albums are stored as a JSON list on +/// [PrivateMessage.albumJson], so a new attachment type does not need a Hive +/// schema for every field. +class AlbumItem { + AlbumItem({ + required this.mediaId, + required this.type, + required this.size, + this.width, + this.height, + this.durationMs, + this.fileName, + this.keyB64, + this.localPath, + this.status = MediaDownloadStatus.ready, + }); + + String mediaId; + + /// [MediaType.name] of this item. + String type; + int size; + int? width; + int? height; + int? durationMs; + String? fileName; + + /// Base64 of the transport key of the attachment, kept so a caption can be + /// re-encrypted into a new envelope later. Null on rows stored before it was + /// kept. + String? keyB64; + + /// Encrypted-at-rest file on this device, null until downloaded/sent. + String? localPath; + int status; + + MediaType? get mediaType { + try { + return MediaType.values.byName(type); + } catch (_) { + return null; + } + } + + bool get isReady => status == MediaDownloadStatus.ready && localPath != null; + + Map toJson() => { + 'mediaId': mediaId, + 'type': type, + 'size': size, + if (width != null) 'width': width, + if (height != null) 'height': height, + if (durationMs != null) 'durationMs': durationMs, + if (fileName != null) 'fileName': fileName, + if (keyB64 != null) 'keyB64': keyB64, + if (localPath != null) 'localPath': localPath, + 'status': status, + }; + + static AlbumItem fromJson(Map json) => AlbumItem( + mediaId: json['mediaId'] as String, + type: json['type'] as String, + size: (json['size'] as num).toInt(), + width: (json['width'] as num?)?.toInt(), + height: (json['height'] as num?)?.toInt(), + durationMs: (json['durationMs'] as num?)?.toInt(), + fileName: json['fileName'] as String?, + keyB64: json['keyB64'] as String?, + localPath: json['localPath'] as String?, + status: (json['status'] as num?)?.toInt() ?? MediaDownloadStatus.ready, + ); +} + @HiveType(typeId: 3) class PrivateMessage extends HiveObject { @HiveField(0) - int senderId; + String senderId; @HiveField(1) String message; @HiveField(2) @@ -17,9 +124,409 @@ class PrivateMessage extends HiveObject { @HiveField(4) bool read; - PrivateMessage(this.senderId, this.message, this.sentAt, this.receivedAt, this.read); + // Media attachment fields (all null for plain text messages). + + /// Server-side media id (used for download/confirm). May be null once the + /// file has been confirmed/deleted on the server but kept locally. + @HiveField(5) + String? mediaId; + + /// [MediaType.name] of the attachment, or null for text messages and albums. + @HiveField(6) + String? mediaTypeStr; + + /// Absolute path to the encrypted-at-rest media file on the device. + @HiveField(7) + String? localPath; + + /// Size of the original (plaintext) media in bytes. + @HiveField(8) + int? mediaSize; + + /// Optional pixel width (images, gifs, videos). + @HiveField(9) + int? width; + + /// Optional pixel height (images, gifs, videos). + @HiveField(10) + int? height; + + /// Optional duration in milliseconds (videos, voice messages). + @HiveField(11) + int? durationMs; + + /// Download status, see [MediaDownloadStatus]. Defaults to ready (sent media). + @HiveField(12, defaultValue: MediaDownloadStatus.ready) + int downloadStatus; + + /// Original file name including the extension (documents etc.). + @HiveField(13) + String? fileName; + + /// Send state, see [SendStatus]. Old records default to sent. + @HiveField(14, defaultValue: SendStatus.sent) + int sendStatus; + + /// JSON list of [AlbumItem]s when this message carries more than one + /// attachment. Null for text and single-media messages. + @HiveField(15) + String? albumJson; + + /// Sender of the message this one quotes, null when it is not a reply. + @HiveField(16) + String? replyToSenderId; + + /// Client timestamp of the quoted message, null when it is not a reply. + @HiveField(17) + DateTime? replyToSentAt; + + /// Preview of the quoted message, kept here so the quote survives its + /// original being deleted on this device. + @HiveField(18) + String? replyToPreview; + + /// Archive id from the server, null for a message this device only ever sent + /// and for rows stored before the id was kept. Deleting on the server needs + /// it. + @HiveField(19) + String? id; + + /// Instant the sender last edited the text, null when it was never edited. + @HiveField(20) + DateTime? editedAt; + + /// Emoji reaction of each participant, keyed by user id. Null when nobody + /// reacted. + @HiveField(21) + Map? reactions; + + /// Whether the message was forwarded: the sender passed on somebody else's + /// text instead of writing it. + @HiveField(22, defaultValue: false) + bool forwarded; + + /// JSON of the media reference (id, key, type, size, metadata) for a single + /// attachment. Kept so editing the caption can build a new envelope without + /// the original upload; null on rows stored before it was kept. + @HiveField(23) + String? mediaRefJson; + + /// When the message must be gone from this device: the disappearing-message + /// deadline, or the view-once life. Null means the retention applies. + @HiveField(24) + DateTime? expiresAt; + + /// Set on a control message that carries no text: "propose", "accept" or + /// "decline" of a chat setting. Null on ordinary messages. + @HiveField(25) + String? systemState; + + /// Seconds carried by a control message. + @HiveField(26, defaultValue: 0) + int systemSeconds; + + /// A single-view attachment: opened once, then gone for both sides. + @HiveField(27, defaultValue: false) + bool viewOnce; + + /// JSON of a static location ({lat, lng, accuracy?, label?}) sent as a + /// message; null for everything else. + @HiveField(28) + String? locationJson; + + /// When the receiver opened this view-once attachment; null while it is still + /// unopened. Server-reported, so both sides see the same instant. + @HiveField(29) + DateTime? openedAt; + + /// When the sender deleted this message for everyone. The row stays as a + /// tombstone in the conversation, with no content left. + @HiveField(30) + DateTime? deletedAt; + + /// Cache for [album], keyed by the [albumJson] it was decoded from. + String? _albumCacheJson; + List? _albumCache; + + PrivateMessage( + this.senderId, + this.message, + this.sentAt, + this.receivedAt, + this.read, { + this.mediaId, + this.mediaTypeStr, + this.localPath, + this.mediaSize, + this.width, + this.height, + this.durationMs, + this.downloadStatus = MediaDownloadStatus.ready, + this.fileName, + this.sendStatus = SendStatus.sent, + this.albumJson, + this.replyToSenderId, + this.replyToSentAt, + this.replyToPreview, + this.editedAt, + this.reactions, + this.forwarded = false, + this.mediaRefJson, + this.expiresAt, + this.systemState, + this.systemSeconds = 0, + this.viewOnce = false, + this.locationJson, + this.openedAt, + this.deletedAt, + }); + + /// The static location carried by this message, null for everything else. + LocationRef? get location { + final raw = locationJson; + if (raw == null || raw.isEmpty) { + return null; + } + try { + return LocationRef.fromJson(jsonDecode(raw)); + } catch (_) { + return null; + } + } + + /// A control message: it carries a chat setting, not text to read. + bool get isSystem => systemState != null; + + /// True once the disappearing deadline of this message has passed. + bool get isExpired { + final deadline = expiresAt; + return deadline != null && deadline.isBefore(DateTime.now()); + } + + /// References needed to re-encrypt this message with a new caption, null for + /// text messages and when their key was never kept. + List? get mediaReferences { + if (isAlbum) { + final refs = []; + for (final item in album) { + final key = item.keyB64 == null ? null : base64Decode(item.keyB64!); + final type = item.mediaType; + if (key == null || type == null) { + return null; + } + refs.add(MediaReference(item.mediaId, key, type, item.size, + width: item.width, + height: item.height, + durationMs: item.durationMs, + fileName: item.fileName)); + } + return refs.isEmpty ? null : refs; + } + final raw = mediaRefJson; + if (raw == null || raw.isEmpty) { + return null; + } + try { + return [ + MediaReference.fromJson( + Map.from(jsonDecode(raw) as Map)) + ]; + } catch (_) { + return null; + } + } + + /// Whether this video was recorded as a round note. + /// + /// The flag rides in the media reference, which only exists once the upload + /// finished; while a note is still sending, the message carries a bare marker + /// written when the send started. + bool get isVideoNote { + final references = mediaReferences; + if (references != null && references.isNotEmpty) { + return references.first.videoNote; + } + final raw = mediaRefJson; + if (raw == null || raw.isEmpty) { + return false; + } + try { + final json = jsonDecode(raw); + return json is Map && json['videoNote'] == true; + } catch (_) { + return false; + } + } + + /// Whether the sender edited the text after sending it. + bool get isEdited => editedAt != null; + + /// Distinct reaction emoji, sorted so the chips do not jump around. + List get reactionEmojis => + (reactions?.values.toSet().toList() ?? [])..sort(); + + /// The quoted message, or null when this message is not a reply. + ReplyRef? get replyTo { + final senderId = replyToSenderId; + final sentAt = replyToSentAt; + if (senderId == null || sentAt == null) { + return null; + } + return ReplyRef( + senderId: senderId, + sentAt: sentAt, + preview: replyToPreview ?? '', + ); + } + + /// Stores (or clears) the message this one quotes. + void setReplyTo(ReplyRef? reply) { + replyToSenderId = reply?.senderId; + replyToSentAt = reply?.sentAt; + replyToPreview = reply?.preview; + } + + /// Whether this message quotes another one. + bool get isReply => replyToSentAt != null; + + /// Stored instead of the text when a message cannot be decrypted. It keeps a + /// visible gap in the chat, and the receiver only acks what it stored, so the + /// server still has the ciphertext. + static const String undecryptableMarker = '\uE000shept-undecryptable'; bool get isMe => senderId == Singleton().profile.user.id; + /// Whether the stored text is the placeholder of an undecryptable message. + bool get isUndecryptable => message == undecryptableMarker; + + /// Whether the sender deleted this message for everyone: the row stays as a + /// tombstone and carries nothing. + bool get isDeleted => deletedAt != null; + int get notificationId => receivedAt.microsecondsSinceEpoch % 0x7FFFFFFF; -} \ No newline at end of file + + /// Whether this message carries a media attachment (single or album). + bool get isMedia => mediaTypeStr != null || isAlbum; + + /// Whether this message is an album (more than one attachment). + bool get isAlbum => albumJson != null; + + /// Decoded album items, empty for non-album messages. + /// + /// Cached per [albumJson]: the getter is hit from previews, deletion paths + /// and album widgets, and decoding the JSON on every access is wasteful. + List get album { + final raw = albumJson; + if (raw == null) { + return const []; + } + if (raw == _albumCacheJson) { + return _albumCache ?? const []; + } + final decodedItems = _decodeAlbum(raw); + _albumCacheJson = raw; + _albumCache = decodedItems; + return decodedItems; + } + + List _decodeAlbum(String raw) { + try { + final decoded = jsonDecode(raw); + if (decoded is List) { + return decoded + .whereType() + .map((item) => AlbumItem.fromJson(Map.from(item))) + .toList(); + } + } catch (_) { + // Corrupted entry: behave like a message without attachments. + } + return const []; + } + + /// Replaces the album items and serializes them back into [albumJson]. + void setAlbum(List items) { + albumJson = jsonEncode(items.map((item) => item.toJson()).toList()); + _albumCacheJson = null; + _albumCache = null; + } + + /// Local (encrypted-at-rest) files of this message, for deletion. + List get localPaths { + final paths = []; + if (localPath != null) { + paths.add(localPath!); + } + for (final item in album) { + if (item.localPath != null) { + paths.add(item.localPath!); + } + } + return paths; + } + + /// The decoded [MediaType] of the attachment, or null for text and albums. + MediaType? get mediaType { + if (albumJson != null || mediaTypeStr == null) { + return null; + } + try { + return MediaType.values.byName(mediaTypeStr!); + } catch (_) { + return null; + } + } + + /// Short text used in chat list previews and notifications. Falls back to a + /// localized media label when a media message has no caption. + String get preview { + if (isDeleted) { + return 'messageDeleted'.tr(); + } + if (isUndecryptable) { + return 'messageUndecryptable'.tr(); + } + if (isSystem) { + return 'disappearingChanged'.tr(); + } + // A view-once message never shows its content in a list: not its caption, + // not the coordinates of a location, before or after it is opened. + if (viewOnce) { + return openedAt == null ? 'viewOnceMedia'.tr() : 'viewOnceOpened'.tr(); + } + final location = this.location; + if (location != null) { + // Without the pin: a map marker belongs in the bubble, not in a one-line + // summary, and rows stored by an older build keep their emoji in the text. + return '${location.lat.toStringAsFixed(5)}, ' + '${location.lng.toStringAsFixed(5)}'; + } + return _previewText; + } + + /// The untrimmed preview: the text, or a media label when there is none. + String get _previewText { + if (!isMedia || message.isNotEmpty) { + return message; + } + if (isAlbum) { + return '${'mediaAlbum'.tr()} (${album.length})'; + } + switch (mediaType) { + case MediaType.image: + return 'mediaPhoto'.tr(); + case MediaType.gif: + return 'mediaGif'.tr(); + case MediaType.video: + return 'mediaVideo'.tr(); + case MediaType.voice: + return 'mediaVoice'.tr(); + case MediaType.file: + return fileName ?? 'mediaFile'.tr(); + case MediaType.sticker: + return 'mediaSticker'.tr(); + case null: + return message; + } + } +} diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 63de9c4..b0483ed 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -17,18 +17,43 @@ class PrivateMessageAdapter extends TypeAdapter { for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return PrivateMessage( - fields[0] as int, + fields[0] as String, fields[1] as String, fields[2] as DateTime, fields[3] as DateTime, fields[4] as bool, - ); + mediaId: fields[5] as String?, + mediaTypeStr: fields[6] as String?, + localPath: fields[7] as String?, + mediaSize: fields[8] as int?, + width: fields[9] as int?, + height: fields[10] as int?, + durationMs: fields[11] as int?, + downloadStatus: fields[12] == null ? 1 : fields[12] as int, + fileName: fields[13] as String?, + sendStatus: fields[14] == null ? 1 : fields[14] as int, + albumJson: fields[15] as String?, + replyToSenderId: fields[16] as String?, + replyToSentAt: fields[17] as DateTime?, + replyToPreview: fields[18] as String?, + editedAt: fields[20] as DateTime?, + reactions: (fields[21] as Map?)?.cast(), + forwarded: fields[22] == null ? false : fields[22] as bool, + mediaRefJson: fields[23] as String?, + expiresAt: fields[24] as DateTime?, + systemState: fields[25] as String?, + systemSeconds: fields[26] == null ? 0 : fields[26] as int, + viewOnce: fields[27] == null ? false : fields[27] as bool, + locationJson: fields[28] as String?, + openedAt: fields[29] as DateTime?, + deletedAt: fields[30] as DateTime?, + )..id = fields[19] as String?; } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(5) + ..writeByte(31) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -38,7 +63,59 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(3) ..write(obj.receivedAt) ..writeByte(4) - ..write(obj.read); + ..write(obj.read) + ..writeByte(5) + ..write(obj.mediaId) + ..writeByte(6) + ..write(obj.mediaTypeStr) + ..writeByte(7) + ..write(obj.localPath) + ..writeByte(8) + ..write(obj.mediaSize) + ..writeByte(9) + ..write(obj.width) + ..writeByte(10) + ..write(obj.height) + ..writeByte(11) + ..write(obj.durationMs) + ..writeByte(12) + ..write(obj.downloadStatus) + ..writeByte(13) + ..write(obj.fileName) + ..writeByte(14) + ..write(obj.sendStatus) + ..writeByte(15) + ..write(obj.albumJson) + ..writeByte(16) + ..write(obj.replyToSenderId) + ..writeByte(17) + ..write(obj.replyToSentAt) + ..writeByte(18) + ..write(obj.replyToPreview) + ..writeByte(19) + ..write(obj.id) + ..writeByte(20) + ..write(obj.editedAt) + ..writeByte(21) + ..write(obj.reactions) + ..writeByte(22) + ..write(obj.forwarded) + ..writeByte(23) + ..write(obj.mediaRefJson) + ..writeByte(24) + ..write(obj.expiresAt) + ..writeByte(25) + ..write(obj.systemState) + ..writeByte(26) + ..write(obj.systemSeconds) + ..writeByte(27) + ..write(obj.viewOnce) + ..writeByte(28) + ..write(obj.locationJson) + ..writeByte(29) + ..write(obj.openedAt) + ..writeByte(30) + ..write(obj.deletedAt); } @override diff --git a/lib/models/user.dart b/lib/models/user.dart index f590509..3b92716 100644 --- a/lib/models/user.dart +++ b/lib/models/user.dart @@ -1,7 +1,7 @@ import 'dart:ui'; import 'package:hive/hive.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../utils/color_utils.dart'; @@ -15,7 +15,7 @@ class User extends HiveObject { } @HiveField(0) - int id; + String id; @HiveField(1) String username; @HiveField(2) diff --git a/lib/models/user.g.dart b/lib/models/user.g.dart index 5eb6eb4..a25cbe9 100644 --- a/lib/models/user.g.dart +++ b/lib/models/user.g.dart @@ -17,7 +17,7 @@ class UserAdapter extends TypeAdapter { for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return User( - fields[0] as int, + fields[0] as String, fields[1] as String, fields[2] as String, fields[3] as bool, diff --git a/lib/pages/camera_page.dart b/lib/pages/camera_page.dart new file mode 100644 index 0000000..65ebf8b --- /dev/null +++ b/lib/pages/camera_page.dart @@ -0,0 +1,368 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:camera/camera.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +/// In-app camera: tap the shutter for a photo, hold it to record a video. +/// +/// Returns the captured file from [open], or null when the user backs out. The +/// caller detects whether it is a photo or a video, so the chat handles it like +/// any other attachment. +class CameraPage extends StatefulWidget { + const CameraPage({super.key}); + + /// Longest clip the shutter records, same as the picker used to allow. + static const Duration maxVideoLength = Duration(seconds: 60); + + static Future open(BuildContext context) { + return Navigator.push( + context, + MaterialPageRoute( + builder: (_) => const CameraPage(), fullscreenDialog: true)); + } + + @override + State createState() => _CameraPageState(); +} + +class _CameraPageState extends State with WidgetsBindingObserver { + List _cameras = const []; + CameraController? _controller; + bool _flashOn = false; + bool _recording = false; + bool _busy = false; + Duration _elapsed = Duration.zero; + Timer? _timer; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + // The camera is the one screen that follows the phone: a photo taken on a + // turned phone is a landscape photo. Everything else stays portrait. + SystemChrome.setPreferredOrientations(const [ + DeviceOrientation.portraitUp, + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]); + _openCamera(); + } + + Future _openCamera({bool front = false}) async { + try { + if (_cameras.isEmpty) { + _cameras = await availableCameras(); + } + if (_cameras.isEmpty) { + throw CameraException('noCamera', 'no camera on this device'); + } + // Whatever the caller asked for, falling back to the first camera keeps a + // single-camera device usable. + final wanted = + front ? CameraLensDirection.front : CameraLensDirection.back; + final camera = _cameras.firstWhere( + (entry) => entry.lensDirection == wanted, + orElse: () => _cameras.first, + ); + final controller = + CameraController(camera, ResolutionPreset.high, enableAudio: true); + await controller.initialize(); + await controller.setFlashMode(_flashOn ? FlashMode.torch : FlashMode.off); + if (!mounted) { + await controller.dispose(); + return; + } + setState(() => _controller = controller); + } catch (_) { + if (mounted) { + await Fluttertoast.showToast( + msg: 'cameraUnavailable'.tr(), backgroundColor: Colors.red); + Navigator.pop(context); + } + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + // The plugin does not park the camera by itself: left running in the + // background it keeps the camera light on and the next open fails. + final controller = _controller; + if (controller == null || !controller.value.isInitialized) { + return; + } + if (state == AppLifecycleState.inactive) { + controller.dispose(); + setState(() => _controller = null); + } else if (state == AppLifecycleState.resumed) { + _openCamera(front: false); + } + } + + Future _switchCamera() async { + if (_recording || _busy) { + return; + } + final front = _cameras.isNotEmpty && + _controller?.description.lensDirection == CameraLensDirection.front; + await _controller?.dispose(); + setState(() => _controller = null); + await _openCamera(front: !front); + } + + Future _toggleFlash() async { + if (_recording) { + return; + } + final on = !_flashOn; + try { + await _controller?.setFlashMode(on ? FlashMode.torch : FlashMode.off); + } catch (_) { + return; + } + if (mounted) { + setState(() => _flashOn = on); + } + } + + Future _takePhoto() async { + final controller = _controller; + if (controller == null || _busy || _recording) { + return; + } + setState(() => _busy = true); + try { + final captured = await controller.takePicture(); + if (mounted) { + Navigator.pop(context, File(captured.path)); + } + } catch (_) { + if (mounted) { + await Fluttertoast.showToast( + msg: 'captureFailed'.tr(), backgroundColor: Colors.red); + setState(() => _busy = false); + } + } + } + + Future _startVideo() async { + final controller = _controller; + if (controller == null || _busy || _recording) { + return; + } + try { + await controller.startVideoRecording(); + } catch (_) { + return; + } + setState(() { + _recording = true; + _elapsed = Duration.zero; + }); + _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (!mounted) { + return; + } + setState(() => _elapsed += const Duration(seconds: 1)); + if (_elapsed >= CameraPage.maxVideoLength) { + _stopVideo(); + } + }); + } + + Future _stopVideo() async { + _timer?.cancel(); + _timer = null; + final controller = _controller; + if (controller == null || !_recording) { + return; + } + setState(() => _recording = false); + try { + final captured = await controller.stopVideoRecording(); + if (mounted) { + Navigator.pop(context, File(captured.path)); + } + } catch (_) { + if (mounted) { + setState(() => _busy = false); + } + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _timer?.cancel(); + _controller?.dispose(); + SystemChrome.setPreferredOrientations(const [DeviceOrientation.portraitUp]); + super.dispose(); + } + + String _format(Duration duration) { + final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + final portrait = MediaQuery.orientationOf(context) == Orientation.portrait; + return Scaffold( + backgroundColor: Colors.black, + body: Stack( + fit: StackFit.expand, + children: [ + if (controller != null && controller.value.isInitialized) + _preview(controller) + else + const Center(child: CircularProgressIndicator()), + SafeArea( + child: portrait + ? Column( + children: [ + _topBar(showTimer: true), + const Spacer(), + _shutter(), + const SizedBox(height: 40), + ], + ) + // Turned to the side, the shutter moves to the right edge where + // the thumb rests, the way the system camera does it. + : Stack( + children: [ + Align( + alignment: Alignment.topCenter, + child: _topBar(showTimer: false), + ), + Align( + alignment: Alignment.centerRight, + child: Padding( + padding: const EdgeInsets.only(right: 32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_recording) _timerChip(), + _shutter(), + ], + ), + ), + ), + ], + ), + ), + ], + ), + ); + } + + Widget _topBar({required bool showTimer}) { + return Row( + children: [ + IconButton( + color: Colors.white, + onPressed: () => Navigator.pop(context), + icon: const Icon(Icons.close), + ), + const Spacer(), + if (showTimer && _recording) _timerChip(), + IconButton( + color: _flashOn ? Colors.amber : Colors.white, + onPressed: _toggleFlash, + icon: Icon(_flashOn ? Icons.flash_on : Icons.flash_off), + ), + IconButton( + color: Colors.white, + onPressed: _switchCamera, + icon: const Icon(Icons.cameraswitch), + ), + ], + ); + } + + Widget _timerChip() { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.fiber_manual_record, color: Colors.red, size: 14), + const SizedBox(width: 6), + Text( + '${_format(_elapsed)} / ${_format(CameraPage.maxVideoLength)}', + style: const TextStyle(color: Colors.white), + ), + ], + ), + ); + } + + /// The sensor reports a landscape frame; on a turned phone the sides swap, so + /// the fill has to cover the screen instead of sitting in a letterboxed band. + Widget _preview(CameraController controller) { + final portrait = MediaQuery.orientationOf(context) == Orientation.portrait; + final aspect = controller.value.aspectRatio; + final width = portrait ? 1 / aspect : aspect; + return SizedBox.expand( + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: width * 1000, + height: 1000, + child: CameraPreview(controller), + ), + ), + ); + } + + /// Tap takes a photo, holding records a video until it is released. + Widget _shutter() { + return GestureDetector( + onTap: _takePhoto, + onLongPressStart: (_) => _startVideo(), + onLongPressEnd: (_) => _stopVideo(), + child: _shutterButton(), + ); + } + + Widget _shutterButton() { + return Container( + width: 78, + height: 78, + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 4), + ), + padding: const EdgeInsets.all(6), + child: _busy + ? const Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2))) + // Recording: a small stop square inside the ring, so the button keeps + // its size and only the glyph changes. + : _recording + ? Center( + child: Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: Colors.red, + borderRadius: BorderRadius.circular(5), + ), + ), + ) + : const DecoratedBox( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: Colors.white, + ), + ), + ); + } +} diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index c8ac05b..94ee029 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -1,68 +1,466 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import '../utils/nav_transitions.dart'; +import '../utils/cache_utils.dart'; +import '../utils/chat_sender.dart'; +import '../utils/disappearing.dart'; +import '../utils/media_utils.dart'; +import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/dialog_utils.dart'; +import '../utils/utils.dart'; +import '../utils/storage_utils.dart'; +import '../utils/theme_utils.dart'; +import '../widgets/settings_tile.dart'; +import 'chat_media_page.dart'; +import 'storage_page.dart'; import 'home_page.dart'; +import 'search_page.dart'; class ChatInfoPage extends StatefulWidget { - const ChatInfoPage(this.userId,{super.key}); - final int userId; + const ChatInfoPage(this.userId, {super.key}); + final String userId; @override State createState() => _ChatInfoPageState(); } class _ChatInfoPageState extends State { + Color? _chatThemeColor; + Map _pins = {}; + bool _readReceipts = false; + + /// Agreed disappearing-message timer of this chat, seconds; 0 when off. + int _disappearing = 0; + + /// Timer the peer proposed and this device has not answered yet. + int? _disappearingProposal; + + /// Bytes this conversation keeps on this device. + int _mediaBytes = 0; + + /// A toggle in flight: the switch stays disabled until the server call and + /// the cache write are done, so it cannot be flipped back and forth. + bool _readReceiptsBusy = false; @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: Text('chatInfoPage'.tr()), - ), - body: SafeArea( - child: Column( + void initState() { + super.initState(); + _loadChatTheme(); + _loadPins(); + _loadReadReceipts(); + _loadDisappearing(); + _loadMediaUsage(); + } + + Future _loadMediaUsage() async { + final usage = await StorageUtils.usageFor(widget.userId); + if (mounted) { + setState(() => _mediaBytes = usage.bytes); + } + } + + Future _loadDisappearing() async { + final agreed = await CacheUtils.getDisappearingSeconds(widget.userId); + final proposal = await CacheUtils.getDisappearingProposal(widget.userId); + if (mounted) { + setState(() { + _disappearing = agreed; + _disappearingProposal = proposal; + }); + } + } + + /// A timer is agreed by both sides: this device only ever proposes, and the + /// peer's proposal is what the accept row answers. + Future _showDisappearingDialog() async { + final proposal = _disappearingProposal; + final chosen = await showDialog( + context: context, + builder: (ctx) => _chatThemed(SimpleDialog( + title: Text('disappearingSettings'.tr()), + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(24, 0, 24, 8), + child: Text('disappearingHint'.tr()), + ), + if (proposal != null) + ListTile( + leading: const Icon(Icons.check), + title: Text( + 'disappearingAccept'.tr(args: [disappearingLabel(proposal)])), + onTap: () => Navigator.pop(ctx, proposal), + ), + if (proposal != null) + ListTile( + leading: const Icon(Icons.close), + title: Text('disappearingDecline'.tr()), + onTap: () => Navigator.pop(ctx, -1), + ), + const Divider(), + for (final option in disappearingOptions) + ListTile( + title: Text(disappearingLabel(option)), + trailing: option == _disappearing + ? const Icon(Icons.check) + : (option == proposal ? const Icon(Icons.schedule) : null), + onTap: () => Navigator.pop(ctx, option), + ), + ], + )), + ); + if (chosen == null) { + return; + } + final user = await CacheUtils.getUserById(widget.userId); + if (user == null) { + return; + } + if (chosen == -1) { + await CacheUtils.setDisappearingProposal(widget.userId, null); + await ChatSender.sendSystem(user, 'decline', 0); + } else if (proposal != null && chosen == proposal) { + await CacheUtils.setDisappearingSeconds(widget.userId, chosen); + await CacheUtils.setDisappearingProposal(widget.userId, null); + await ChatSender.sendSystem(user, 'accept', chosen); + } else { + // Nothing changes until the peer accepts, so a proposal is never a new + // local timer on its own. + await ChatSender.sendSystem(user, 'propose', chosen); + } + await _loadDisappearing(); + MessageNotifier().notify(); + } + + Future _loadReadReceipts() async { + final enabled = await CacheUtils.isReadReceiptsEnabled(widget.userId); + if (mounted) { + setState(() { + _readReceipts = enabled; + }); + } + } + + /// Turns receipts of this chat on or off. Turning them on publishes the + /// current cursor right away, so the peer's ticks catch up without waiting + /// for the next message. + Future _toggleReadReceipts(bool enabled) async { + if (_readReceiptsBusy) { + return; + } + setState(() { + _readReceiptsBusy = true; + _readReceipts = enabled; + }); + try { + await CacheUtils.setReadReceiptsEnabled(widget.userId, enabled); + if (enabled) { + final messages = await CacheUtils.getPrivateMessages(widget.userId); + if (messages.isNotEmpty) { + await Utils.sendReadCursor(widget.userId, messages.last.sentAt); + } + } + await _loadReadReceipts(); + } finally { + if (mounted) { + setState(() => _readReceiptsBusy = false); + } + } + } + + Future _loadPins() async { + final pins = await CacheUtils.getPinnedMessages(widget.userId); + if (mounted) { + setState(() { + _pins = pins; + }); + } + } + + /// Pinned messages of this chat, newest pin first, with an unpin per row. + Future _openPinned() async { + final messages = await CacheUtils.getPrivateMessages(widget.userId); + final pins = await CacheUtils.getPinnedMessages(widget.userId); + final pinned = messages + .where((message) => message.id != null && pins.containsKey(message.id)) + .toList() + ..sort((a, b) => pins[b.id]!.compareTo(pins[a.id]!)); + if (!mounted) { + return; + } + await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) => _chatThemed(SafeArea( + child: ListView( + shrinkWrap: true, children: [ - // TODO Theme - - // TODO Media - - // Delete chat - TextButton( - onPressed: () async { - await DialogUtils.yesNoDialog(context, 'deleteChatConfirm'.tr(), - 'deleteChatConfirmText'.tr(), () async { - MessageNotifier().deleteChat(widget.userId); - // Redirect to home page and clear navigation stack - Navigator.pushAndRemoveUntil( - context, - MaterialPageRoute(builder: (context) => const HomePage()), - (route) => false, - ); - }); - }, - child: Row( - children: [ - Icon( - Icons.delete_forever, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'deleteChat'.tr(), - style: TextStyle(color: Colors.red), - ), - ), - SizedBox( - width: 24, - ), - ], + if (pinned.isEmpty) ListTile(title: Text('noPinnedMessages'.tr())), + for (final message in pinned) + ListTile( + leading: const Icon(Icons.push_pin), + title: Text( + message.preview.isEmpty ? 'mediaPhoto'.tr() : message.preview, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text(DateFormat.yMMMd() + .add_Hm() + .format(message.sentAt.toLocal())), + // Hands the instant back to the chat, which scrolls to it and + // flashes the bubble. + onTap: () { + Navigator.pop(ctx); + Navigator.pop(context, message.sentAt); + }, + trailing: IconButton( + icon: const Icon(Icons.close), + tooltip: 'unpinMessage'.tr(), + onPressed: () async { + await MessageActions.togglePin(message, widget.userId, + pinned: true); + if (ctx.mounted) { + Navigator.pop(ctx); + } + await _loadPins(); + }, + ), ), - ), ], ), + )), + ); + } + + /// Routes, sheets and dialogs opened from this page are pushed on the + /// Navigator, above the Theme this page is wrapped in, so each of them has to + /// carry the chat theme itself or it falls back to the app theme. + ThemeData get _chatTheme => ThemeUtils.chatTheme(context, _chatThemeColor); + + Widget _chatThemed(Widget child) => Theme(data: _chatTheme, child: child); + + Future _loadChatTheme() async { + Color? color = await CacheUtils.getChatTheme(widget.userId); + if (mounted) { + setState(() { + _chatThemeColor = color; + }); + } + } + + /// Opens the attachments of this chat on a page of their own. + void _openMedia() { + Navigator.of(context).push(fadeRoute( + ChatMediaPage(widget.userId, chatThemeColor: _chatThemeColor))); + } + + /// Open the chat theme dialog: the same palette as the app theme, applied + /// live. The dialog is themed with the chat color, so it previews itself. + Future _pickChatTheme() async { + await showDialog( + context: context, + builder: (dialogContext) => Theme( + data: ThemeUtils.chatTheme(context, _chatThemeColor), + child: Builder( + builder: (themedContext) => DialogUtils.chatThemeDialog( + themedContext, + current: _chatThemeColor, + onChanged: _applyChatTheme, + ), + ), + )); + await _loadChatTheme(); + } + + /// Stores the picked chat color; null falls back to the global theme. + Future _applyChatTheme(Color? color) async { + if (color == null) { + await CacheUtils.clearChatTheme(widget.userId); + } else { + await CacheUtils.setChatTheme(widget.userId, color); + } + } + + /// Pick a day and hand it back to the chat page, which jumps to the first + /// message of that day (or the first one after it). + Future _jumpToDate() async { + final now = DateTime.now(); + final picked = await showDatePicker( + context: context, + initialDate: now, + firstDate: DateTime(now.year - 10), + lastDate: now, + builder: (ctx, child) => _chatThemed(child ?? const SizedBox.shrink()), + ); + if (picked != null && mounted) { + Navigator.pop(context, picked); + } + } + + /// Search this conversation. A picked hit is handed back to the chat page, + /// which jumps to it. + Future _openSearch() async { + final user = await CacheUtils.getUserById(widget.userId); + if (user == null || !mounted) { + return; + } + final picked = await Navigator.of(context) + .push(stepRoute(_chatThemed(MessageSearchPage(user)))); + if (picked != null && mounted) { + Navigator.pop(context, picked); + } + } + + @override + Widget build(BuildContext context) { + return Theme( + data: ThemeUtils.chatTheme(context, _chatThemeColor), + child: Scaffold( + appBar: AppBar( + title: Text('chatInfoPage'.tr()), + ), + body: SafeArea( + child: CustomScrollView( + slivers: [ + SliverToBoxAdapter( + child: Column( + children: [ + // Search in this conversation + SettingsTile( + icon: Icons.search, + label: 'searchInChat'.tr(), + onPressed: _openSearch, + ), + // Jump to a day + SettingsTile( + icon: Icons.event, + label: 'jumpToDate'.tr(), + onPressed: _jumpToDate, + ), + // Read receipts: off by default, one switch for both + // directions of this chat + SettingsTile( + icon: Icons.done_all, + label: 'readReceipts'.tr(), + // Tap on the row toggles too; a non-null handler keeps + // the row in the enabled colours (a disabled TextButton + // greys out its icon and label). + onPressed: () => _toggleReadReceipts(!_readReceipts), + trailing: Switch( + value: _readReceipts, + onChanged: + _readReceiptsBusy ? null : _toggleReadReceipts, + ), + ), + // How much this chat costs on disk, and the way to free it + SettingsTile( + icon: Icons.storage, + label: 'storageTitle'.tr(), + onPressed: () async { + await Navigator.push(context, + stepRoute(_chatThemed(const StoragePage()))); + await _loadMediaUsage(); + }, + extra: Padding( + padding: const EdgeInsets.only(left: 10), + child: Text(MediaUtils.formatBytes(_mediaBytes)), + ), + ), + // Pinned messages, shared with the other participant + SettingsTile( + icon: Icons.push_pin, + label: 'pinnedMessages'.tr(), + onPressed: _openPinned, + extra: _pins.isEmpty + ? null + : Padding( + padding: const EdgeInsets.only(left: 10), + child: Text('${_pins.length}'), + ), + ), + // Attachments of this chat: a page of their own. + SettingsTile( + icon: Icons.photo_library_outlined, + label: 'mediaTitle'.tr(), + onPressed: _openMedia, + ), + // Disappearing messages: a timer both sides agree on. + SettingsTile( + icon: Icons.timer_outlined, + label: 'disappearingSettings'.tr(), + onPressed: _showDisappearingDialog, + extra: Padding( + padding: const EdgeInsets.only(left: 10), + child: Text(_disappearingProposal != null + ? 'disappearingProposalShort'.tr(args: [ + disappearingLabel(_disappearingProposal!) + ]) + : disappearingLabel(_disappearing)), + ), + ), + // Chat theme + SettingsTile( + icon: Icons.palette, + label: 'chatTheme'.tr(), + onPressed: _pickChatTheme, + extra: _chatThemeColor == null + ? null + : Padding( + padding: const EdgeInsets.only(left: 10), + child: Container( + width: 16, + height: 16, + decoration: BoxDecoration( + color: _chatThemeColor, + shape: BoxShape.circle, + ), + ), + ), + ), + Divider(thickness: 1, indent: 10, endIndent: 10), + ], + ), + ), + SliverToBoxAdapter( + child: Column( + children: [ + // Delete chat + SettingsTile( + icon: Icons.delete_forever, + label: 'deleteChat'.tr(), + color: Colors.red, + onPressed: () async { + await DialogUtils.yesNoDialog( + context, + 'deleteChatConfirm'.tr(), + 'deleteChatConfirmText'.tr(), () async { + final deleted = + await MessageNotifier().deleteChat(widget.userId); + if (!deleted) { + Fluttertoast.showToast( + msg: 'deleteChatFailed'.tr(), + backgroundColor: Colors.red); + return; + } + if (!context.mounted) { + return; + } + // Redirect to home page and clear navigation stack + Navigator.pushAndRemoveUntil( + context, + fadeRoute(const HomePage()), + (route) => false, + ); + }, theme: _chatTheme); + }, + ), + ], + ), + ), + ], + ), + ), ), ); } diff --git a/lib/pages/chat_media_page.dart b/lib/pages/chat_media_page.dart new file mode 100644 index 0000000..f9797b4 --- /dev/null +++ b/lib/pages/chat_media_page.dart @@ -0,0 +1,217 @@ +import 'dart:typed_data'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; +import '../models/private_message.dart'; +import '../utils/cache_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/message_notifier.dart'; +import '../utils/nav_transitions.dart'; +import '../utils/theme_utils.dart'; +import '../widgets/media_bubble.dart'; +import 'media_viewer_page.dart'; + +/// Every attachment of one chat this device can open, newest first. +class ChatMediaPage extends StatefulWidget { + const ChatMediaPage(this.userId, {super.key, this.chatThemeColor}); + + final String userId; + + /// The chat's own color, so the grid and the viewer open in it. + final Color? chatThemeColor; + + @override + State createState() => _ChatMediaPageState(); +} + +class _ChatMediaPageState extends State { + List _media = []; + + @override + void initState() { + super.initState(); + _loadMedia(); + } + + Future _loadMedia() async { + List messages = + await CacheUtils.getPrivateMessages(widget.userId); + if (mounted) { + setState(() { + _media = MessageNotifier.viewableMedia(messages); + }); + } + } + + void _openMedia(PrivateMessage message) { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + return; + } + Navigator.of(context).push( + fadeRoute( + // The viewer is a separate route, so it needs the chat theme passed in + Theme( + data: ThemeUtils.chatTheme(context, widget.chatThemeColor), + child: MediaViewerPage( + message: message, + conversationUserId: widget.userId, + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Theme( + data: ThemeUtils.chatTheme(context, widget.chatThemeColor), + child: Scaffold( + appBar: AppBar( + title: Text('mediaTitle'.tr()), + ), + body: SafeArea( + child: _media.isEmpty + ? Center( + child: Text( + 'noMedia'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ) + // A sliver grid, so only the visible tiles decrypt. + : GridView.builder( + padding: const EdgeInsets.symmetric(horizontal: 8), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + mainAxisSpacing: 4, + crossAxisSpacing: 4, + ), + itemCount: _media.length, + itemBuilder: (context, index) => _MediaTile( + message: _media[index], + onTap: () => _openMedia(_media[index]), + ), + ), + ), + ), + ); + } +} + +/// Square thumbnail of one shared media message. +class _MediaTile extends StatefulWidget { + const _MediaTile({required this.message, required this.onTap}); + + final PrivateMessage message; + final VoidCallback onTap; + + @override + State<_MediaTile> createState() => _MediaTileState(); +} + +class _MediaTileState extends State<_MediaTile> { + Uint8List? _bytes; + bool _error = false; + + @override + void initState() { + super.initState(); + _loadImage(); + } + + Future _loadImage() async { + // Videos get a first-frame thumbnail; documents show an icon. + if (widget.message.mediaType == MediaType.video || + widget.message.mediaType == MediaType.file) { + return; + } + final path = widget.message.localPath; + if (path == null) { + return; + } + try { + Uint8List bytes = await MediaUtils.decryptAtRest(path); + if (mounted) { + setState(() { + _bytes = bytes; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _error = true; + }); + } + } + } + + /// One tile of the three-column grid, gaps and padding taken off. + double get _tileWidth => (MediaQuery.sizeOf(context).width - 24) / 3; + + @override + Widget build(BuildContext context) { + final isVideo = widget.message.mediaType == MediaType.video; + final isFile = widget.message.mediaType == MediaType.file; + return GestureDetector( + onTap: widget.onTap, + child: Container( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: isVideo + ? _videoTile() + : _bytes != null + ? Image.memory(_bytes!, + fit: BoxFit.cover, + // Tile-sized decode: a full-resolution photo per square is + // 40+ MB of bitmap and a visible hitch while scrolling. + cacheWidth: MediaUtils.decodeWidth(context, _tileWidth)) + : Center( + child: _error + ? const Icon(Icons.broken_image, size: 24) + : isFile + ? _fileTile() + : const SizedBox( + width: 18, + height: 18, + child: + CircularProgressIndicator(strokeWidth: 2), + ), + ), + ), + ); + } + + /// Video: first frame with a play badge. + Widget _videoTile() { + return Stack( + fit: StackFit.expand, + children: [ + VideoThumbnail(path: widget.message.localPath), + const Center( + child: Icon(Icons.play_arrow, color: Colors.white, size: 28), + ), + ], + ); + } + + /// Documents: extension badge instead of a thumbnail. + Widget _fileTile() { + final name = widget.message.fileName ?? ''; + final dot = name.lastIndexOf('.'); + final extension = + dot > 0 && dot < name.length - 1 ? name.substring(dot + 1) : ''; + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(MediaUtils.iconForFileName(widget.message.fileName), size: 24), + if (extension.isNotEmpty) + Text( + extension.toUpperCase(), + style: const TextStyle(fontSize: 10, fontWeight: FontWeight.bold), + ), + ], + ); + } +} diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 0b8e8af..b04748f 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1,23 +1,45 @@ -import 'dart:convert'; -import 'dart:typed_data'; +import 'dart:async'; +import 'dart:io'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:camera/camera.dart' show CameraPreview; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:page_transition/page_transition.dart'; -import 'package:provider/provider.dart'; -import 'package:whisper_websocket_client_dart/models/new_private_message.dart'; -import 'package:whisper_websocket_client_dart/models/ws_message.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:sprintf/sprintf.dart'; +import '../utils/dialog_utils.dart'; +import '../utils/nav_transitions.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; -import '../utils/crypto_utils.dart'; +import '../utils/chat_scroll.dart'; +import '../utils/chat_sender.dart'; +import '../utils/live_location.dart'; +import '../utils/media_utils.dart'; +import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; +import '../utils/round_note_playback.dart'; +import '../utils/presence.dart'; +import '../utils/round_video_recorder.dart'; +import '../utils/sticker_store.dart'; import '../utils/singleton.dart'; -import '../utils/utils.dart'; +import '../utils/text_envelope.dart'; +import '../utils/utils.dart' as utils; +import '../utils/theme_utils.dart'; +import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; -import 'package:basic_utils/basic_utils.dart' as bu; +import '../widgets/pinned_round_note.dart'; +import '../widgets/live_location_bubble.dart'; +import '../widgets/typing_dots.dart'; +import 'camera_page.dart'; import 'chat_info_page.dart'; +import '../widgets/sticker_sheet.dart'; +import 'image_editor_page.dart'; +import 'video_trim_page.dart'; +import 'forward_page.dart'; class ChatPage extends StatefulWidget { const ChatPage(this.user, {super.key}); @@ -30,167 +52,2293 @@ class ChatPage extends StatefulWidget { // Transaprent AppBar: https://ckreymborg.medium.com/how-to-create-a-glassmorphism-frosted-glass-appbar-in-flutter-fb217ce1b4ca class _ChatPageState extends State { + /// Messages added per scroll-up step (incremental loading). + static const int _pageSize = 30; + // Add controller for text input final TextEditingController _controllerMessage = TextEditingController(); // Add list for messages List _messages = []; + // How many of the newest messages are rendered + int _visibleCount = _pageSize; // Buttons bool _isSending = false; // ScrollController for content final ScrollController _scrollController = ScrollController(); + // The round note that keeps playing (and floats top right) while its circle + // is out of sight; one per open chat. + final RoundNotePlayback _notePlayback = RoundNotePlayback(); // Indicates whether messages are being load for the first time bool _firstLoad = true; + // Guards against overlapping cache reads + bool _loading = false; + // A change arrived mid-read: run one more pass when it ends + bool _reloadRequested = false; + // True only around our own read, which notifies on purpose (home list row) + bool _selfRead = false; + // Guards against overlapping history requests + bool _historyLoading = false; + // Guards against overlapping "grow the window upwards" passes + bool _growing = false; + // A jump walks the list itself; window growth would move the offset under it + bool _jumping = false; + // Whether the newest archive page was already asked for + bool _historyLoaded = false; + // Cursor for the next (older) archive page, null when the archive ends + String? _historyCursor; + // Voice recording state + bool _isRecording = false; + bool _recordingStarting = false; + bool _stopRequested = false; + + /// Sliding up while recording locks it: the finger can be lifted and the + /// recording keeps going until the bar's stop button is tapped. + bool _recordingLocked = false; + + /// Round video note started by holding the composer's camera button. It lives + /// only as long as the finger is down. + RoundVideoRecorder? _noteRecorder; + bool _isRecordingNote = false; + bool _noteStarting = false; + bool _noteStopRequested = false; + bool _noteCancel = false; + Duration _noteElapsed = Duration.zero; + Timer? _noteTimer; + + /// Press that may turn into a round note. A raw [Listener] is used instead of + /// a long-press recognizer: inside a TextField the field's own recognizer wins + /// the gesture arena and the press would never reach us. + Timer? _noteHoldTimer; + Offset? _notePressOrigin; + + /// The current press was held long enough to start a note, so releasing it + /// must not also count as a tap that opens the camera. + bool _noteHoldFired = false; + bool _cancelRecording = false; + MediaRecorderController? _recorderController; + Duration _recordDuration = Duration.zero; + Timer? _recordTimer; + // Per-chat theme override, null means the global theme + Color? _chatThemeColor; + + /// The message the composer is quoting, null when not replying. + PrivateMessage? _replyTo; + + /// Oldest message that was unread when the chat opened: the "new messages" + /// divider. Captured before this page marks everything read. + DateTime? _unreadAnchor; + final GlobalKey _unreadDividerKey = GlobalKey(); + + /// Client timestamps (microseconds) of the messages picked in multi-select. + final Set _selected = {}; + + /// Bubble keys by client timestamp, for jumping to a quoted message. + final Map _messageKeys = {}; + + /// Pinned message ids of this chat with the instant of the pin. + Map _pins = {}; + + /// Which pin the strip shows; the list is newest pin first. + int _pinIndex = 0; + + /// Message the last jump landed on, flashing so the user sees which one it + /// was; cleared by [_highlightTimer]. + int? _highlightMicros; + Timer? _highlightTimer; + + /// Whether this chat publishes and shows read receipts. + bool _readReceipts = false; + + /// Instant up to which the other participant has read this chat. + DateTime? _peerReadAt; + + /// Client timestamp of the newest own message: only that one carries the + /// read tick. + int? _lastOwnMicros; + + /// Instant this device already told the server about, so an idle re-render + /// does not send the same cursor again. + DateTime? _publishedReadAt; + Timer? _readPublish; + + /// The composer floats over the message list, so the list reserves its + /// measured height at the bottom and slides behind the bar above it. + final GlobalKey _composerKey = GlobalKey(); + double _composerHeight = 0; + + /// Newest message the viewport has already shown at the bottom; anything + /// after it while scrolled up counts as unseen. + int _newestSeenSentAt = 0; + int _unseenCount = 0; + // Whether the floating "jump to latest" button is up because the viewport is + // far from the newest message. Hysteresis keeps it from blinking around the + // threshold while the finger is still moving. + bool _farFromBottom = false; + + bool get _selectionMode => _selected.isNotEmpty; @override void initState() { super.initState(); - // Load messages from cache - _loadMessages(); + MessageNotifier().addListener(_onMessagesChanged); + PresenceNotifier.instance.addListener(_onPresenceChanged); + _scrollController.addListener(_onScroll); + _metricsObserver = _KeyboardObserver(() { + if (_atBottom) { + WidgetsBinding.instance.addPostFrameCallback((_) => _jumpToBottom()); + } + }); + WidgetsBinding.instance.addObserver(_metricsObserver); + _start(); // Load concept message getConceptMessage(); + // Load per-chat theme + _loadChatTheme(); + // A chat created since the last announcement must learn we are here; the + // call is a no-op when presence is off. + WidgetsBinding.instance.addPostFrameCallback((_) { + utils.Utils.announcePresence(); + }); + } + + /// The read state must be captured before the chat marks it read, otherwise + /// there is no divider left to draw. + Future _start() async { + final firstUnread = await CacheUtils.firstUnreadSentAt(widget.user.id); + if (mounted && firstUnread != null) { + setState(() { + _unreadAnchor = firstUnread; + }); + } + await _loadMessages(); + // Then top the conversation up from the server archive + _loadHistory(); + } + + /// Keeps the newest message on screen when the keyboard opens. + late final _KeyboardObserver _metricsObserver; + + /// Typing and presence are ephemeral, so the header redraws on every change. + void _onPresenceChanged() { + if (mounted) { + setState(() {}); + } + } + + /// Reload the conversation from the cache when messages or media state change. + void _onMessagesChanged() { + // Our own read notifies too (it marks messages read); do not re-enter. + if (_selfRead) { + return; + } + _loadMessages(); + } + + /// Whether the viewport sits at the newest message. The list is reversed, so + /// the newest message is at offset zero and older ones have larger offsets. + bool get _atBottom { + if (!_scrollController.hasClients) { + return true; + } + return _scrollController.position.pixels <= 40; + } + + /// Load the conversation once per change instead of once per build. + Future _loadMessages() async { + if (_loading) { + // Reading the cache already; the running pass may predate this change. + _reloadRequested = true; + return; + } + if (!mounted) { + return; + } + _loading = true; + final first = _firstLoad; + final wasAtBottom = _atBottom; + try { + // The read notifies as a side effect; keep that out of the listener. + final List messages; + _selfRead = true; + try { + messages = await MessageNotifier().getMessages(widget.user.id); + } finally { + _selfRead = false; + } + if (!mounted) { + return; + } + // The first content frame decrypts every visible attachment, so keep it + // out of the push animation and let the spinner ride along instead. + if (first) { + await _waitForRouteAnimation(); + } + if (!mounted) { + return; + } + final newest = + messages.isEmpty ? 0 : messages.last.sentAt.microsecondsSinceEpoch; + final pins = await CacheUtils.getPinnedMessages(widget.user.id); + final peerReadAt = await CacheUtils.getPeerReadAt(widget.user.id); + final readReceipts = + await CacheUtils.isReadReceiptsEnabled(widget.user.id); + if (!mounted) { + return; + } + var lastOwn = 0; + for (final message in messages.reversed) { + if (message.isMe) { + lastOwn = message.sentAt.microsecondsSinceEpoch; + break; + } + } + setState(() { + _messages = messages; + _pins = pins; + _peerReadAt = peerReadAt; + _readReceipts = readReceipts; + _lastOwnMicros = lastOwn == 0 ? null : lastOwn; + if (!first) { + if (wasAtBottom) { + _unseenCount = 0; + } else if (newest > _newestSeenSentAt) { + _unseenCount += messages + .where((message) => + !message.isMe && + message.sentAt.microsecondsSinceEpoch > _newestSeenSentAt) + .length; + } + } + _newestSeenSentAt = newest; + _firstLoad = false; + }); + if (first || wasAtBottom) { + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + return; + } + _jumpToBottom(); + if (first) { + await _jumpToFirstUnread(); + } + } + // Reading the chat is what moves the cursor; the peer's ticks follow. + _publishReadCursor(); + } finally { + _loading = false; + if (_reloadRequested) { + _reloadRequested = false; + if (mounted) { + await _loadMessages(); + } + } + } + } + + /// Completes once the page transition that opened this page has finished. + Future _waitForRouteAnimation() async { + final animation = ModalRoute.of(context)?.animation; + if (animation == null || animation.status == AnimationStatus.completed) { + return; + } + final done = Completer(); + void onStatus(AnimationStatus status) { + if (status == AnimationStatus.completed) { + animation.removeStatusListener(onStatus); + if (!done.isCompleted) { + done.complete(); + } + } + } + + animation.addStatusListener(onStatus); + await done.future; + } + + void _jumpToBottom({bool animate = false}) { + if (!_scrollController.hasClients) { + return; + } + // Reversed list: the newest message is at offset zero. + if (animate) { + _scrollController.animateTo(0, + duration: const Duration(milliseconds: 250), curve: Curves.easeOut); + } else { + _scrollController.jumpTo(0); + } + if (_unseenCount != 0 || _farFromBottom) { + setState(() { + _unseenCount = 0; + _farFromBottom = false; + }); + } + } + + /// Takes the oldest end over a few frames: the first jump only reaches the + /// estimated extent, and the list lays out the real end further on. + Future _settleAtOldest() async { + for (var pass = 0; pass < 5; pass++) { + if (!_scrollController.hasClients) { + return; + } + final before = _scrollController.position.maxScrollExtent; + _scrollController.jumpTo(before); + await WidgetsBinding.instance.endOfFrame; + if (!mounted || !_scrollController.hasClients) { + return; + } + if ((_scrollController.position.maxScrollExtent - before).abs() < 1) { + return; + } + } + } + + /// Opens the chat on the first message the user has not read yet. + Future _jumpToFirstUnread() async { + if (_unreadAnchor == null) { + return; + } + await WidgetsBinding.instance.endOfFrame; + final context = _unreadDividerKey.currentContext; + if (context == null || !context.mounted) { + return; + } + await Scrollable.ensureVisible(context, + alignment: 0.15, duration: const Duration(milliseconds: 250)); + } + + /// Extend the rendered window when the user scrolls towards older messages. + void _onScroll() { + if (_jumping || !_scrollController.hasClients) { + return; + } + final position = _scrollController.position; + if (_atBottom && _unseenCount != 0) { + setState(() { + _unseenCount = 0; + }); + } + // Show after scrolling past a short threshold, hide closer to the bottom: + // one state with two edges, so the button does not flicker on the edge. + final far = _farFromBottom ? position.pixels > 60 : position.pixels > 120; + if (far != _farFromBottom) { + setState(() { + _farFromBottom = far; + }); + } + // Reversed list: older messages are at the far end of the scroll extent. + if (position.pixels < position.maxScrollExtent - 200) { + return; + } + if (_visibleCount < _messages.length) { + _growWindow(_pageSize); + } else if (_historyCursor != null) { + // The cache ran out: ask the server for the page above it. + _loadHistory(older: true); + } + } + + /// Renders more messages above the viewport without moving what is on screen. + /// + /// The list is reversed, so the extra messages are appended past the current + /// end of the scroll extent and the viewport does not need any compensation. + Future _growWindow(int by) async { + if (_growing || !mounted) { + return; + } + _growing = true; + setState(() { + _visibleCount += by; + }); + await WidgetsBinding.instance.endOfFrame; + _growing = false; + } + + /// Fetch one page of the conversation from the server archive. + /// + /// The first call fills a chat this device never had (a fresh install, or a + /// message older than anything local); later calls walk backwards when the + /// user scrolls past the oldest message. + Future _loadHistory({bool older = false}) async { + if (_historyLoading || (older && _historyCursor == null)) { + return; + } + if (!older && _historyLoaded) { + return; + } + if (!utils.Utils.isOnline) { + return; + } + _historyLoading = true; + try { + final page = await utils.Utils.callApi( + () => Singleton().messagesApi.getHistory(widget.user.id, + before: older ? _historyCursor : null, limit: _pageSize), + showError: false); + if (page == null || !mounted) { + return; + } + _historyLoaded = true; + _historyCursor = page.nextCursor; + // The account may have cleared this chat on another device: drop what + // this one still holds before the page is written back. + if (page.clearedAt != null) { + await CacheUtils.applyConversationClearedAt( + widget.user.id, page.clearedAt!.toLocal()); + MessageNotifier().notify(); + } + // Pins are shared and the page always carries the whole set, so this is + // also how an unpin that happened on another device lands here. + final pins = { + for (final pin in page.pins) pin.messageId: pin.pinnedAt.toLocal(), + }; + await CacheUtils.replacePinnedMessages(widget.user.id, pins); + if (mounted) { + setState(() { + _pins = pins; + }); + } + for (final peer in page.peers) { + await CacheUtils.addUser( + User(peer.id, peer.username, peer.publicKey, peer.admin)); + } + if (page.messages.isEmpty) { + return; + } + await utils.Utils.storeHistoryPage(page.messages); + if (!mounted) { + return; + } + // Show the page that just arrived without making the user scroll again. + // Reversed list: the page is appended past the current end, so the + // viewport stays where the user left it. + setState(() { + _visibleCount += page.messages.length; + }); + } finally { + _historyLoading = false; + } + } + + /// Runs [open] with the composer unfocused and unfocuses again afterwards. + /// + /// A sheet or a page pushed over the chat hands the focus (and with it the + /// keyboard) back to the field when it closes; without this the keyboard pops + /// up on its own after every attachment sheet or message action. + Future _withoutComposerFocus(Future Function() open) async { + FocusManager.instance.primaryFocus?.unfocus(); + await open(); + if (!mounted) { + return; + } + FocusManager.instance.primaryFocus?.unfocus(); + await WidgetsBinding.instance.endOfFrame; + if (mounted) { + FocusScope.of(context).unfocus(); + } + } + + /// Opens the long-press sheet for one message. The pin state of the sheet is + /// the one this device knows, so the entry reads "unpin" when it applies. + Future _openMessageActions(PrivateMessage message) { + final id = message.id; + return _withoutComposerFocus(() => MessageActions.showSheet( + context, + message, + widget.user.id, + pinned: id != null && _pins.containsKey(id), + onSelect: () => _toggleSelected(message), + )); + } + + /// Pinned messages this device holds, newest pin first: the strip walks them. + List get _pinnedInOrder { + final pinned = []; + for (final message in _messages) { + final id = message.id; + if (id != null && _pins.containsKey(id)) { + pinned.add(message); + } + } + pinned.sort((a, b) => _pins[b.id]!.compareTo(_pins[a.id]!)); + return pinned; + } + + /// Steps the strip to the next pinned message and jumps to it. + Future _cyclePin(List pins) async { + final next = (_pinIndex + 1) % pins.length; + setState(() { + _pinIndex = next; + }); + await _jumpToMessage(pins[next].sentAt); + } + + /// Slim strip under the header: one pin, tap to jump, cross to unpin, the + /// counter to walk the rest. + Widget _buildPinBar() { + final pins = _pinnedInOrder; + if (pins.isEmpty) { + return const SizedBox.shrink(); + } + final pinned = pins[_pinIndex % pins.length]; + final preview = pinned.preview; + return Material( + // Opaque in the header's tint: the strip sits over the message list, so a + // translucent fill would let bubbles show through it. + color: chatBackground(tintAlpha: 0.32), + child: InkWell( + onTap: () => _jumpToMessage(pinned.sentAt), + child: Padding( + padding: const EdgeInsets.only(left: 12, right: 4), + child: Row( + children: [ + const Icon(Icons.push_pin, size: 13), + const SizedBox(width: 6), + Expanded( + child: Text( + preview.isEmpty ? 'mediaPhoto'.tr() : preview, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 11), + ), + ), + if (pins.length > 1) + // Without this the strip only ever showed the newest pin and + // the others were unreachable. + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => _cyclePin(pins), + child: Padding( + padding: const EdgeInsets.only(left: 6), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${_pinIndex % pins.length + 1}/${pins.length}', + style: const TextStyle(fontSize: 10), + ), + const Icon(Icons.expand_more, size: 14), + ], + ), + ), + ), + IconButton( + icon: const Icon(Icons.close, size: 14), + tooltip: 'unpinMessage'.tr(), + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(minWidth: 28, minHeight: 26), + onPressed: () => MessageActions.togglePin( + pinned, widget.user.id, + pinned: true), + ), + ], + ), + ), + ), + ); + } + + /// Publishes how far this chat was read, debounced: scrolling through a burst + /// of messages should cost one request, not one per message. + void _publishReadCursor() { + if (!_readReceipts || _messages.isEmpty) { + return; + } + final newest = _messages.last.sentAt; + if (_publishedReadAt != null && !newest.isAfter(_publishedReadAt!)) { + return; + } + _readPublish?.cancel(); + _readPublish = Timer(const Duration(seconds: 1), () async { + final at = _messages.isEmpty ? null : _messages.last.sentAt; + if (at == null) { + return; + } + if (await utils.Utils.sendReadCursor(widget.user.id, at) && mounted) { + _publishedReadAt = at; + } + }); + } + + /// Load the draft message saved when leaving the chat. + Future getConceptMessage() async { + String? conceptMsg = await CacheUtils.getMessageConcept(widget.user.id); + if (!mounted) { + return; + } + setState(() { + _controllerMessage.text = conceptMsg ?? ''; + }); + } + + /// Load the per-chat theme override. + Future _loadChatTheme() async { + Color? color = await CacheUtils.getChatTheme(widget.user.id); + if (!mounted) { + return; + } + setState(() { + _chatThemeColor = color; + }); + } + + Future _openChatInfo() async { + // The info page hands back a timestamp when a search hit or a date was + // picked there. + final target = await Navigator.of(context) + .push(stepRoute(ChatInfoPage(widget.user.id))); + // The theme (and possibly the user) may have changed while it was open. + await _loadChatTheme(); + await _loadMessages(); + if (target != null && mounted) { + await _jumpTo(target); + } + } + + /// Jumps to [target], or to the first message after it: a search hit is an + /// exact instant, a picked day is midnight. + Future _jumpTo(DateTime target) async { + if (_messages.isEmpty) { + return; + } + var index = _messages.indexWhere((message) => message.sentAt == target); + if (index < 0) { + index = _messages.indexWhere((message) => message.sentAt.isAfter(target)); + } + if (index < 0) { + await Fluttertoast.showToast( + msg: 'noMessagesOnDate'.tr(), backgroundColor: Colors.orange); + return; + } + await _jumpToMessage(_messages[index].sentAt); + } + + // --------------------------------------------------------------------------- + // Reply and multi-select + // --------------------------------------------------------------------------- + + /// Quote [message] in the composer. + void _startReply(PrivateMessage message) { + if (_selectionMode) { + return; + } + setState(() { + _replyTo = message; + }); + } + + /// Adds or removes [message] from the selection; leaving it empty closes the + /// selection mode. + void _toggleSelected(PrivateMessage message) { + final micros = message.sentAt.microsecondsSinceEpoch; + setState(() { + if (!_selected.remove(micros)) { + _selected.add(micros); + } + }); + } + + void _clearSelection() { + setState(_selected.clear); + } + + /// Messages currently picked, oldest first. + List get _selectedMessages => _messages + .where((message) => + _selected.contains(message.sentAt.microsecondsSinceEpoch)) + .toList(); + + Future _copySelected() async { + final text = _selectedMessages + .map((message) => message.message) + .where((text) => text.isNotEmpty) + .join('\n'); + _clearSelection(); + if (text.isEmpty) { + return; + } + await Clipboard.setData(ClipboardData(text: text)); + Fluttertoast.showToast(msg: 'copiedText'.tr()); + } + + Future _forwardSelected() async { + final messages = _selectedMessages; + if (messages.isEmpty) { + return; + } + _clearSelection(); + await Navigator.of(context).push(stepRoute(ForwardPage(messages))); + } + + void _deleteSelected() { + final messages = _selectedMessages; + if (messages.isEmpty) { + return; + } + DialogUtils.yesNoDialog( + context, 'deleteMessageConfirm'.tr(), 'deleteMessageConfirmText'.tr(), + () async { + for (final message in messages) { + await CacheUtils.deletePrivateMessage(widget.user.id, message); + } + _clearSelection(); + MessageNotifier().notify(); + }); + } + + /// Flashes the bubble a jump landed on, so the target is obvious even when + /// the message itself looks like its neighbours. + void _flashMessage(int micros) { + _highlightTimer?.cancel(); + setState(() => _highlightMicros = micros); + _highlightTimer = Timer(const Duration(milliseconds: 1200), () { + if (mounted) { + setState(() => _highlightMicros = null); + } + }); + } + + /// Scrolls to [sentAt], used by the reply quote, the search hits and the + /// date jump. + /// + /// Widening the rendered window is not enough: a list only builds what is + /// near the viewport, so growing the tail never builds an old message. The + /// window is therefore cut down to the target first, then the oldest end is + /// taken and the viewport walks towards newer messages until the target is + /// built. Walking back from the oldest end covers both a target above the + /// viewport and one below it. + Future _jumpToMessage(DateTime sentAt) async { + final micros = sentAt.microsecondsSinceEpoch; + _jumping = true; + try { + final index = _messages.indexWhere((message) => message.sentAt == sentAt); + if (index < 0) { + return; + } + final needed = windowForAddition(_messages.length, index); + if (needed > _visibleCount) { + setState(() { + _visibleCount = needed; + }); + await WidgetsBinding.instance.endOfFrame; + if (!mounted || !_scrollController.hasClients) { + return; + } + } + final context = _messageKeys[micros]?.currentContext; + if (context != null && context.mounted) { + await Scrollable.ensureVisible(context, + alignment: 0.2, duration: const Duration(milliseconds: 250)); + _flashMessage(micros); + return; + } + await _settleAtOldest(); + for (var attempt = 0; attempt < 50; attempt++) { + if (!mounted || !_scrollController.hasClients) { + return; + } + final reached = _messageKeys[micros]?.currentContext; + if (reached != null && reached.mounted) { + await Scrollable.ensureVisible(reached, + alignment: 0.3, duration: const Duration(milliseconds: 250)); + _flashMessage(micros); + return; + } + final position = _scrollController.position; + final next = + nextJumpOffset(position.pixels, position.viewportDimension); + if (next == position.pixels) { + return; + } + _scrollController.jumpTo(next); + await WidgetsBinding.instance.endOfFrame; + } + } finally { + _jumping = false; + } + } + + /// Send the typed text. + Future _sendMessage() async { + final text = _controllerMessage.text; + if (text.isEmpty) { + return; + } + final quoted = _replyTo; + final reply = quoted == null + ? null + : ReplyRef( + senderId: quoted.senderId, + sentAt: quoted.sentAt, + preview: ReplyRef.previewOf(quoted.preview), + ); + setState(() { + _isSending = true; + }); + if (await ChatSender.sendText(widget.user, text, reply: reply)) { + _controllerMessage.text = ''; + setState(() { + _replyTo = null; + }); + await CacheUtils.deleteMessageConcept(widget.user.id); + } + if (mounted) { + setState(() { + _isSending = false; + }); + } + } + + /// Send a media attachment: probe what the type needs, then the shared send + /// path (encrypt, upload, persist a bubble, send). + Future _sendMedia(MediaType type, File file, + {String caption = '', + int? durationMs, + List? waveform, + bool videoNote = false, + bool viewOnce = false}) async { + setState(() { + _isSending = true; + }); + try { + final bytes = await file.readAsBytes(); + final probe = await _probe(type, bytes, file.path, durationMs); + final sent = await ChatSender.sendMedia(widget.user, type, bytes, + caption: caption, + width: probe.width, + height: probe.height, + durationMs: probe.durationMs, + fileName: MediaUtils.baseName(file.path), + waveform: waveform, + videoNote: videoNote, + viewOnce: viewOnce); + _afterSend(sent, caption); + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } finally { + if (mounted) { + setState(() { + _isSending = false; + }); + } + } + } + + /// Send several attachments as one album message. + Future _sendAlbum(List files, + {String caption = '', bool viewOnce = false}) async { + setState(() { + _isSending = true; + }); + try { + final attachments = []; + for (final file in files) { + final bytes = await file.readAsBytes(); + final type = MediaUtils.detectType(file.path); + final probe = await _probe(type, bytes, file.path, null); + attachments.add(OutgoingAttachment( + type: type, + bytes: bytes, + width: probe.width, + height: probe.height, + durationMs: probe.durationMs, + fileName: MediaUtils.baseName(file.path), + )); + } + final sent = await ChatSender.sendAlbum(widget.user, attachments, + caption: caption, viewOnce: viewOnce); + _afterSend(sent, caption); + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } finally { + if (mounted) { + setState(() { + _isSending = false; + }); + } + } + } + + /// Clear the composer when the caption was consumed by a successful send. + void _afterSend(bool sent, String caption) { + if (sent && caption.isNotEmpty && _controllerMessage.text == caption) { + _controllerMessage.text = ''; + CacheUtils.deleteMessageConcept(widget.user.id); + } + } + + /// Width/height/duration for the types that need them. + Future _probe( + MediaType type, Uint8List bytes, String path, int? durationMs) async { + if (type == MediaType.image || type == MediaType.gif) { + return MediaUtils.imageDimensions(bytes); + } + if (type == MediaType.video) { + final probe = await MediaUtils.videoMetadata(path); + return MediaProbe( + width: probe.width, + height: probe.height, + durationMs: probe.durationMs ?? durationMs, + ); + } + return MediaProbe(durationMs: durationMs); + } + + /// Pick one or more files, then confirm with an optional caption. + /// + /// [forcedType] fixes the type for camera picks; [filesOnly] rejects photos + /// and videos (the "File" entry must stay a document picker). + Future _pickAndSend(Future> Function() picker, + {MediaType? forcedType, bool filesOnly = false}) async { + try { + final picked = await picker(); + if (picked.isEmpty) { + return; + } + var files = picked; + if (filesOnly) { + files = + picked.where((file) => !MediaUtils.isVisualMedia(file)).toList(); + if (files.length != picked.length) { + await Fluttertoast.showToast( + msg: 'fileTypeNotAllowed'.tr(), backgroundColor: Colors.orange); + } + if (files.isEmpty) { + return; + } + } + + // Cheap size check before reading anything into memory. + for (final file in files) { + if (!MediaUtils.uploadFits(await file.length())) { + await Fluttertoast.showToast( + msg: + '${'fileTooLarge'.tr()} ${MediaUtils.formatBytes(MediaUtils.maxUploadBytes)}', + backgroundColor: Colors.red); + return; + } + } + + final single = files.length == 1; + final type = + single ? forcedType ?? MediaUtils.detectType(files.first.path) : null; + // Any picked attachment can travel as a single view: one visual file, a + // gallery album or a plain document all burn the same way. Only a single + // photo or video can be edited first. + final editable = + single && (type == MediaType.image || type == MediaType.video); + final confirmed = await _confirmAttachment(files.length, + allowViewOnce: true, allowEdit: editable); + if (confirmed == null) { + return; + } + if (single && confirmed.edit) { + final edited = await _editAttachment(type!, files.first); + if (edited == null) { + return; + } + files = [edited]; + } + if (single) { + await _sendMedia(type!, files.first, + caption: confirmed.caption, viewOnce: confirmed.viewOnce); + } else { + await _sendAlbum(files, + caption: confirmed.caption, viewOnce: confirmed.viewOnce); + } + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } + } + + /// Opens the sticker collection and sends the picked one as it is: a sticker + /// travels as its own media type, so the recipient draws it without a bubble. + Future _pickSticker() async { + Sticker? sticker; + await _withoutComposerFocus(() async { + sticker = await StickerSheet.show(context); + }); + final picked = sticker; + if (picked == null) { + return; + } + final bytes = await MediaUtils.decryptAtRest(picked.path); + final sent = await ChatSender.sendMedia( + widget.user, MediaType.sticker, bytes, + fileName: MediaUtils.baseName(picked.path)); + _afterSend(sent, ''); + } + + /// Opens the in-app camera. What comes back is a photo or a video, and it + /// goes through the same confirm sheet as a gallery pick. + Future _captureFromCamera() async { + File? file; + await _withoutComposerFocus(() async { + file = await CameraPage.open(context); + }); + final captured = file; + if (captured == null) { + return; + } + final type = MediaUtils.detectType(captured.path); + await _pickAndSend(() async => [captured], + forcedType: + type == MediaType.video ? MediaType.video : MediaType.image); + } + + /// The tap that ends a hold must not open the camera: the button sees the + /// release as a tap as well. + void _openCameraUnlessNote() { + if (_noteHoldFired || _isRecordingNote || _noteStarting) { + return; + } + _captureFromCamera(); + } + + /// A press on the camera button starts the hold timer; a tap still opens the + /// camera through the button itself. + void _onCameraPressStart(PointerDownEvent event) { + // The press is inside the field's tap region, which would focus it and + // raise the keyboard over the note preview. + FocusScope.of(context).unfocus(); + _notePressOrigin = event.position; + _noteHoldFired = false; + _noteHoldTimer?.cancel(); + _noteHoldTimer = Timer(const Duration(milliseconds: 400), () { + _noteHoldTimer = null; + _noteHoldFired = true; + _startRoundNote(); + }); + } + + void _onCameraPressMove(PointerMoveEvent event) { + final origin = _notePressOrigin; + if (origin == null || !_isRecordingNote) { + return; + } + final cancel = event.position.dx - origin.dx < -80; + if (cancel != _noteCancel) { + setState(() => _noteCancel = cancel); + } + } + + void _onCameraPressEnd(PointerEvent event) { + _noteHoldTimer?.cancel(); + _noteHoldTimer = null; + _notePressOrigin = null; + if (_isRecordingNote) { + _stopRoundNote(); + } else if (_noteStarting) { + // Released while the camera was still opening. + _noteStopRequested = true; + } + } + + /// Starts a round video note from the composer. It runs only while the finger + /// is down; releasing sends it, sliding left throws it away. + Future _startRoundNote() async { + if (_isRecordingNote || _noteStarting || _isSending) { + return; + } + _noteStarting = true; + FocusScope.of(context).unfocus(); + final recorder = RoundVideoRecorder(); + try { + if (!await recorder.start()) { + await recorder.dispose(); + await Fluttertoast.showToast( + msg: 'cameraUnavailable'.tr(), backgroundColor: Colors.red); + return; + } + } finally { + _noteStarting = false; + } + if (!mounted) { + await recorder.dispose(); + return; + } + setState(() { + _noteRecorder = recorder; + _isRecordingNote = true; + _noteCancel = false; + _noteElapsed = Duration.zero; + }); + // The press lands inside the field's tap region, which can hand the focus + // (and the keyboard) back once the preview is on screen. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + FocusScope.of(context).unfocus(); + } + }); + _noteTimer = Timer.periodic(const Duration(seconds: 1), (_) { + if (!mounted) { + return; + } + setState(() => _noteElapsed += const Duration(seconds: 1)); + if (_noteElapsed >= RoundVideoRecorder.maxLength) { + _stopRoundNote(); + } + }); + // The finger was lifted while the camera was still opening. + if (_noteStopRequested) { + _noteStopRequested = false; + await _stopRoundNote(); + } + } + + /// Stops the round note and sends it, unless it was dragged away. + Future _stopRoundNote() async { + _noteTimer?.cancel(); + _noteTimer = null; + final recorder = _noteRecorder; + _noteRecorder = null; + final cancelled = _noteCancel; + _noteCancel = false; + if (mounted) { + setState(() => _isRecordingNote = false); + } + if (recorder == null) { + return; + } + if (cancelled) { + await recorder.cancel(); + return; + } + final file = await recorder.stop(); + if (mounted) { + FocusScope.of(context).unfocus(); + } + if (file == null) { + return; + } + await _sendMedia(MediaType.video, file, videoNote: true); + } + + /// The circle above the composer while a round note is being recorded. + Widget _buildRoundNotePreview() { + final controller = _noteRecorder?.controller; + final color = _noteCancel ? Colors.red : chatTheme.colorScheme.primary; + final ready = controller != null && controller.value.isInitialized; + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 162, + height: 162, + child: Stack( + alignment: Alignment.center, + children: [ + // A minute of recording fills the ring around the preview, so + // the limit is visible without reading the timer. + SizedBox.expand( + child: TweenAnimationBuilder( + tween: Tween( + begin: 0, + end: (_noteElapsed.inMilliseconds / + RoundVideoRecorder.maxLength.inMilliseconds) + .clamp(0.0, 1.0)), + duration: const Duration(seconds: 1), + builder: (context, value, _) => CircularProgressIndicator( + value: value, + strokeWidth: 4, + strokeCap: StrokeCap.round, + backgroundColor: color.withValues(alpha: 0.25), + valueColor: AlwaysStoppedAnimation(color), + ), + ), + ), + ClipOval( + child: SizedBox( + width: 150, + height: 150, + child: ready + ? FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: + controller.value.previewSize?.height ?? 150, + height: + controller.value.previewSize?.width ?? 150, + child: CameraPreview(controller), + ), + ) + : const ColoredBox( + color: Colors.black26, + child: Center(child: CircularProgressIndicator()), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 4), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.fiber_manual_record, + size: 12, color: Colors.red), + const SizedBox(width: 4), + Text( + '${_formatRecordDuration(_noteElapsed)} · ${'slideToCancel'.tr()}', + style: TextStyle(color: color, fontSize: 12), + ), + ], + ), + ], + ), + ); + } + + /// Runs the editor for one picked attachment. Returns null when the user + /// backs out, which aborts the send instead of silently sending the original. + Future _editAttachment(MediaType type, File file) async { + if (type == MediaType.image) { + final bytes = await file.readAsBytes(); + if (!mounted) { + return null; + } + final edited = await ImageEditorPage.open(context, bytes); + if (edited == null) { + return null; + } + final dir = await getTemporaryDirectory(); + final path = + '${dir.path}/shept_edited_${DateTime.now().microsecondsSinceEpoch}.png'; + return File(path)..writeAsBytesSync(edited, flush: true); + } + if (!mounted) { + return null; + } + return VideoTrimPage.open(context, file); + } + + /// Sends one fix as a location message. No coordinates are read until the + /// user picks this action, and they travel only inside the ciphertext. + Future _sendCurrentLocation() async { + // A location is a message of its own, so the single view is a choice made + // here rather than in an attachment sheet. + final viewOnce = await showDialog( + context: context, + builder: (ctx) => SimpleDialog( + title: Text('attachLocation'.tr()), + children: [ + ListTile( + leading: const Icon(Icons.place), + title: Text('attachLocation'.tr()), + onTap: () => Navigator.pop(ctx, false), + ), + ListTile( + leading: const Icon(Icons.visibility_off), + title: Text('attachViewOnce'.tr()), + subtitle: Text('viewOnceHint'.tr()), + onTap: () => Navigator.pop(ctx, true), + ), + ], + ), + ); + if (viewOnce == null || !mounted) { + return; + } + setState(() => _isSending = true); + try { + final position = await LiveLocationSharer.currentPosition(); + if (position == null) { + await Fluttertoast.showToast( + msg: 'locationUnavailable'.tr(), backgroundColor: Colors.red); + return; + } + final sent = await ChatSender.sendLocation( + widget.user, position.latitude, position.longitude, + accuracy: position.accuracy, viewOnce: viewOnce); + _afterSend(sent, ''); + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } finally { + if (mounted) { + setState(() => _isSending = false); + } + } + } + + /// Live location is opt-in, ends on its own and can be stopped in the banner. + Future _startLiveLocation() async { + const options = [15, 60, 480]; + final minutes = await showDialog( + context: context, + builder: (ctx) => SimpleDialog( + title: Text('liveLocationShare'.tr()), + children: [ + for (final option in options) + ListTile( + title: Text('liveLocationFor'.tr(args: ['$option min'])), + onTap: () => Navigator.pop(ctx, option), + ), + ], + ), + ); + if (minutes == null) { + return; + } + // The first frame needs a GPS fix and a round trip: without a sending state + // the sheet closes into a silent screen with nothing to look at. + setState(() => _isSending = true); + try { + final started = await LiveLocationSharer.instance + .start(widget.user, Duration(minutes: minutes)); + if (started && mounted) { + setState(() {}); + } + } finally { + if (mounted) { + setState(() => _isSending = false); + } + } + } + + /// Bottom sheet with a caption field; returns the caption and the view-once + /// choice, or null to cancel. + Future _confirmAttachment(int count, + {bool allowViewOnce = false, bool allowEdit = false}) { + return AttachmentConfirmSheet.show( + context, + count: count, + allowViewOnce: allowViewOnce, + allowEdit: allowEdit, + initialCaption: _controllerMessage.text.trim(), + theme: ThemeUtils.chatTheme(context, _chatThemeColor), + backgroundColor: chatBackground(tintAlpha: 0.18), + ); + } + + /// GIF/WebP inserted straight from the keyboard (Gboard image keyboard). + Future _onKeyboardContentInserted( + KeyboardInsertedContent content) async { + final bytes = content.data; + if (bytes == null || bytes.isEmpty) { + await Fluttertoast.showToast( + msg: 'gifFromKeyboardFailed'.tr(), backgroundColor: Colors.red); + return; + } + final extension = content.mimeType == 'image/webp' ? 'webp' : 'gif'; + final file = await MediaUtils.writeTempBytes(bytes, extension); + await _sendMedia(MediaType.gif, file); + } + + /// Show the attachment options bottom sheet. + void _showAttachSheet() { + _withoutComposerFocus(() => showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) { + return SafeArea( + child: Wrap( + children: [ + ListTile( + leading: const Icon(Icons.photo_library), + title: Text('attachGallery'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend(MediaUtils.pickMultipleMediaFromGallery); + }, + ), + ListTile( + leading: const Icon(Icons.emoji_emotions_outlined), + title: Text('attachStickers'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickSticker(); + }, + ), + ListTile( + leading: const Icon(Icons.insert_drive_file), + title: Text('attachFile'.tr()), + onTap: () { + Navigator.pop(ctx); + _pickAndSend(MediaUtils.pickMultipleFiles, + filesOnly: true); + }, + ), + ListTile( + leading: const Icon(Icons.place), + title: Text('attachLocation'.tr()), + onTap: () { + Navigator.pop(ctx); + _sendCurrentLocation(); + }, + ), + ListTile( + leading: const Icon(Icons.my_location), + title: Text('attachLiveLocation'.tr()), + onTap: () { + Navigator.pop(ctx); + _startLiveLocation(); + }, + ), + ], + ), + ); + }, + )); } - Future getConceptMessage() async { - String? conceptMsg = await CacheUtils.getMessageConcept(widget.user.id); - if (conceptMsg != null) { - _controllerMessage.text = conceptMsg; + /// Start recording a voice message (hold-to-record). + Future _startRecording() async { + if (_isRecording || _recordingStarting || _isSending) { + return; } - } - - Future _loadMessages() async { - _messages = await MessageNotifier().getMessages(widget.user.id); - MessageNotifier().notify(); - setState(() {}); - } - - /// Send message - Future _sendMessage() async { - debugPrint(_controllerMessage.text.length.toString()); - if (_controllerMessage.text.isEmpty) { + _recordingStarting = true; + final controller = MediaRecorderController(); + try { + if (!await controller.hasPermission()) { + await Fluttertoast.showToast( + msg: 'micPermissionDenied'.tr(), backgroundColor: Colors.red); + await controller.dispose(); + return; + } + await controller.start(); + } catch (e) { + await controller.dispose(); + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + return; + } finally { + _recordingStarting = false; + } + if (!mounted) { + await controller.dispose(); return; } setState(() { - _isSending = true; + _recorderController = controller; + _isRecording = true; + _cancelRecording = false; + _recordingLocked = false; + _recordDuration = Duration.zero; }); - await Utils.wsConnect(); - // Send message - if (Singleton().wsClient.isConnected) { - // Encrypt message content - Map data; - try { - data = await CryptoUtils.encryptMessageData( - utf8.encode(_controllerMessage.text), - bu.CryptoUtils.rsaPublicKeyFromPem(widget.user.publicKey)); - } catch (e) { - await Fluttertoast.showToast( - msg: e.toString(), backgroundColor: Colors.red); + _recordTimer = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) { setState(() { - _isSending = false; + _recordDuration += const Duration(seconds: 1); }); - return; - } - DateTime sentAt; - try { - sentAt = Singleton().wsClient.sendMessage(WsMessage.privateMessage( - NewPrivateMessage(widget.user.id, data['encryptedData']!, - data['encryptedKey']!, data['nonce']!, data['mac']!))); - // Save user to cache - if (widget.user.publicKey != '' && - widget.user.username != '' && - !widget.user.isInBox) { - CacheUtils.addUser(widget.user); - } - // Add message to cache - await MessageNotifier().addMessages(widget.user.id, [ - PrivateMessage(Singleton().profile.user.id, _controllerMessage.text, - sentAt, sentAt, true) - ]); - // Reset text - _controllerMessage.text = ''; - // Delete concept - await CacheUtils.deleteMessageConcept(widget.user.id); - } catch (e) { - await Fluttertoast.showToast( - msg: e.toString(), backgroundColor: Colors.red); } - } else { + }); + // The finger was lifted while the recorder was still starting. + if (_stopRequested) { + _stopRequested = false; + await _stopRecording(); + } + } + + /// Finish recording and send (unless the gesture was cancelled). + Future _stopRecording() async { + _recordTimer?.cancel(); + _recordTimer = null; + final controller = _recorderController; + _recorderController = null; + final cancelled = _cancelRecording; + _cancelRecording = false; + if (mounted) { + setState(() { + _isRecording = false; + }); + } + if (controller == null) { + return; + } + if (cancelled) { + await controller.cancel(); + await controller.dispose(); + return; + } + final recorded = await controller.stop(); + final waveform = controller.waveform; + await controller.dispose(); + if (recorded == null) { + return; + } + // Ignore accidental taps that produce a near-empty recording. + if (recorded.durationMs < 800) { + await MediaUtils.deleteLocalFile(recorded.file.path); await Fluttertoast.showToast( - msg: 'wsOffline'.tr(), backgroundColor: Colors.red); + msg: 'voiceTooShort'.tr(), backgroundColor: Colors.orange); + return; + } + await _sendMedia(MediaType.voice, recorded.file, + durationMs: recorded.durationMs, waveform: waveform); + } + + /// Stop and drop the recording (bar button). + Future _cancelRecordingGesture() async { + if (!_isRecording) { + return; } setState(() { - _isSending = false; + _cancelRecording = true; }); + await _stopRecording(); } - /// Get ListView with content - ListView _getContent(List messages) { - _firstLoad = false; - return ListView.builder( - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics(), - ), - controller: _scrollController, - reverse: false, - itemCount: messages.length + 1, - itemBuilder: (context, index) { - if (index == 0) { - // Header with avatar (will appear at the top) - return Center( - child: Padding( - padding: const EdgeInsets.only(top: 20, bottom: 20), - child: Column( + String _formatRecordDuration(Duration d) { + final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = d.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + /// Composer: a paperclip inside the field on the left, one round action + /// beside the field on the right — mic while it is empty, send once there is + /// text — painted in the chat's colour. + Widget _buildInputBar() { + return Padding( + padding: const EdgeInsets.fromLTRB(5, 4, 8, 4), + // Stretching the row makes the button exactly as tall as the field, so + // the two are aligned however many lines the field grows to. + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: Stack( children: [ - CircleAvatar( - radius: 50, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 40, - color: widget.user.avatarTextColor, + TextField( + controller: _controllerMessage, + minLines: 1, + maxLines: 5, + textInputAction: TextInputAction.newline, + onChanged: (value) { + // The receiver clears the indicator on its own; this only + // throttles the frames and stays silent when the user opted + // out. + if (value.trim().isNotEmpty) { + utils.Utils.sendTypingHint(widget.user.id); + } + }, + contentInsertionConfiguration: + ContentInsertionConfiguration( + allowedMimeTypes: const ['image/gif', 'image/webp'], + onContentInserted: _onKeyboardContentInserted, + ), + decoration: InputDecoration( + hintText: 'yourMessage'.tr(), + isDense: true, + contentPadding: const EdgeInsets.symmetric(vertical: 12), + // Room for the buttons that float above the field. + prefixIcon: const SizedBox(width: 40), + suffixIcon: const SizedBox(width: 40), + filled: true, + fillColor: chatTheme.brightness == Brightness.dark + ? chatTheme.colorScheme.surfaceBright + : chatTheme.colorScheme.surfaceDim, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(30), + borderSide: BorderSide.none, + ), + ), + ), + // The paperclip and the camera sit above the field, not in + // it: a press inside the TextField's tap region focuses it and + // flashes the keyboard, which must not happen while a round + // note is recording. + Positioned( + left: 0, + top: 0, + bottom: 0, + child: Center( + child: _composerIcon( + icon: Icons.attach_file, + label: 'attachButton'.tr(), + tooltip: 'attachButton'.tr(), + onPressed: _isSending ? null : _showAttachSheet, ), ), ), - const SizedBox(height: 12), - Text( - widget.user.username, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, + Positioned( + right: 0, + top: 0, + bottom: 0, + child: Center( + child: Listener( + onPointerDown: _onCameraPressStart, + onPointerMove: _onCameraPressMove, + onPointerUp: _onCameraPressEnd, + onPointerCancel: _onCameraPressEnd, + child: _composerIcon( + icon: Icons.photo_camera_outlined, + label: 'attachCamera'.tr(), + onPressed: _isSending ? null : _openCameraUnlessNote, + ), + ), ), ), - const SizedBox(height: 30), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 50), - child: Text('legendaryChat'.tr(), - textAlign: TextAlign.center)), ], ), ), - ); - } - // Return chat bubble - final previousMessage = index > 1 ? messages[index - 2] : null; - final message = messages[index - 1]; - final nextMessage = index < messages.length ? messages[index] : null; - return ChatBubble(previousMessage, message, nextMessage, widget.user); - }, + const SizedBox(width: 8), + ValueListenableBuilder( + valueListenable: _controllerMessage, + builder: (context, value, _) { + // A send in flight shows here whatever the field holds: + // encrypting and uploading a large attachment, probing a video + // or waiting for a GPS fix takes a while, and the bubble is not + // there yet. + if (_isSending) { + return _composerButton( + child: const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, color: Colors.white), + ), + ); + } + if (value.text.trim().isNotEmpty) { + return _composerButton( + onPressed: _sendMessage, + child: const Icon(Icons.send), + ); + } + // Hold-to-record voice message. The bar is overlaid while + // recording, so this detector stays mounted and its long-press + // end still fires. + return GestureDetector( + onLongPressStart: (_) => _startRecording(), + onLongPressMoveUpdate: (details) { + if (_recordingLocked) { + return; + } + final offset = details.localOffsetFromOrigin; + if (offset.dy < -60) { + setState(() { + _recordingLocked = true; + _cancelRecording = false; + }); + return; + } + final shouldCancel = offset.dx < -80; + if (shouldCancel != _cancelRecording) { + setState(() { + _cancelRecording = shouldCancel; + }); + } + }, + onLongPressEnd: (_) { + // A locked recording outlives the gesture: it stops from + // the bar, which is all the release used to do. + if (_isRecording && !_recordingLocked) { + _stopRecording(); + } else if (!_isRecording) { + _stopRequested = true; + } + }, + child: _composerButton( + onPressed: () async { + await Fluttertoast.showToast(msg: 'holdToRecord'.tr()); + }, + child: const Icon(Icons.mic), + ), + ); + }, + ), + ], + ), + ), + ); + } + + /// A plain icon beside the composer. Compact on purpose: three full-width + /// buttons would squeeze the field, which is the part that carries the width. + Widget _composerIcon({ + required IconData icon, + required String label, + required VoidCallback? onPressed, + String? tooltip, + }) { + final button = IconButton( + icon: Icon(icon), + iconSize: 22, + padding: EdgeInsets.zero, + visualDensity: VisualDensity.compact, + constraints: const BoxConstraints.tightFor(width: 40, height: 44), + tooltip: tooltip, + onPressed: onPressed, + ); + return tooltip == null + ? Semantics(button: true, label: label, child: button) + : button; + } + + /// The round action beside the composer, filled with the chat's colour. It + /// takes the row's height, so it is a circle while the field has one line. + Widget _composerButton({Widget? child, VoidCallback? onPressed}) { + final color = chatTheme.colorScheme.primary; + final onColor = + ThemeData.estimateBrightnessForColor(color) == Brightness.dark + ? Colors.white + : Colors.black87; + return SizedBox( + width: 48, + child: Material( + color: color, + shape: const StadiumBorder(), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onPressed, + child: IconTheme( + data: IconThemeData(color: onColor), + child: Center(child: child), + ), + ), + ), + ); + } + + /// Quoted message above the composer, dismissable. + Widget _buildReplyBar() { + final reply = _replyTo!; + final author = reply.isMe + ? 'meText'.tr() + : (widget.user.username.isNotEmpty ? widget.user.username : '?'); + return Container( + margin: const EdgeInsets.only(bottom: 6), + padding: const EdgeInsets.only(left: 10), + decoration: BoxDecoration( + color: chatTheme.colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(12), + border: Border( + left: BorderSide(color: chatTheme.colorScheme.primary, width: 3), + ), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + author, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: chatTheme.colorScheme.primary, + ), + ), + Text( + reply.preview, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + color: chatTheme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + IconButton( + tooltip: 'cancel'.tr(), + icon: const Icon(Icons.close, size: 18), + onPressed: () { + setState(() { + _replyTo = null; + }); + }, + ), + ], + ), + ); + } + + /// Bar shown while recording a voice message. + Widget _buildRecordingBar() { + final color = _cancelRecording ? Colors.red : chatTheme.colorScheme.primary; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: chatTheme.brightness == Brightness.dark + ? chatTheme.colorScheme.surfaceBright + : chatTheme.colorScheme.surfaceDim, + borderRadius: BorderRadius.circular(30), + ), + child: Row( + children: [ + Icon(Icons.mic, color: color), + const SizedBox(width: 8), + Text(_formatRecordDuration(_recordDuration)), + const SizedBox(width: 16), + Expanded( + child: Text( + _recordingLocked + ? 'recordingLocked'.tr() + : (_cancelRecording + ? 'releaseToCancel'.tr() + : 'slideToCancel'.tr()), + style: TextStyle(color: Colors.grey[600]), + overflow: TextOverflow.ellipsis, + ), + ), + IconButton( + tooltip: 'cancel'.tr(), + onPressed: _cancelRecordingGesture, + icon: const Icon(Icons.delete), + color: Colors.red, + ), + IconButton( + tooltip: 'send'.tr(), + onPressed: _stopRecording, + icon: const Icon(Icons.send), + color: color, + ), + ], + ), + ); + } + + /// Avatar + name header shown above the oldest message. + Widget _buildHeader() { + return Center( + child: Padding( + padding: const EdgeInsets.only(top: 20, bottom: 20), + child: Column( + children: [ + CircleAvatar( + radius: 50, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 40, + color: widget.user.avatarTextColor, + ), + ), + ), + const SizedBox(height: 12), + Text( + widget.user.username, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 30), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 50), + child: Text('legendaryChat'.tr(), textAlign: TextAlign.center)), + ], + ), + ), + ); + } + + /// The "new messages" divider, drawn above the first unread message. + Widget _buildUnreadDivider() { + // The picked chat color itself: this helper runs above the chat Theme, so + // Theme.of(context) would be the app theme. + final color = _chatThemeColor ?? Singleton().appTheme.color; + return Padding( + key: _unreadDividerKey, + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + child: Row( + children: [ + Expanded(child: Divider(color: color)), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Text( + 'newMessages'.tr(), + style: TextStyle( + fontSize: 12, color: color, fontWeight: FontWeight.bold), + ), + ), + Expanded(child: Divider(color: color)), + ], + ), + ); + } + + /// Calendar day a message belongs to, in the timezone the bubble shows. + DateTime _dayOf(PrivateMessage message) { + final time = (message.isMe ? message.sentAt : message.receivedAt).toLocal(); + return DateTime(time.year, time.month, time.day); + } + + String _dayLabel(DateTime day) { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final days = today.difference(day).inDays; + if (days <= 0) { + return 'todayText'.tr(); + } + if (days == 1) { + return 'yesterdayText'.tr(); + } + if (days < 7) { + return DateFormat.EEEE().format(day); + } + if (day.year == now.year) { + return DateFormat.MMMMd().format(day); + } + return DateFormat.yMMMMd().format(day); + } + + Widget _buildBubble( + PrivateMessage message, PrivateMessage? older, PrivateMessage? newer, + {bool? showAvatar}) { + final micros = message.sentAt.microsecondsSinceEpoch; + final key = _messageKeys.putIfAbsent(micros, () => GlobalKey()); + final showsDivider = _unreadAnchor?.microsecondsSinceEpoch == micros; + final bubble = ChatBubble( + older, + message, + newer, + widget.user, + key: key, + // The picked chat color itself, not a tonal derivative of it. + accentColor: _chatThemeColor ?? Singleton().appTheme.color, + selectionMode: _selectionMode, + selected: _selected.contains(micros), + highlight: _highlightMicros == micros, + showAvatar: showAvatar, + readAt: micros == _lastOwnMicros && _readReceipts ? _peerReadAt : null, + onSelect: () => _toggleSelected(message), + onActions: () => _openMessageActions(message), + onReactions: () => + MessageActions.showReactions(context, message, widget.user.id), + onQuickReact: () => MessageActions.react( + message, widget.user.id, MessageActions.quickReaction), + onReply: () => _startReply(message), + onTapQuote: message.isReply + ? () => _jumpToMessage(message.replyTo!.sentAt) + : null, + ); + if (!showsDivider) { + return bubble; + } + // The divider sits above its message and goes away once the day header + // does not repeat it. + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [_buildUnreadDivider(), bubble], + ); + } + + /// When the live-location session of this chat started, null when there is + /// none. Ordering the bubble by it keeps the chat chronological. + DateTime? _liveLocationStart() { + if (LiveLocationSharer.instance.isSharing(widget.user.id)) { + return LiveLocationSharer.instance.startedAt; + } + // Only while a position is still live: a stopped session leaves no bubble. + if (PresenceNotifier.instance.liveLocation(widget.user.id) == null) { + return null; + } + return PresenceNotifier.instance.liveStartedAt(widget.user.id); + } + + /// Messages, grouped by day: each day gets a sticky header. + Widget _getContent(List messages) { + final start = + messages.length > _visibleCount ? messages.length - _visibleCount : 0; + final visible = messages.sublist(start); + final hasOlder = start > 0; + + final days = >{}; + for (var i = 0; i < visible.length; i++) { + days.putIfAbsent(_dayOf(visible[i]), () => []).add(i); + } + // The live location takes the place of the message that would carry it: + // right after everything sent before the session started. -1 marks it in + // the day bucket. + final liveStart = _liveLocationStart(); + // Where the marker sits in the timeline: after visible[liveAfter], -1 when + // it precedes every message. -1 in a day bucket marks the marker itself. + var liveAfter = -1; + final liveMine = LiveLocationSharer.instance.isSharing(widget.user.id); + if (liveStart != null) { + final firstNewer = visible.indexWhere((m) => m.sentAt.isAfter(liveStart)); + liveAfter = (firstNewer < 0 ? visible.length : firstNewer) - 1; + final day = DateTime(liveStart.year, liveStart.month, liveStart.day); + final bucket = days.putIfAbsent(day, () => []); + var at = bucket.indexWhere((i) => visible[i].sentAt.isAfter(liveStart)); + if (at < 0) { + at = bucket.length; + } + bucket.insert(at, -1); + } + final orderedDays = days.keys.toList()..sort(); + + // The scroll view is reversed: the first sliver is painted at the bottom + // of the screen, so the days and their messages go newest first. Offset + // zero is the newest message, which is why opening the chat needs no jump + // and older pages cannot move what the user is reading. + return CustomScrollView( + controller: _scrollController, + reverse: true, + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics(), + ), + slivers: [ + // Reversed list: the first sliver sits at the visual bottom, so this + // spacer keeps the newest message above the composer bar. + SliverToBoxAdapter(child: SizedBox(height: _composerHeight)), + for (final day in orderedDays.reversed) ...[ + SliverList.builder( + itemCount: days[day]!.length, + itemBuilder: (context, index) { + final position = days[day]![days[day]!.length - 1 - index]; + if (position < 0) { + // The avatar belongs to whoever ends the run, here the marker + // itself when nothing follows it. + return LiveLocationBubble(widget.user, + showAvatar: !liveMine && liveAfter == visible.length - 1); + } + final message = visible[position]; + return _buildBubble( + message, + position > 0 ? visible[position - 1] : null, + position < visible.length - 1 ? visible[position + 1] : null, + // The marker continues the peer's run, so a message right + // before it is not the one that closes it. + showAvatar: !liveMine && position == liveAfter ? false : null, + ); + }, + ), + SliverPersistentHeader( + // A pinned header would stick to the bottom edge in a reversed + // view, so day separators scroll with their messages instead. + pinned: false, + delegate: _DayHeader( + label: _dayLabel(day), + textColor: Theme.of(context).colorScheme.onSurfaceVariant, + background: chatBackground(tintAlpha: 0.35), + ), + ), + ], + SliverToBoxAdapter( + child: hasOlder + ? const Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ) + : _buildHeader(), + ), + // The body sits behind the translucent app bar, so the conversation + // has to start below it: without this the avatar header and the first + // day separator are painted under the bar. + SliverToBoxAdapter( + child: SizedBox( + height: MediaQuery.viewPaddingOf(context).top + kToolbarHeight, + ), + ), + ], ); } @override void dispose() { + _noteHoldTimer?.cancel(); + MessageNotifier().removeListener(_onMessagesChanged); + PresenceNotifier.instance.removeListener(_onPresenceChanged); + _scrollController.removeListener(_onScroll); + WidgetsBinding.instance.removeObserver(_metricsObserver); + _recordTimer?.cancel(); + _highlightTimer?.cancel(); + if (_readPublish?.isActive ?? false) { + // Leaving within the debounce window used to drop the cursor; send it + // now, fire and forget (dispose cannot await). + _readPublish!.cancel(); + if (_readReceipts && _messages.isNotEmpty) { + unawaited( + utils.Utils.sendReadCursor(widget.user.id, _messages.last.sentAt)); + } + } + _readPublish?.cancel(); + _recorderController?.dispose(); + _notePlayback.dispose(); _controllerMessage.dispose(); _scrollController.dispose(); super.dispose(); } + /// Background tinted by the chat color: the M3 surface alone is almost + /// neutral, so a chat with its own color was indistinguishable from any other. + /// + /// [tintAlpha] overrides how much of the color goes in (the AppBar uses more + /// so the header reads as part of the conversation). + Color chatBackground({double? tintAlpha}) { + final scheme = Theme.of(context).colorScheme; + final accent = _chatThemeColor ?? Singleton().appTheme.color; + final double alpha = tintAlpha ?? + (Theme.of(context).brightness == Brightness.dark ? 0.16 : 0.12); + return Color.alphaBlend(accent.withValues(alpha: alpha), scheme.surface); + } + + /// The chat's own theme. [build] and its helpers run above the chat `Theme`, + /// so `Theme.of(context)` there is the app theme, not this conversation's. + ThemeData get chatTheme => ThemeUtils.chatTheme(context, _chatThemeColor); + + /// Repeating doodle pattern behind the messages, recolored by the theme so it + /// reads on a light and on a dark background. + DecorationImage chatPattern() { + return DecorationImage( + image: const AssetImage('assets/images/chat_bg.png'), + repeat: ImageRepeat.repeat, + scale: 3, + colorFilter: ColorFilter.mode( + Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.07), + BlendMode.srcIn), + ); + } + + /// AppBar color: a stronger tint, kept translucent so the blur still shows. + Color appBarBackground() { + final bool dark = Theme.of(context).brightness == Brightness.dark; + return chatBackground(tintAlpha: dark ? 0.30 : 0.22) + .withValues(alpha: 0.85); + } + + /// Chat AppBar, or the selection AppBar while messages are picked. + Widget _buildAppBarContent() { + if (_selectionMode) { + final single = + _selectedMessages.length == 1 ? _selectedMessages.first : null; + return AppBar( + automaticallyImplyLeading: false, + backgroundColor: appBarBackground(), + leading: IconButton( + icon: const Icon(Icons.close), + tooltip: 'cancel'.tr(), + onPressed: _clearSelection, + ), + title: Text(sprintf('selectedCount'.tr(), [_selected.length])), + actions: [ + IconButton( + icon: Icon(MessageActions.copyIcon), + tooltip: 'copyMessage'.tr(), + onPressed: _copySelected, + ), + IconButton( + icon: Icon(MessageActions.forwardIcon), + tooltip: 'forwardMessage'.tr(), + onPressed: _forwardSelected, + ), + IconButton( + icon: Icon(MessageActions.deleteIcon), + tooltip: 'deleteMessageForMe'.tr(), + onPressed: _deleteSelected, + ), + // Save, resend and the rest still live in the single-message sheet. + if (single != null) + IconButton( + icon: const Icon(Icons.more_vert), + tooltip: 'moreActions'.tr(), + onPressed: () => _withoutComposerFocus(() => + MessageActions.showSheet(context, single, widget.user.id)), + ), + ], + ); + } + return AppBar( + automaticallyImplyLeading: false, + backgroundColor: appBarBackground(), + leading: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.pop(context), + ), + GestureDetector( + onTap: _openChatInfo, + child: CircleAvatar( + radius: 18, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 16, + color: widget.user.avatarTextColor, + ), + ), + ), + ), + ], + ), + leadingWidth: 96, // Increase width to accommodate both icons + // Title + title: GestureDetector( + onTap: _openChatInfo, + behavior: HitTestBehavior.opaque, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(widget.user.username), + // One line of live status; it disappears when nothing is known so + // the header keeps its plain height. + if (PresenceNotifier.instance.statusText(widget.user.id) + case final status?) + Text( + status, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.normal, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + // Action buttons + actions: [ + IconButton( + icon: const Icon(Icons.info), + tooltip: 'infoButton'.tr(), + onPressed: _openChatInfo, + ), + ], + ); + } + + /// Measures the composer so the list can reserve exactly its height. + void _measureComposer() { + final render = _composerKey.currentContext?.findRenderObject(); + if (render is! RenderBox || !render.hasSize) { + return; + } + final height = render.size.height; + if ((height - _composerHeight).abs() > 0.5) { + setState(() => _composerHeight = height); + } + } + @override Widget build(BuildContext context) { - final notifier = context.watch(); - + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _measureComposer(); + } + }); + // A bottomNavigationBar is anchored to the screen bottom, not to the + // keyboard: with edge-to-edge the window is no longer resized for the IME, + // so the bar has to carry the inset itself or the field hides behind the + // keyboard. It stays inside the measured composer, so the list reserves + // the room. + final keyboardInset = MediaQuery.viewInsetsOf(context).bottom; return PopScope( onPopInvokedWithResult: (didPop, _) async { if (didPop && _messages.isNotEmpty) { @@ -202,133 +2350,242 @@ class _ChatPageState extends State { } } }, - child: Scaffold( - extendBodyBehindAppBar: true, - appBar: PreferredSize( - preferredSize: Size( - double.infinity, - 56.0, + child: Theme( + data: ThemeUtils.chatTheme(context, _chatThemeColor), + child: Scaffold( + extendBodyBehindAppBar: true, + backgroundColor: chatBackground(), + appBar: PreferredSize( + preferredSize: Size( + double.infinity, + 56.0, + ), + child: ClipRRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), + child: _buildAppBarContent(), + ), + ), ), - child: ClipRRect( - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), - child: AppBar( - automaticallyImplyLeading: false, - backgroundColor: Theme.of(context) - .colorScheme - .surface - .withValues(alpha: 0.2), - leading: Row( + // The message list runs behind the composer bar, so a tall bubble is + // never cut off at the input's edge. + extendBody: true, + // Transparent on purpose: the chat background and the messages + // slide under the composer instead of a filled band behind it. + bottomNavigationBar: Container( + key: _composerKey, + padding: EdgeInsets.only(bottom: keyboardInset), + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisSize: MainAxisSize.min, children: [ - IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () => Navigator.pop(context), - ), - CircleAvatar( - radius: 18, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 16, - color: widget.user.avatarTextColor, + if (_replyTo != null) _buildReplyBar(), + if (_isRecordingNote) _buildRoundNotePreview(), + if (PresenceNotifier.instance.isTyping(widget.user.id)) + Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 4), + child: Align( + alignment: Alignment.centerLeft, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + // The same avatar the bubbles and the chat list + // draw, one size smaller. + CircleAvatar( + radius: 10, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 10, + color: widget.user.avatarTextColor, + ), + ), + ), + const SizedBox(width: 6), + TypingDots( + color: Theme.of(context) + .colorScheme + .onSurfaceVariant, + ), + ], + ), ), ), + Stack( + alignment: Alignment.center, + children: [ + _buildInputBar(), + if (_isRecording) + Positioned.fill(child: _buildRecordingBar()), + ], ), ], ), - leadingWidth: 96, // Increase width to accommodate both icons - // Title - title: Text(widget.user.username), - // Action buttons - actions: [ - IconButton( - icon: const Icon(Icons.info), - tooltip: 'infoButton'.tr(), - onPressed: () { - // Push info page - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.rightToLeftJoined, - child: ChatInfoPage(widget.user.id), - childCurrent: widget)); - }, - ), - ], ), ), ), - ), - body: Column( - children: [ - // Messages and avatar list - Expanded( - child: FutureBuilder>( - future: notifier.getMessages(widget.user.id), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting && - _firstLoad) { - return Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), - ), - ); - } - // Set data - if (snapshot.hasData) { - WidgetsBinding.instance.addPostFrameCallback((_) { - _scrollController - .jumpTo(_scrollController.position.maxScrollExtent); - }); - _messages = snapshot.data!; - } - // Return messages - return _getContent(_messages); - }), - ), - SafeArea( - top: false, - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Row( - children: [ - Expanded( - child: Padding( - padding: EdgeInsets.only(right: 5, left: 5), - // TODO certically expandable text field - child: TextField( - controller: _controllerMessage, - decoration: InputDecoration( - hintText: 'yourMessage'.tr(), - filled: true, - fillColor: Theme.of(context).brightness == - Brightness.dark - ? Theme.of(context).colorScheme.surfaceBright - : Theme.of(context).colorScheme.surfaceDim, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(30), - borderSide: BorderSide.none, - ), - suffixIcon: IconButton( - onPressed: _isSending ? null : _sendMessage, - icon: const Icon(Icons.send), + body: Container( + decoration: BoxDecoration(image: chatPattern()), + child: RoundNoteScope( + playback: _notePlayback, + child: Stack( + children: [ + Column( + children: [ + // Messages and avatar list + Expanded( + child: Stack( + children: [ + _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ) + : _getContent(_messages), + // Floating "down" button: up whenever the viewport is + // far from the newest message, and carrying the count + // of what arrived while the user was reading above. + Positioned( + right: 16, + bottom: _composerHeight + 16, + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 200), + transitionBuilder: (child, animation) => + FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: Tween(begin: 0.8, end: 1) + .animate(animation), + child: child, + ), + ), + child: !_firstLoad && + (_farFromBottom || _unseenCount > 0) + ? FloatingActionButton.small( + key: const ValueKey('jumpToLatest'), + heroTag: 'jumpToBottom', + tooltip: 'jumpToLatest'.tr(), + onPressed: () => + _jumpToBottom(animate: true), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.arrow_downward, + size: 16), + if (_unseenCount > 1) + Padding( + padding: const EdgeInsets.only( + left: 2), + child: Text('$_unseenCount', + style: const TextStyle( + fontSize: 11)), + ), + ], + ), + ) + : const SizedBox.shrink(), + ), ), - ), + ], ), ), + ], + ), + // Right under the header, over the list: the pins are where the + // eye looks first and the composer stays clean. + Positioned( + top: kToolbarHeight + MediaQuery.of(context).padding.top, + left: 0, + right: 0, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_pinnedInOrder.isNotEmpty) _buildPinBar(), + // A round note that keeps playing once its circle left + // the viewport: the copy hangs under the strip above. + Padding( + padding: const EdgeInsets.only(top: 8, right: 12), + child: Align( + alignment: Alignment.topRight, + child: PinnedRoundNote(playback: _notePlayback), + ), + ), + ], ), - ], - ), + ), + ], ), ), - ], + ), + ), + ), + ); + } +} + +/// Sticky day label above the messages of one calendar day. +class _DayHeader extends SliverPersistentHeaderDelegate { + _DayHeader({ + required this.label, + required this.textColor, + required this.background, + }); + + final String label; + final Color textColor; + final Color background; + + @override + double get minExtent => 34; + + @override + double get maxExtent => 34; + + @override + Widget build( + BuildContext context, double shrinkOffset, bool overlapsContent) { + return Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: textColor, + ), ), ), ); } + + @override + bool shouldRebuild(covariant _DayHeader oldDelegate) => + oldDelegate.label != label || + oldDelegate.textColor != textColor || + oldDelegate.background != background; +} + +/// Fires [onMetricsChanged] when the keyboard opens or closes. +class _KeyboardObserver extends WidgetsBindingObserver { + _KeyboardObserver(this.onMetricsChanged); + + final VoidCallback onMetricsChanged; + + @override + void didChangeMetrics() { + onMetricsChanged(); + } } diff --git a/lib/pages/devices_page.dart b/lib/pages/devices_page.dart new file mode 100644 index 0000000..add49f2 --- /dev/null +++ b/lib/pages/devices_page.dart @@ -0,0 +1,175 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:shept_openapi_client_dart/api.dart'; + +import '../utils/singleton.dart'; +import '../utils/utils.dart'; + +/// Devices signed into the account, with revoke and unrevoke. +/// +/// Revoking is the hard lockout: the device loses its socket, its refresh +/// sessions and every request it makes from then on, even though it still holds +/// the account key. +class DevicesPage extends StatefulWidget { + const DevicesPage({super.key}); + + @override + State createState() => _DevicesPageState(); +} + +class _DevicesPageState extends State { + List _devices = []; + bool _loading = true; + bool _busy = false; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + final response = + await Utils.callApi(() => Singleton().userApi.getDevices()); + if (!mounted) { + return; + } + setState(() { + _devices = response?.devices ?? []; + _loading = false; + }); + } + + /// Revokes or unrevokes one device and refreshes the list. + Future _setRevoked(ModelsDevice device, bool revoke) async { + if (_busy) { + return; + } + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(revoke ? 'revokeDevice'.tr() : 'unrevokeDevice'.tr()), + content: Text(revoke + ? 'revokeDeviceConfirm'.tr(args: [device.label]) + : 'unrevokeDeviceConfirm'.tr(args: [device.label])), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text('cancel'.tr()), + ), + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(true), + child: Text('confirm'.tr()), + ), + ], + ), + ); + if (confirmed != true || !mounted) { + return; + } + setState(() { + _busy = true; + }); + await Utils.callApi(() => revoke + ? Singleton().userApi.revokeDevice(device.id) + : Singleton().userApi.unrevokeDevice(device.id)); + if (!mounted) { + return; + } + setState(() { + _busy = false; + }); + await Fluttertoast.showToast( + msg: revoke ? 'deviceRevokedToast'.tr() : 'deviceUnrevokedToast'.tr(), + backgroundColor: Colors.grey); + await _load(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text('devicesPage'.tr())), + body: SafeArea( + child: _loading + ? const Center(child: CircularProgressIndicator()) + : RefreshIndicator( + onRefresh: _load, + child: ListView.builder( + itemCount: _devices.length, + itemBuilder: (context, index) { + final device = _devices[index]; + final revoked = device.revokedAt != null; + return ListTile( + leading: Icon( + device.platform == 'android' || device.platform == 'ios' + ? Icons.smartphone + : Icons.computer, + color: revoked + ? Theme.of(context).disabledColor + : Theme.of(context).colorScheme.secondary, + ), + title: Row( + children: [ + Flexible( + child: Text( + device.label, + overflow: TextOverflow.ellipsis, + style: revoked + ? TextStyle( + decoration: TextDecoration.lineThrough, + color: Theme.of(context).disabledColor) + : null, + ), + ), + if (device.current == true) + Padding( + padding: const EdgeInsets.only(left: 6), + child: Text( + 'thisDevice'.tr(), + style: TextStyle( + fontSize: 12, + color: Theme.of(context) + .colorScheme + .secondary), + ), + ), + ], + ), + subtitle: Text( + revoked + ? 'deviceRevokedAt'.tr(args: [ + DateFormat.yMd(context.locale.toString()) + .add_Hm() + .format(device.revokedAt!.toLocal()) + ]) + : 'deviceLastSeen'.tr(args: [ + DateFormat.yMd(context.locale.toString()) + .add_Hm() + .format(device.lastSeenAt.toLocal()) + ]), + ), + trailing: device.current == true + ? null + : TextButton( + onPressed: _busy + ? null + : () => _setRevoked(device, !revoked), + child: Text( + revoked ? 'unrevoke'.tr() : 'revoke'.tr(), + style: TextStyle( + color: revoked + ? Theme.of(context) + .colorScheme + .secondary + : Colors.red), + ), + ), + ); + }, + ), + ), + ), + ); + } +} diff --git a/lib/pages/forward_page.dart b/lib/pages/forward_page.dart new file mode 100644 index 0000000..150d309 --- /dev/null +++ b/lib/pages/forward_page.dart @@ -0,0 +1,130 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../models/private_message.dart'; +import '../models/user.dart'; +import '../utils/chat_sender.dart'; +import '../utils/media_utils.dart'; +import '../utils/message_notifier.dart'; +import '../widgets/user_list_item.dart'; +import 'search_user_page.dart'; +import '../utils/nav_transitions.dart'; + +/// Picks the destination of forwarded messages: an existing conversation or a +/// user found by search. Sends the messages and closes itself. +class ForwardPage extends StatefulWidget { + const ForwardPage(this.messages, {super.key}); + final List messages; + + @override + State createState() => _ForwardPageState(); +} + +class _ForwardPageState extends State { + List _chats = []; + bool _sending = false; + + @override + void initState() { + super.initState(); + _loadChats(); + } + + Future _loadChats() async { + final chats = await MessageNotifier().getLatestPrivateMessages(); + if (mounted) { + setState(() { + _chats = chats.keys.toList(); + }); + } + } + + Future _forward(User to) async { + if (_sending) { + return; + } + setState(() { + _sending = true; + }); + try { + var allSent = true; + for (final message in widget.messages) { + bool sent; + if (message.isMedia) { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + // Save/forward are hidden for attachments that are not on disk. + allSent = false; + continue; + } + final bytes = await MediaUtils.decryptAtRest(path); + sent = await ChatSender.sendMedia(to, type, bytes, + caption: message.message, + width: message.width, + height: message.height, + durationMs: message.durationMs, + fileName: message.fileName, + forwarded: true); + } else { + sent = + await ChatSender.sendText(to, message.message, forwarded: true); + } + allSent = allSent && sent; + } + if (!mounted) { + return; + } + if (allSent) { + Fluttertoast.showToast(msg: 'forwarded'.tr()); + Navigator.pop(context); + } + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + } finally { + if (mounted) { + setState(() { + _sending = false; + }); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('forwardTo'.tr()), + actions: [ + IconButton( + icon: const Icon(Icons.search), + tooltip: 'searchUserPage'.tr(), + onPressed: () { + Navigator.of(context) + .push(stepRoute(SearchUserPage(onUserSelected: (user) { + // Close the search page, _forward closes this one + Navigator.pop(context); + _forward(user); + }))); + }, + ), + ], + ), + body: SafeArea( + child: _chats.isEmpty + ? Center(child: Text('noChatsToForward'.tr())) + : ListView.builder( + itemCount: _chats.length, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: UserListItem( + _chats[index], () => _forward(_chats[index])), + ); + }, + ), + ), + ); + } +} diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index dd71350..09a1755 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -2,26 +2,32 @@ import 'dart:async'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; -import 'package:firebase_messaging/firebase_messaging.dart'; +// Firebase is retired; dependency is commented out in pubspec.yaml. +// import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:page_transition/page_transition.dart'; -import 'package:provider/provider.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import '../utils/nav_transitions.dart'; +import 'package:sprintf/sprintf.dart'; import '../pages/chat_page.dart'; import '../utils/websocket_manager.dart'; import '../widgets/chat_list_item.dart'; import '../models/private_message.dart'; import '../utils/cache_utils.dart'; import '../utils/message_notifier.dart'; +import '../utils/notification_service.dart'; import 'search_user_page.dart'; import 'settings_page.dart'; import '../utils/dialog_utils.dart'; import '../widgets/invite_list_item.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../models/user.dart'; +import '../utils/admin_format.dart'; import '../utils/singleton.dart'; +import '../utils/screen_guard.dart'; +import '../utils/share_intent.dart'; import '../utils/utils.dart'; -import '../widgets/select_user_list_item.dart'; +import '../widgets/admin_user_list_item.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @@ -30,19 +36,52 @@ class HomePage extends StatefulWidget { State createState() => _HomePageState(); } -class _HomePageState extends State { +/// Which rows the chat list shows. +/// +/// The roadmap lists folders for unread and favourites; favourites arrive in F7 +/// with contacts, so the pinned chats stand in for them. +enum _ChatFilter { all, unread, pinned } + +class _HomePageState extends State + with SingleTickerProviderStateMixin, WidgetsBindingObserver { final WebSocketManager _webSocketManager = WebSocketManager(); List _serverUsers = []; - List _selectedUsers = []; int _currentPageIndex = 0; List _serverInvites = []; - Map _chats = {}; + List> _chatEntries = []; + + /// Unread incoming messages per conversation id, for the list badges. + Map _unreadCounts = {}; + + /// Conversation ids pinned to the top of the list. + Set _pinnedChats = {}; + + /// Read cursors of the chats that publish receipts, for the seen ticks. + Map _peerReadAts = {}; + + /// The folder strip floats over the list, so its height is measured instead + /// of taking layout space; the list pads itself by the same amount. + final GlobalKey _filterKey = GlobalKey(); + double _filterHeight = 0; + + /// Which rows the list shows; folders without extra storage. + _ChatFilter _filter = _ChatFilter.all; bool _firstLoad = true; - String? _pendingFcmToken; // Store pending token + String? _pendingFid; // Store pending FID + + // Kept in state so switching the bottom navigation back to the admin panel + // does not drop the selected sub-tab. + late final TabController _adminTabController = + TabController(length: 2, vsync: this); + bool _usersLoading = true; + bool _usersError = false; + bool _invitesLoading = true; + bool _invitesError = false; @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); // Load all server users and invites if admin if (Singleton().profile.user.admin) { _getServerUsers(); @@ -50,71 +89,136 @@ class _HomePageState extends State { } // Get all conversations with their last messages _getConversations(); + // Refresh the list when a message arrives or its state changes; the build + // method must not create a new future on every rebuild. + MessageNotifier().addListener(_onMessagesChanged); + // A screenshot outside the view-once viewer is reported, not blocked: the + // app cannot prevent it, and pretending otherwise would be a lie. + ScreenGuard.onScreenshot = _onScreenshot; + ScreenGuard.start(); + // A pending FCM id is retried when the socket comes up instead of polling. + Utils.onConnected = _sendPendingFid; + // Open the chat a notification tap pointed at (after unlocking) + _openPendingChat(); + // Pictures, videos and links shared from other apps. Started here rather + // than at launch, so a share can never open over the password screen. + SharedInbox.start(); + // Taps arriving while Home is alive open the chat right away + NotificationService.onChatSelected = _openChat; // Start checking WebSocket connection _webSocketManager.startConnectionCheck(); - // Request FCM notification permissions - FirebaseMessaging.instance.requestPermission(provisional: true); - - // FCM token refresh - store token and send when online - FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) async { - _pendingFcmToken = fcmToken; - await _sendFcmTokenWhenOnline(fcmToken); - }).onError((err) { - if (kDebugMode) { - debugPrint('Error getting FCM token: $err'); - } - }); + // Firebase is retired: FCM registration is commented out, the app still + // compiles and runs without push. + // // Request FCM notification permissions + // FirebaseMessaging.instance.requestPermission(provisional: true); + // + // // FID registration - store FID and send when online + // FirebaseMessaging.instance.onRegistered.listen((fid) async { + // _pendingFid = fid; + // await _sendPushTargetWhenOnline(fid); + // }).onError((err) { + // if (kDebugMode) { + // debugPrint('Error getting FID: $err'); + // } + // }); + // + // // Enable FCM notifications + // FirebaseMessaging.instance.setAutoInitEnabled(true); + // + // // A foreground push is not shown by the OS; show it ourselves. + // _fcmSubscription = FirebaseMessaging.onMessage.listen((message) { + // final notification = message.notification; + // if (notification == null) { + // return; + // } + // NotificationService().showSecurityNotification( + // notification.title ?? 'newLoginTitle'.tr(), + // notification.body ?? '', + // ); + // }); + // + // // Register with FCM, the FID arrives via onRegistered + // _registerForPush(); + } - // Enable FCM notifications - FirebaseMessaging.instance.setAutoInitEnabled(true); + /// Foreground pushes: the server warns the other devices about a new login, + /// and a foreground app has to show that itself. + /// Firebase is retired; kept commented so the type reference does not pull + /// the dependency back in. + // StreamSubscription? _fcmSubscription; - // Set initial FCM token - _setFcmToken(); + /// A screenshot of an ordinary message cannot be stopped, only noticed. + void _onScreenshot() { + Fluttertoast.showToast( + msg: 'screenshotDetected'.tr(), backgroundColor: Colors.orange); + } - // Listen to offline mode changes to send pending tokens - _listenToConnectivityChanges(); + /// Presence is announced when the app comes back and withdrawn when it goes + /// away: the server keeps nothing, so a stale "online" would never clear. @override + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + Utils.announcePresence(); + // A message whose deadline passed while the app was in the background is + // gone before it paints again. + CacheUtils.purgeExpiredMessages().then((_) => MessageNotifier().notify()); + } else if (state == AppLifecycleState.paused) { + Utils.withdrawPresence(); + } } @override void dispose() { + WidgetsBinding.instance.removeObserver(this); + ScreenGuard.onScreenshot = null; + // _fcmSubscription?.cancel(); + _adminTabController.dispose(); + MessageNotifier().removeListener(_onMessagesChanged); + if (NotificationService.onChatSelected == _openChat) { + NotificationService.onChatSelected = null; + } + if (Utils.onConnected == _sendPendingFid) { + Utils.onConnected = null; + } super.dispose(); // Stop checking WebSocket connection _webSocketManager.stopConnectionCheck(); } - /// Listen to connectivity changes and send pending FCM token - void _listenToConnectivityChanges() { - // Check periodically if we came back online and have a pending token - Timer.periodic(Duration(seconds: 30), (timer) { - if (!Singleton().offlineMode && _pendingFcmToken != null) { - _sendFcmTokenWhenOnline(_pendingFcmToken!); - } - }); + /// Reload the conversation list after a message or its send/media state + /// changed. + void _onMessagesChanged() { + _getConversations(); } - /// Set FCM token on server with offline mode handling - Future _setFcmToken() async { - try { - var token = await FirebaseMessaging.instance.getToken(); - if (token == null) { - return; - } - _pendingFcmToken = token; - await _sendFcmTokenWhenOnline(token); - } catch (e) { - if (kDebugMode) { - debugPrint('Error setting FCM token: $e'); - } + /// Push a pending Firebase installation id once the socket is up. + Future _sendPendingFid() async { + final fid = _pendingFid; + if (fid == null) { + return; } + await _sendPushTargetWhenOnline(fid); } - - /// Send FCM token when online, store when offline - Future _sendFcmTokenWhenOnline(String token) async { + + /// Register with FCM, the FID arrives via onRegistered + /// Firebase is retired; kept commented so the dependency stays out. + // Future _registerForPush() async { + // try { + // await FirebaseMessaging.instance.register(); + // } catch (e) { + // if (kDebugMode) { + // debugPrint('Error registering with FCM: $e'); + // } + // } + // } + + /// Send FID when online, store when offline + Future _sendPushTargetWhenOnline(String fid) async { // Skip if in offline mode if (Singleton().offlineMode) { if (kDebugMode) { - debugPrint('Offline mode - FCM token will be sent when online'); + debugPrint('Offline mode - FID will be sent when online'); } return; } @@ -122,122 +226,302 @@ class _HomePageState extends State { try { await Utils.callApi( () => Singleton().firebaseApi.setFirebaseToken( - setFirebaseTokenInput: SetFirebaseTokenInput(token: token)), + setFirebaseTokenInput: SetFirebaseTokenInput(token: fid)), useSecurity: true, - ).timeout( - Duration(seconds: 10), - onTimeout: () => null, - ); + ).timeout(Duration(seconds: 10)); + // Sent; the retry loop only covers values that never made it + if (_pendingFid == fid) { + _pendingFid = null; + } } catch (e) { - // Error occurred, keep token pending - _pendingFcmToken = token; + // Error occurred, keep FID pending + _pendingFid = fid; if (kDebugMode) { - debugPrint('Error sending FCM token: $e'); + debugPrint('Error sending FID: $e'); } } } /// Get all conversations with their last messages Future _getConversations() async { - _chats = await CacheUtils.getLatestPrivateMessages(); - if (context.mounted) { - setState(() {}); + final chats = await CacheUtils.getLatestPrivateMessages(); + final unread = await CacheUtils.getUnreadCounts(); + final pinned = await CacheUtils.getPinnedConversations(); + final peerReadAts = await CacheUtils.peerReadAts(); + if (!mounted) { + return; } + setState(() { + _chatEntries = chats.entries.toList(); + _unreadCounts = unread; + _pinnedChats = pinned; + _peerReadAts = peerReadAts; + _firstLoad = false; + }); + } + + /// Pin or unpin a conversation. Local only: nothing is sent to the server. + Future _togglePin(User user) async { + final pinned = _pinnedChats.contains(user.id); + await CacheUtils.setConversationPinned(user.id, !pinned); + if (!mounted) { + return; + } + Fluttertoast.showToast( + msg: pinned ? 'chatUnpinned'.tr() : 'chatPinned'.tr()); + await _getConversations(); + } + + /// Delete a conversation after the confirmation dialog confirmed it. + void _deleteChat(User user) { + DialogUtils.yesNoDialog( + context, 'deleteChatConfirm'.tr(), 'deleteChatConfirmText'.tr(), + () async { + final deleted = await MessageNotifier().deleteChat(user.id); + if (!deleted) { + Fluttertoast.showToast( + msg: 'deleteChatFailed'.tr(), backgroundColor: Colors.red); + } + await _getConversations(); + }); + } + + /// Icon shown under a swiped chat row. + Widget _swipeBackground(Alignment alignment, IconData icon, Color color) { + return Container( + alignment: alignment, + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Icon(icon, color: color), + ); } /// Get server users Future _getServerUsers() async { - if (mounted) { - setState(() { - _serverUsers = []; - _selectedUsers = []; - }); - var users = await Utils.callApi(() => Singleton().userApi.getAllUsers()); + if (!mounted) { + return; + } + setState(() { + _usersError = false; + _usersLoading = true; + }); + final users = await Utils.callApi(() => Singleton().userApi.getAllUsers()); + if (!mounted) { + return; + } + setState(() { + // A failed refresh keeps the rows that are already on screen. + _usersError = users == null; if (users != null) { - for (var x in users) { - _serverUsers.add(User.fromModel(x)); - } - if (mounted) { - setState(() {}); - } + _serverUsers = sortedByUsername(users.map(User.fromModel).toList()); } + _usersLoading = false; + }); + } + + /// Delete one user after the confirmation dialog confirmed it. + Future _deleteUser(User user) async { + try { + await Utils.callApi( + () => Singleton() + .userApi + .deleteUsers(deleteUsersInput: DeleteUsersInput(ids: [user.id])), + rethrowErr: true, + ); + } catch (_) { + // Utils.callApi already surfaced the error as a red toast. + return; + } + if (!mounted) { + return; } + Fluttertoast.showToast( + msg: 'userDeleted'.tr(), backgroundColor: Colors.grey); + await _getServerUsers(); } - /// Delete selected users - Future _deleteSelectedUsers() async { + /// Get server invites + Future _getServerInvites() async { + if (!mounted) { + return; + } setState(() { - _serverUsers = - []; // I am unable to deactivate the user checkbox, so I will make all the users vanish so it will reset itself :) + _invitesError = false; + _invitesLoading = true; }); - // Delete selected users - await Utils.callApi(() => Singleton() - .userApi - .deleteUsers(deleteUsersInput: DeleteUsersInput(ids: _selectedUsers))); + final invites = + await Utils.callApi(() => Singleton().inviteApi.getAllInvites()); + if (!mounted) { + return; + } setState(() { - _selectedUsers = []; + _invitesError = invites == null; + if (invites != null) { + _serverInvites = invites; + } + _invitesLoading = false; }); - // Refresh users - await _getServerUsers(); } - /// Get server invites - Future _getServerInvites() async { - if (mounted) { - setState(() { - _serverInvites = []; - }); - var invites = - await Utils.callApi(() => Singleton().inviteApi.getAllInvites()); - if (mounted) { - setState(() { - if (invites != null) { - _serverInvites = invites; - } - }); + /// Open the chat of [userId] on top of Home. + Future _openChat(String userId) async { + final user = await CacheUtils.getUserById(userId); + if (user == null || !mounted) { + return; + } + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; } + Navigator.of(context).push(slideUpRoute(ChatPage(user))); + }); + } + + /// Open the chat a notification tap pointed at. This also covers a locked + /// app: the tap is remembered and the chat opens after the password page + /// replaced itself with HomePage. + Future _openPendingChat() async { + final userId = Singleton().pendingChatUserId; + if (userId == null) { + return; } + Singleton().pendingChatUserId = null; + await _openChat(userId); } - /// Shows new invite dialog. + /// Shows new invite dialog. It has no cancel path, so closing it always + /// means an invite was created. Future _createNewInvite(BuildContext context) async { - await showDialog(context: context, builder: DialogUtils.inviteDialog) - .then((_) async { - await _getServerInvites(); - }); + await showDialog(context: context, builder: DialogUtils.inviteDialog); + await _getServerInvites(); + } + + /// Chats that pass the current folder filter. + List> get _visibleChats { + switch (_filter) { + case _ChatFilter.unread: + return _chatEntries + .where((chat) => (_unreadCounts[chat.key.id] ?? 0) > 0) + .toList(); + case _ChatFilter.pinned: + return _chatEntries + .where((chat) => _pinnedChats.contains(chat.key.id)) + .toList(); + case _ChatFilter.all: + return _chatEntries; + } + } + + String _filterLabel(_ChatFilter filter) { + switch (filter) { + case _ChatFilter.all: + return 'allChats'.tr(); + case _ChatFilter.unread: + return 'unreadChats'.tr(); + case _ChatFilter.pinned: + return 'pinnedChats'.tr(); + } + } + + /// Folder chips above the list: everything, unread, pinned. + Widget _filterChips() { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + children: [ + for (final filter in _ChatFilter.values) + Padding( + padding: const EdgeInsets.only(right: 8), + child: ChoiceChip( + label: Text(_filterLabel(filter)), + selected: _filter == filter, + onSelected: (_) => setState(() { + _filter = filter; + }), + ), + ), + ], + ), + ); } /// Get ListView with content - ListView _getContent(Map chats) { + ListView _getContent(List> chats) { _firstLoad = false; return ListView.builder( physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics(), ), + // The list runs behind the translucent app bar and under the floating + // folder strip, so it pads itself instead of using the automatic + // MediaQuery padding. + padding: EdgeInsets.only( + top: MediaQuery.viewPaddingOf(context).top + + kToolbarHeight + + _filterHeight, + ), itemCount: chats.length, itemBuilder: (context, index) { - final chat = chats.entries.elementAt(index); + // Indexed access: `Map.entries.elementAt` is O(n) and made the list + // build O(n^2). + final chat = chats[index]; + final scheme = Theme.of(context).colorScheme; return Padding( padding: EdgeInsets.only(right: 5, left: 5, bottom: 3), - child: ChatListItem(chat.key, chat.value, () { - // Push to chat - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.bottomToTopJoined, - child: ChatPage(chat.key), - childCurrent: widget)); - }), + // Swipe right pins, swipe left deletes. Both spring back: the gesture + // opens an action, it never removes a row on its own. + child: Dismissible( + key: ValueKey('chat|${chat.key.id}'), + direction: DismissDirection.horizontal, + background: _swipeBackground( + Alignment.centerLeft, Icons.push_pin, scheme.primary), + secondaryBackground: _swipeBackground( + Alignment.centerRight, Icons.delete, scheme.error), + confirmDismiss: (direction) async { + if (direction == DismissDirection.startToEnd) { + await _togglePin(chat.key); + } else { + _deleteChat(chat.key); + } + return false; + }, + child: ChatListItem( + chat.key, + chat.value, + () { + // Push to chat + Navigator.of(context).push(slideUpRoute(ChatPage(chat.key))); + }, + unreadCount: _unreadCounts[chat.key.id] ?? 0, + pinned: _pinnedChats.contains(chat.key.id), + peerReadAt: _peerReadAts[chat.key.id], + ), + ), ); }, ); } + /// Measures the folder strip: it floats over the list, so the list needs its + /// height as padding rather than as layout space. + void _measureFilters() { + final render = _filterKey.currentContext?.findRenderObject(); + if (render is! RenderBox || !render.hasSize) { + return; + } + final height = render.size.height; + if ((height - _filterHeight).abs() > 0.5) { + setState(() => _filterHeight = height); + } + } + @override Widget build(BuildContext context) { - final notifier = context.watch(); - + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _currentPageIndex == 0) { + _measureFilters(); + } + }); return Scaffold( extendBodyBehindAppBar: true, appBar: _currentPageIndex == 0 @@ -253,7 +537,7 @@ class _HomePageState extends State { backgroundColor: Theme.of(context) .colorScheme .surface - .withValues(alpha: 0.2), + .withValues(alpha: 0.5), // User icon with first letter leading: Transform.scale( scale: 0.65, @@ -284,14 +568,7 @@ class _HomePageState extends State { icon: const Icon(Icons.settings), tooltip: 'settingsButton'.tr(), onPressed: () { - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.rightToLeftJoined, - child: SettingsPage(), - childCurrent: widget, - )); + Navigator.of(context).push(stepRoute(SettingsPage())); }, ), ], @@ -301,31 +578,19 @@ class _HomePageState extends State { ) : null, resizeToAvoidBottomInset: false, - // Floating button - floatingActionButton: FloatingActionButton( - onPressed: _currentPageIndex == 0 - ? () { - Navigator.of(context).push(PageTransition( - duration: const Duration(milliseconds: 300), - reverseDuration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - type: PageTransitionType.bottomToTopJoined, - child: SearchUserPage(), - childCurrent: widget)); - } - : () async { - await _createNewInvite(context); + // Floating button, only on the messages tab; the invites tab has its own + floatingActionButton: _currentPageIndex == 0 + ? FloatingActionButton( + onPressed: () { + Navigator.of(context).push(stepRoute(SearchUserPage())); }, - shape: const CircleBorder(), - foregroundColor: Theme.of(context).colorScheme.surface, - backgroundColor: Theme.of(context).colorScheme.primary, - tooltip: _currentPageIndex == 0 - ? 'addChat'.tr() - : 'newInvite'.tr(), // Change tooltip according to page index - child: Icon(_currentPageIndex == 0 - ? Icons.add_comment - : Icons.person_add), // Change icon according to page index - ), + shape: const CircleBorder(), + foregroundColor: Theme.of(context).colorScheme.surface, + backgroundColor: Theme.of(context).colorScheme.primary, + tooltip: 'addChat'.tr(), + child: const Icon(Icons.add_comment), + ) + : null, // Bottom navigation bar for admin only bottomNavigationBar: Singleton().profile.user.admin ? SafeArea( @@ -356,132 +621,204 @@ class _HomePageState extends State { // Body body: [ // Messages - Column( + Stack( children: [ - SizedBox(height: 10), - // Messages and avatar list - Expanded( - child: FutureBuilder>( - future: notifier.getLatestPrivateMessages(), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting && - _firstLoad) { - return Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), - ), - ); - } - // Set data - if (snapshot.hasData) { - _chats = snapshot.data!; - } - // Return chats - return _getContent(_chats); - }), + // Messages and avatar list, behind the chips: rows scroll under + // them instead of being cut off by a strip of background. + Positioned.fill( + child: _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ) + : _visibleChats.isEmpty + ? Center(child: Text('noChatsInFilter'.tr())) + : _getContent(_visibleChats), + ), + // The body sits behind the translucent app bar; the chips do not + // scroll, so they start below it. + Positioned( + top: MediaQuery.viewPaddingOf(context).top + kToolbarHeight, + left: 0, + right: 0, + child: Container(key: _filterKey, child: _filterChips()), ), ], ), // Admin panel - DefaultTabController( - initialIndex: 0, - length: 2, - child: Scaffold( - appBar: AppBar( - title: Text('adminPage'.tr()), - bottom: TabBar( - tabs: [ - Tab( - child: Text( - 'serverUsersPage'.tr(), - style: TextStyle(fontSize: 18), - ), - ), - Tab( - child: Text( - 'serverInvitesPage'.tr(), - style: TextStyle(fontSize: 18), - ), - ), - ], - ), - ), - body: TabBarView( - children: [ - // Server users - Column( - children: [ - Visibility( - visible: _serverUsers.isNotEmpty, - child: Align( - alignment: Alignment.topRight, - child: Padding( - padding: EdgeInsets.all(5), - child: ElevatedButton( - onPressed: _selectedUsers.isEmpty - ? null - : () async { - await DialogUtils.yesNoDialog( - context, - 'deleteUserConfirm'.tr(), - 'deleteUserConfirmText'.tr(), - _deleteSelectedUsers); - }, - child: Text('deleteUser'.tr()), - ), - ), - ), - ), - Expanded( - child: RefreshIndicator( - onRefresh: _getServerUsers, - child: ListView.builder( - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics(), - ), - itemCount: _serverUsers.length, - itemBuilder: (context, index) { - return Padding( - padding: const EdgeInsets.only(bottom: 10), - child: SelectUserListItem(_serverUsers[index], - (isSelected) { - // Add/remove selected users from list - setState(() { - if (isSelected) { - isSelected = isSelected; - _selectedUsers.add(_serverUsers[index].id); - } else { - _selectedUsers - .remove(_serverUsers[index].id); - } - }); - }), - ); - }, - ), - ), - ) - ], - ), - // Invites - RefreshIndicator( - onRefresh: _getServerInvites, - child: ListView.builder( - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics(), - ), - itemCount: _serverInvites.length, - itemBuilder: (context, index) { - return InviteListItem(_serverInvites[index]); - }, - ), - ) + Scaffold( + appBar: AppBar( + title: Text('adminPage'.tr()), + bottom: TabBar( + controller: _adminTabController, + tabs: [ + Tab(child: Text('serverUsersPage'.tr())), + Tab(child: Text('serverInvitesPage'.tr())), ], ), ), + body: TabBarView( + controller: _adminTabController, + children: [ + _usersTab(), + _invitesTab(), + ], + ), ) ][_currentPageIndex], // Pick widget by current index ); } + + /// Rounded surface the admin rows sit in. + Widget _adminCard(List children) { + final colors = Theme.of(context).colorScheme; + return ClipRRect( + borderRadius: BorderRadius.circular(16), + child: Material( + color: colors.surfaceContainerHigh, + child: Column( + children: [ + for (var i = 0; i < children.length; i++) ...[ + if (i > 0) + Divider( + height: 1, + indent: 16, + endIndent: 16, + color: colors.outlineVariant, + ), + children[i], + ], + ], + ), + ), + ); + } + + /// Centred icon + message used for the empty admin lists. + Widget _adminEmpty(IconData icon, String message) { + final colors = Theme.of(context).colorScheme; + return SizedBox( + height: 220, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 40, color: colors.secondary), + const SizedBox(height: 12), + Text(message, style: TextStyle(color: colors.secondary)), + ], + ), + ); + } + + /// Centred error message with a retry button, replacing the blank tab of the old UI. + Widget _adminError(VoidCallback retry) { + final colors = Theme.of(context).colorScheme; + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.error_outline, size: 40, color: colors.error), + const SizedBox(height: 12), + Text( + 'loadError'.tr(), + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 16), + FilledButton.tonal(onPressed: retry, child: Text('retry'.tr())), + ], + ), + ); + } + + Widget _adminSpinner() { + return Center( + child: Transform.scale( + scale: 1.5, + child: const CircularProgressIndicator(), + ), + ); + } + + Widget _usersTab() { + if (_usersLoading && _serverUsers.isEmpty) { + return _adminSpinner(); + } + if (_usersError && _serverUsers.isEmpty) { + return _adminError(_getServerUsers); + } + return RefreshIndicator( + onRefresh: _getServerUsers, + child: ListView( + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics(), + ), + padding: const EdgeInsets.fromLTRB(10, 10, 10, 24), + children: [ + if (_serverUsers.isEmpty) + _adminEmpty(Icons.people_outline, 'noUsers'.tr()) + else + _adminCard([ + for (final user in _serverUsers) + AdminUserListItem( + user, + onDelete: () async { + await DialogUtils.yesNoDialog( + context, + 'deleteUserConfirm'.tr(), + sprintf( + 'deleteUserConfirmTextName'.tr(), [user.username]), + () => _deleteUser(user), + ); + }, + ), + ]), + ], + ), + ); + } + + Widget _invitesTab() { + if (_invitesLoading && _serverInvites.isEmpty) { + return _adminSpinner(); + } + if (_invitesError && _serverInvites.isEmpty) { + return _adminError(_getServerInvites); + } + return Stack( + children: [ + RefreshIndicator( + onRefresh: _getServerInvites, + child: ListView( + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics(), + ), + padding: const EdgeInsets.fromLTRB(10, 10, 10, 96), + children: [ + if (_serverInvites.isEmpty) + _adminEmpty(Icons.mail_outline, 'noInvites'.tr()) + else + _adminCard([ + for (final invite in _serverInvites) InviteListItem(invite), + ]), + ], + ), + ), + Positioned( + right: 16, + bottom: 16, + child: FloatingActionButton( + onPressed: () => _createNewInvite(context), + shape: const CircleBorder(), + foregroundColor: Theme.of(context).colorScheme.surface, + backgroundColor: Theme.of(context).colorScheme.primary, + tooltip: 'newInvite'.tr(), + child: const Icon(Icons.person_add), + ), + ), + ], + ); + } } diff --git a/lib/pages/image_editor_page.dart b/lib/pages/image_editor_page.dart new file mode 100644 index 0000000..9489745 --- /dev/null +++ b/lib/pages/image_editor_page.dart @@ -0,0 +1,383 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:crop_your_image/crop_your_image.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +enum _EditMode { preview, crop, draw } + +/// Crop, rotate and draw on a photo before it leaves the device. +/// +/// Returns the edited bytes from [open], or null when the user backs out. The +/// strokes and the rotation are composited into a PNG at the original +/// resolution, so nothing is lost to the preview size. +class ImageEditorPage extends StatefulWidget { + const ImageEditorPage(this.bytes, {super.key}); + + final Uint8List bytes; + + /// Opens the editor and returns the edited bytes, or null. + static Future open(BuildContext context, Uint8List bytes) { + return Navigator.push( + context, MaterialPageRoute(builder: (_) => ImageEditorPage(bytes))); + } + + @override + State createState() => _ImageEditorPageState(); +} + +class _ImageEditorPageState extends State { + /// Colours a stroke can be drawn in: enough to stand out on a photo, few + /// enough to pick without a dialog. + static const List _palette = [ + Color(0xFFFF3B30), + Color(0xFFFFCC00), + Color(0xFF34C759), + Color(0xFF007AFF), + Color(0xFFAF52DE), + Color(0xFFFFFFFF), + Color(0xFF000000), + ]; + + Color _ink = _palette.first; + + final CropController _cropController = CropController(); + late Uint8List _bytes = widget.bytes; + _EditMode _mode = _EditMode.preview; + final List> _strokes = []; + bool _busy = false; + + /// Width / height of [_bytes]. The drawing surface is locked to it, so a + /// stroke lands under the finger instead of somewhere offset from it. + double _aspect = 1; + + @override + void initState() { + super.initState(); + _measure(_bytes); + } + + Future _measure(Uint8List bytes) async { + final codec = await ui.instantiateImageCodec(bytes); + final frame = await codec.getNextFrame(); + final aspect = frame.image.width / frame.image.height; + frame.image.dispose(); + codec.dispose(); + if (mounted) { + setState(() => _aspect = aspect); + } + } + + /// Width of a stroke relative to the picture, so the line looks the same at + /// any screen size and at the exported resolution. + static const double _strokeFraction = 1 / 60; + + Future _rotate() async { + setState(() => _busy = true); + try { + final rendered = await _render(_bytes, _strokes, quarterTurns: 1); + _strokes.clear(); + setState(() => _bytes = rendered); + await _measure(rendered); + } finally { + if (mounted) { + setState(() => _busy = false); + } + } + } + + Future _done() async { + setState(() => _busy = true); + try { + final rendered = await _render(_bytes, _strokes); + if (mounted) { + Navigator.pop(context, rendered); + } + } finally { + if (mounted) { + setState(() => _busy = false); + } + } + } + + void _undo() { + if (_strokes.isEmpty) { + return; + } + setState(() => _strokes.removeLast()); + } + + /// Draws [strokes] over the decoded [base] and rotates by [quarterTurns] 90° + /// steps, all at the image's own resolution. + Future _render(Uint8List base, List> strokes, + {int quarterTurns = 0}) async { + final codec = await ui.instantiateImageCodec(base); + final frame = await codec.getNextFrame(); + final image = frame.image; + final width = image.width; + final height = image.height; + final swap = quarterTurns.isOdd; + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + if (swap) { + canvas.translate(height.toDouble(), 0); + canvas.rotate(1.5707963267948966); + } + canvas.drawImage(image, Offset.zero, Paint()); + final paint = Paint() + ..color = _ink + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = width * _strokeFraction; + for (final stroke in strokes) { + if (stroke.length == 1) { + final point = stroke.first; + canvas.drawPoints(ui.PointMode.points, + [Offset(point.dx * width, point.dy * height)], paint); + continue; + } + final path = Path(); + for (var i = 0; i < stroke.length; i++) { + final point = Offset(stroke[i].dx * width, stroke[i].dy * height); + i == 0 + ? path.moveTo(point.dx, point.dy) + : path.lineTo(point.dx, point.dy); + } + canvas.drawPath(path, paint); + } + final picture = recorder.endRecording(); + final output = + await picture.toImage(swap ? height : width, swap ? width : height); + final data = await output.toByteData(format: ui.ImageByteFormat.png); + picture.dispose(); + output.dispose(); + image.dispose(); + return data!.buffer.asUint8List(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('editImage'.tr()), + actions: [ + IconButton( + tooltip: 'rotate'.tr(), + onPressed: _busy || _mode == _EditMode.crop ? null : _rotate, + icon: const Icon(Icons.rotate_90_degrees_ccw), + ), + IconButton( + tooltip: 'crop'.tr(), + onPressed: _busy + ? null + : () => setState(() { + _mode = _mode == _EditMode.crop + ? _EditMode.preview + : _EditMode.crop; + }), + icon: Icon(_mode == _EditMode.crop ? Icons.check : Icons.crop), + ), + IconButton( + tooltip: 'draw'.tr(), + onPressed: _busy + ? null + : () => setState(() { + _mode = _mode == _EditMode.draw + ? _EditMode.preview + : _EditMode.draw; + }), + icon: const Icon(Icons.edit), + ), + if (_mode == _EditMode.draw) + IconButton( + tooltip: 'undo'.tr(), + onPressed: _strokes.isEmpty ? null : _undo, + icon: const Icon(Icons.undo), + ), + IconButton( + tooltip: 'save'.tr(), + onPressed: _busy ? null : _done, + icon: const Icon(Icons.check_circle), + ), + ], + ), + body: _busy + ? const Center(child: CircularProgressIndicator()) + : _mode == _EditMode.crop + ? _cropView() + : Column( + children: [ + Expanded(child: _drawView()), + if (_mode == _EditMode.draw) _paletteBar(), + ], + ), + ); + } + + Widget _cropView() { + return Column( + children: [ + Expanded( + child: Crop( + image: _bytes, + controller: _cropController, + onCropped: (result) { + switch (result) { + case CropSuccess(:final croppedImage): + setState(() { + _bytes = croppedImage; + _strokes.clear(); + _mode = _EditMode.preview; + }); + _measure(croppedImage); + case CropFailure(): + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text('mediaError'.tr()))); + } + }, + ), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.all(12), + child: SizedBox( + width: double.infinity, + child: FilledButton( + onPressed: () => _cropController.crop(), + child: Text('applyCrop'.tr()), + ), + ), + ), + ), + ], + ); + } + + Widget _drawView() { + return Center( + child: AspectRatio( + aspectRatio: _aspect, + child: LayoutBuilder( + builder: (context, constraints) { + final drawing = _mode == _EditMode.draw; + return GestureDetector( + onPanStart: drawing + ? (details) => setState(() { + _strokes.add( + [_normalize(details.localPosition, constraints)]); + }) + : null, + onPanUpdate: drawing + ? (details) => setState(() { + _strokes.last.add( + _normalize(details.localPosition, constraints)); + }) + : null, + child: Stack( + fit: StackFit.expand, + children: [ + Image.memory(_bytes, fit: BoxFit.contain), + CustomPaint( + painter: _StrokePainter(_strokes, _ink), + ), + ], + ), + ); + }, + ), + ), + ); + } + + /// Colour choices for drawing. Shown only while drawing, so the picture keeps + /// the whole screen otherwise. + Widget _paletteBar() { + final outline = Theme.of(context).colorScheme.onSurface; + return SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + for (final color in _palette) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: GestureDetector( + onTap: () => setState(() => _ink = color), + child: Container( + width: 28, + height: 28, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: color == _ink ? outline : Colors.transparent, + width: 2, + ), + ), + ), + ), + ), + ], + ), + ), + ); + } + + /// Strokes are kept relative to the picture, so the export does not depend on + /// the size it was drawn at. + Offset _normalize(Offset local, BoxConstraints constraints) { + return Offset( + (local.dx / constraints.maxWidth).clamp(0.0, 1.0), + (local.dy / constraints.maxHeight).clamp(0.0, 1.0), + ); + } +} + +class _StrokePainter extends CustomPainter { + _StrokePainter(this.strokes, this.color); + + final List> strokes; + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = size.width * _ImageEditorPageState._strokeFraction; + for (final stroke in strokes) { + if (stroke.length == 1) { + canvas.drawPoints( + ui.PointMode.points, + [ + Offset( + stroke.first.dx * size.width, stroke.first.dy * size.height) + ], + paint); + continue; + } + final path = Path(); + for (var i = 0; i < stroke.length; i++) { + final point = + Offset(stroke[i].dx * size.width, stroke[i].dy * size.height); + i == 0 + ? path.moveTo(point.dx, point.dy) + : path.lineTo(point.dx, point.dy); + } + canvas.drawPath(path, paint); + } + } + + @override + bool shouldRepaint(covariant _StrokePainter oldDelegate) => + oldDelegate.color != color || + oldDelegate.strokes.length != strokes.length || + (strokes.isNotEmpty && + oldDelegate.strokes.last.length != strokes.last.length); +} diff --git a/lib/pages/live_location_page.dart b/lib/pages/live_location_page.dart new file mode 100644 index 0000000..fd773dc --- /dev/null +++ b/lib/pages/live_location_page.dart @@ -0,0 +1,132 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +import '../models/user.dart'; +import '../utils/live_location.dart'; +import '../utils/message_actions.dart'; +import '../utils/presence.dart'; +import '../utils/text_envelope.dart'; + +/// The live view of one shared location: the last position, its accuracy and the +/// time left, updated in place. No tiles are fetched, so the coordinates stay on +/// the device until the map button is tapped. +class LiveLocationPage extends StatefulWidget { + const LiveLocationPage(this.peer, {super.key}); + + final User peer; + + @override + State createState() => _LiveLocationPageState(); +} + +class _LiveLocationPageState extends State { + Timer? _tick; + + @override + void initState() { + super.initState(); + _tick = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) { + setState(() {}); + } + }); + PresenceNotifier.instance.addListener(_onChanged); + } + + @override + void dispose() { + _tick?.cancel(); + PresenceNotifier.instance.removeListener(_onChanged); + super.dispose(); + } + + void _onChanged() { + if (mounted) { + setState(() {}); + } + } + + String _left(DateTime until) { + final left = until.difference(DateTime.now()); + if (left.isNegative) { + return '0:00'; + } + return '${left.inMinutes}:' + '${left.inSeconds.remainder(60).toString().padLeft(2, '0')}'; + } + + @override + Widget build(BuildContext context) { + final mine = LiveLocationSharer.instance.isSharing(widget.peer.id); + final theirs = PresenceNotifier.instance.liveLocation(widget.peer.id); + final point = theirs; + final until = mine ? LiveLocationSharer.instance.until : point?.until; + final scheme = Theme.of(context).colorScheme; + final active = mine || point != null; + final lat = point?.lat; + final lng = point?.lng; + + return Scaffold( + appBar: AppBar(title: Text(widget.peer.username)), + body: SafeArea( + child: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.my_location, size: 72, color: scheme.primary), + const SizedBox(height: 16), + Text( + mine ? 'liveLocationMine'.tr() : 'liveLocationTheirs'.tr(), + style: Theme.of(context).textTheme.titleMedium, + ), + if (until != null) ...[ + const SizedBox(height: 4), + Text(_left(until), + style: Theme.of(context).textTheme.headlineSmall), + ], + if (point != null) ...[ + const SizedBox(height: 12), + Text(point.coordinates, + style: Theme.of(context).textTheme.bodyLarge), + if (point.accuracy != null) + Text('± ${point.accuracy!.round()} m', + style: TextStyle(color: scheme.onSurfaceVariant)), + ], + if (!active) ...[ + const SizedBox(height: 12), + Text('liveLocationEnded'.tr(), + style: TextStyle(color: scheme.onSurfaceVariant)), + ], + const SizedBox(height: 24), + if (lat != null && lng != null) + FilledButton.icon( + onPressed: () => MessageActions.openLocation( + LocationRef(lat, lng, accuracy: point?.accuracy)), + icon: const Icon(Icons.map), + label: Text('openInMaps'.tr()), + ), + if (mine) ...[ + const SizedBox(height: 8), + TextButton.icon( + onPressed: () async { + await LiveLocationSharer.instance.stop(); + if (mounted) { + setState(() {}); + } + }, + icon: const Icon(Icons.stop_circle_outlined), + label: Text('liveLocationStop'.tr()), + ), + ], + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart new file mode 100644 index 0000000..280247e --- /dev/null +++ b/lib/pages/media_viewer_page.dart @@ -0,0 +1,398 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:chewie/chewie.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +import '../models/private_message.dart'; +import '../utils/cache_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/message_actions.dart'; +import '../utils/message_notifier.dart'; +import '../utils/playback_lock.dart'; +import '../utils/screen_guard.dart'; + +/// Fullscreen viewer for the media of one conversation, stored +/// encrypted-at-rest. Swiping moves between the attachments. +class MediaViewerPage extends StatefulWidget { + final PrivateMessage message; + + /// The other side of the conversation: the source of the other attachments + /// and what the delete action needs. + final String conversationUserId; + + /// Index of the tapped attachment when [message] is an album. + final int albumIndex; + + /// A view-once attachment: one page, screenshot-blocked, burnt on close. + final bool viewOnce; + + const MediaViewerPage({ + required this.message, + required this.conversationUserId, + this.albumIndex = 0, + this.viewOnce = false, + super.key, + }); + + @override + State createState() => _MediaViewerPageState(); +} + +class _MediaViewerPageState extends State { + List _media = []; + PageController? _controller; + int _index = 0; + + PrivateMessage get _current => _media[_index]; + + @override + void initState() { + super.initState(); + if (widget.viewOnce) { + // The one allowed view may not be screenshotted or recorded. Android + // enforces it with FLAG_SECURE; iOS has no block, only a best-effort + // notification, which is why the app says so on the info screen. + ScreenGuard.enableSecure(); + } + _loadMedia(); + } + + /// The viewer pages through the same attachments the gallery shows, starting + /// at the one that was tapped. + Future _loadMedia() async { + if (widget.viewOnce) { + // One attachment, one reveal: an album is one reveal of all its pages, + // and swiping past them is still that single open. + final pages = widget.message.isAlbum + ? MessageNotifier.albumMedia(widget.message) + : [widget.message]; + setState(() { + _media = pages; + _index = 0; + _controller = PageController(initialPage: 0); + }); + return; + } + if (widget.message.isAlbum) { + // Album attachments are pages of their own; keep the album order so the + // tapped tile maps to the same index. + final media = MessageNotifier.albumMedia(widget.message); + if (!mounted) { + return; + } + setState(() { + _media = media.isEmpty ? [widget.message] : media; + _index = widget.albumIndex.clamp(0, _media.length - 1); + _controller = PageController(initialPage: _index); + }); + return; + } + final messages = + await CacheUtils.getPrivateMessages(widget.conversationUserId); + final media = MessageNotifier.viewableMedia(messages); + var index = -1; + if (widget.message.mediaId != null) { + index = media.indexWhere((m) => m.mediaId == widget.message.mediaId); + } + if (index < 0) { + index = media.indexWhere((m) => + m.senderId == widget.message.senderId && + m.sentAt == widget.message.sentAt); + } + if (!mounted) { + return; + } + setState(() { + // Never fall back to the first page when the tapped attachment is not in + // the list: that opens a different attachment than the one clicked. + _media = index < 0 ? [widget.message] : media; + _index = index < 0 ? 0 : index; + _controller = PageController(initialPage: _index); + }); + } + + @override + void dispose() { + if (widget.viewOnce) { + ScreenGuard.disableSecure(); + } + _controller?.dispose(); + super.dispose(); + } + + /// Overflow menu of the viewer: the same actions as the bubble sheet, except + /// copy (the caption is already visible). + PopupMenuButton _buildActions() { + return PopupMenuButton( + icon: const Icon(Icons.more_vert), + onSelected: (value) { + switch (value) { + case 'save': + MessageActions.save(_current); + break; + case 'forward': + MessageActions.forward(context, [_current]); + break; + case 'delete': + MessageActions.delete(context, _current, widget.conversationUserId, + onDeleted: () => Navigator.pop(context)); + break; + } + }, + itemBuilder: (context) => [ + if (MessageActions.canSave(_current)) + _menuItem('save', MessageActions.saveIcon, 'saveAttachment'.tr()), + _menuItem('forward', MessageActions.forwardIcon, 'forwardMessage'.tr()), + _menuItem( + 'delete', MessageActions.deleteIcon, 'deleteMessageForMe'.tr()), + ], + ); + } + + /// Menu row with the same icon the bubble sheet uses for this action. + PopupMenuItem _menuItem(String value, IconData icon, String label) { + return PopupMenuItem( + value: value, + child: Row( + children: [ + Icon(icon), + const SizedBox(width: 12), + Text(label), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + final caption = controller == null ? '' : _current.message; + final colors = Theme.of(context).colorScheme; + return Scaffold( + backgroundColor: colors.surface, + appBar: AppBar( + actions: controller == null ? null : [_buildActions()], + ), + body: controller == null + ? const Center(child: CircularProgressIndicator()) + : PageView.builder( + controller: controller, + itemCount: _media.length, + onPageChanged: (index) => setState(() { + _index = index; + }), + itemBuilder: (context, index) => Center( + child: _MediaPage(_media[index], current: index == _index), + ), + ), + bottomNavigationBar: caption.isNotEmpty + ? Container( + color: colors.surface, + padding: const EdgeInsets.all(16), + child: SafeArea( + top: false, + child: Text( + caption, + style: TextStyle(color: colors.onSurface), + ), + ), + ) + : null, + ); + } +} + +/// One attachment of the viewer: decodes its own file and releases it again +/// when the page is swiped away. +class _MediaPage extends StatefulWidget { + const _MediaPage(this.message, {required this.current}); + final PrivateMessage message; + + /// Whether this page is the one on screen; a swiped-away page pauses. + final bool current; + + @override + State<_MediaPage> createState() => _MediaPageState(); +} + +class _MediaPageState extends State<_MediaPage> with WidgetsBindingObserver { + Uint8List? _imageBytes; + VideoPlayerController? _videoController; + ChewieController? _chewieController; + File? _tempFile; + bool _loading = true; + bool _error = false; + bool _lockHeld = false; + + MediaType get _type => widget.message.mediaType ?? MediaType.image; + + bool get _isVideo => _type == MediaType.video; + + bool get _isFile => _type == MediaType.file; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + PlaybackLock.owner.addListener(_onLockChanged); + _load(); + } + + /// A video claims the lock while it plays and gives it back when it stops, + /// so a voice message can never be heard underneath it. + void _onVideoStateChanged() { + final playing = _videoController?.value.isPlaying ?? false; + if (playing) { + _lockHeld = true; + PlaybackLock.claim(this); + } else if (_lockHeld) { + _lockHeld = false; + PlaybackLock.release(this); + } + } + + /// Pauses when a voice message starts playing. + void _onLockChanged() { + if (!identical(PlaybackLock.owner.value, this)) { + _videoController?.pause(); + } + } + + @override + void didUpdateWidget(covariant _MediaPage oldWidget) { + super.didUpdateWidget(oldWidget); + if (!widget.current) { + _videoController?.pause(); + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) { + _videoController?.pause(); + } + } + + Future _load() async { + try { + final localPath = widget.message.localPath; + if (localPath == null) { + throw Exception('no local media'); + } + if (_isFile) { + // A file shows its icon and metadata, never its content. + } else if (_isVideo) { + _tempFile = await MediaUtils.materializeTempFile( + localPath, MediaUtils.extensionForType(_type)); + final controller = VideoPlayerController.file(_tempFile!); + await controller.initialize(); + controller.addListener(_onVideoStateChanged); + _videoController = controller; + _chewieController = ChewieController( + videoPlayerController: controller, + autoPlay: true, + looping: false, + allowFullScreen: true, + ); + } else { + _imageBytes = await MediaUtils.decryptAtRest(localPath); + } + if (mounted) { + setState(() { + _loading = false; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _loading = false; + _error = true; + }); + } + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + PlaybackLock.owner.removeListener(_onLockChanged); + PlaybackLock.release(this); + _videoController?.removeListener(_onVideoStateChanged); + _chewieController?.dispose(); + _videoController?.dispose(); + MediaUtils.deleteLocalFile(_tempFile?.path); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const CircularProgressIndicator(); + } + if (_error) { + return Text('mediaError'.tr(), + style: TextStyle(color: Theme.of(context).colorScheme.onSurface)); + } + if (_isFile) { + return _filePage(); + } + if (_isVideo && _chewieController != null) { + return AspectRatio( + aspectRatio: _videoController!.value.aspectRatio, + child: Chewie(controller: _chewieController!), + ); + } + if (_imageBytes != null) { + return InteractiveViewer( + minScale: 0.5, + maxScale: 4, + child: SizedBox.expand( + child: Image.memory(_imageBytes!, fit: BoxFit.contain), + ), + ); + } + return Text('mediaError'.tr(), + style: TextStyle(color: Theme.of(context).colorScheme.onSurface)); + } + + /// File page: icon, name, size and a save button. + Widget _filePage() { + final message = widget.message; + final name = message.fileName ?? 'mediaFile'.tr(); + final colors = Theme.of(context).colorScheme; + return Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(MediaUtils.iconForFileName(message.fileName), + color: colors.onSurface, size: 64), + const SizedBox(height: 12), + Text( + name, + textAlign: TextAlign.center, + style: TextStyle(color: colors.onSurface, fontSize: 16), + ), + if (message.mediaSize != null) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + MediaUtils.formatBytes(message.mediaSize!), + style: TextStyle(color: colors.onSurfaceVariant, fontSize: 12), + ), + ), + const SizedBox(height: 16), + FilledButton.icon( + onPressed: () => MessageActions.save(message), + icon: const Icon(Icons.download), + label: Text('saveAttachment'.tr()), + ), + ], + ), + ); + } +} diff --git a/lib/pages/password_page.dart b/lib/pages/password_page.dart index 1724911..6ef6a85 100644 --- a/lib/pages/password_page.dart +++ b/lib/pages/password_page.dart @@ -1,14 +1,14 @@ import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; -import 'package:whisper_websocket_client_dart/ws_client.dart'; +import 'package:shept_websocket_client_dart/ws_client.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; import '../utils/crypto_utils.dart'; import '../utils/singleton.dart'; import '../utils/utils.dart'; import 'home_page.dart'; +import '../utils/nav_transitions.dart'; class PasswordPage extends StatefulWidget { const PasswordPage({super.key}); @@ -49,7 +49,6 @@ class _PasswordPageState extends State { if (key != null) { setState(() { _isButtonDisabled = true; - _controllerLocalPassword.text = 'yourAmazingPasswordIsHereOhYesItIs'; }); // Set the decryption key @@ -59,7 +58,7 @@ class _PasswordPageState extends State { // Load profile Singleton().profile = await CacheUtils.getProfile(); // OpenAPI client - Singleton().api = ApiClient(basePath: Singleton().profile.url); + Singleton().api = Singleton.createApiClient(Singleton().profile.url); // Check tokens await Utils.authCheck(); // WebSocket client @@ -69,8 +68,7 @@ class _PasswordPageState extends State { // Redirect to home page if (mounted) { - Navigator.pushReplacement(context, - MaterialPageRoute(builder: (context) => const HomePage())); + Navigator.pushReplacement(context, fadeRoute(const HomePage())); } } catch (e) { setState(() { @@ -113,14 +111,42 @@ class _PasswordPageState extends State { if (password) { await Fluttertoast.showToast( msg: 'passwordPlsWait'.tr(), backgroundColor: Colors.grey); + // Installs created before random salts re-encrypt their data once here. + bool migrated = false; + try { + migrated = + await CacheUtils.migrateSalt(_controllerLocalPassword.text); + } catch (e) { + debugPrint('salt migration failed: $e'); + } + if (migrated && await CacheUtils.isBiometryEnabled()) { + // The stored biometric key was derived with the old salt, so it can + // no longer open the re-encrypted boxes. + await BiometricAuth.clearEncryptionKey(); + await CacheUtils.setBiometryEnabled(false); + await Fluttertoast.showToast( + msg: 'biometricsDisabledAfterMigration'.tr(), + backgroundColor: Colors.orange); + } + final List? salt = await CacheUtils.getSalt(); + if (salt == null && !migrated) { + await Fluttertoast.showToast( + msg: 'passwordMigrationFailed'.tr(), backgroundColor: Colors.red); + setState(() { + _isButtonDisabled = false; + }); + return; + } // Derive key from password - List key = await CryptoUtils.pbkdf2(_controllerLocalPassword.text); + List key = migrated + ? List.from(Singleton().boxCollectionKey) + : await CryptoUtils.pbkdf2(_controllerLocalPassword.text, salt!); // Add key to singleton Singleton().boxCollectionKey = key; // Add profile to singleton Singleton().profile = await CacheUtils.getProfile(); // OpenAPI client - Singleton().api = ApiClient(basePath: Singleton().profile.url); + Singleton().api = Singleton.createApiClient(Singleton().profile.url); // Kontrola tokenů await Utils.authCheck(); @@ -130,8 +156,7 @@ class _PasswordPageState extends State { await Utils.wsConnect(firstConnect: true); if (mounted) { - Navigator.pushReplacement(context, - MaterialPageRoute(builder: (context) => const HomePage())); + Navigator.pushReplacement(context, fadeRoute(const HomePage())); } } else { await Fluttertoast.showToast( @@ -221,7 +246,8 @@ class _PasswordPageState extends State { padding: const EdgeInsets.only(top: 20), child: IconButton( icon: const Icon(Icons.fingerprint, size: 40), - onPressed: _isButtonDisabled ? null : _authenticateWithBiometric, + onPressed: + _isButtonDisabled ? null : _authenticateWithBiometric, ), ), ), diff --git a/lib/pages/register_page.dart b/lib/pages/register_page.dart index dd12b52..c9e8677 100644 --- a/lib/pages/register_page.dart +++ b/lib/pages/register_page.dart @@ -2,11 +2,11 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_websocket_client_dart/ws_client.dart'; +import 'package:shept_websocket_client_dart/ws_client.dart'; import '../models/invite_data.dart'; import '../models/profile.dart'; import '../models/user.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; import '../utils/crypto_utils.dart'; @@ -15,6 +15,7 @@ import '../utils/singleton.dart'; import '../utils/utils.dart'; import 'package:basic_utils/basic_utils.dart' as bu; import 'home_page.dart'; +import '../utils/nav_transitions.dart'; class RegisterPage extends StatefulWidget { const RegisterPage(this.invite, {super.key}); @@ -107,7 +108,7 @@ class _RegisterPageState extends State { // Generate RSA keypair var keyPair = await CryptoUtils.getRSAKeyPair(); // OpenAPI client - Singleton().api = ApiClient(basePath: widget.invite.url); + Singleton().api = Singleton.createApiClient(widget.invite.url); // Registration var newUser = await Utils.callApi( () => Singleton().authApi.createUser( @@ -132,11 +133,14 @@ class _RegisterPageState extends State { true); // Add profile to singleton Singleton().profile = profile; + // A random salt must exist before anything is encrypted with the key + final List salt = CryptoUtils.generateSalt(); + await CacheUtils.setSalt(salt); // Save password hash to cache CacheUtils.setPasswordHash(_controllerLocalPassword.text); - // Generování klíče z hesla a uložení do singletonu + // Derive the key from the password and store it in the singleton List key = - await CryptoUtils.pbkdf2(_controllerLocalPassword.text); + await CryptoUtils.pbkdf2(_controllerLocalPassword.text, salt); Singleton().boxCollectionKey = key; // Save profile to cache @@ -164,20 +168,32 @@ class _RegisterPageState extends State { await Fluttertoast.showToast( msg: 'biometricsEnabled'.tr(), backgroundColor: Colors.grey); + + // Redirect to home page and clear navigation history + Navigator.of(context).pushAndRemoveUntil( + fadeRoute(const HomePage()), + (Route route) => false, + ); } else { await Fluttertoast.showToast( msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); + + // Redirect to home page and clear navigation history + Navigator.of(context).pushAndRemoveUntil( + fadeRoute(const HomePage()), + (Route route) => false, + ); } }, ); + } else { + // Redirect to home page and clear navigation history + Navigator.of(context).pushAndRemoveUntil( + fadeRoute(const HomePage()), + (Route route) => false, + ); } - - // Redirect to home page and clear navigation history - Navigator.of(context).pushAndRemoveUntil( - MaterialPageRoute(builder: (context) => const HomePage()), - (Route route) => false, - ); } } diff --git a/lib/pages/scan_invite_button_page.dart b/lib/pages/scan_invite_button_page.dart index caa9af7..719c2ad 100644 --- a/lib/pages/scan_invite_button_page.dart +++ b/lib/pages/scan_invite_button_page.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; import 'scan_invite_page.dart'; +import '../utils/nav_transitions.dart'; class ScanInviteButtonPage extends StatefulWidget { const ScanInviteButtonPage({super.key}); @@ -30,10 +31,7 @@ class _ScanInviteButtonPageState extends State { ), onPressed: () { // Navigate to scanning invite - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => const ScanInvitePage())); + Navigator.push(context, stepRoute(const ScanInvitePage())); }, child: Padding( padding: const EdgeInsets.all(7), diff --git a/lib/pages/scan_invite_page.dart b/lib/pages/scan_invite_page.dart index 35009e7..a0555f4 100644 --- a/lib/pages/scan_invite_page.dart +++ b/lib/pages/scan_invite_page.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; @@ -7,6 +8,8 @@ import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart'; import '../models/invite_data.dart'; import 'register_page.dart'; +import '../utils/nav_transitions.dart'; +import '../utils/utils.dart'; class ScanInvitePage extends StatefulWidget { const ScanInvitePage({super.key}); @@ -18,33 +21,79 @@ class ScanInvitePage extends StatefulWidget { class _ScanInvitePageState extends State { final GlobalKey _qrKey = GlobalKey(); QRViewController? _qrController; + StreamSubscription? _scanSubscription; + bool _isProcessingScan = false; + final Set _shownToastForScan = {}; /// On creation of QR view void _onQRViewCreated(QRViewController controller) { _qrController = controller; - controller.scannedDataStream.listen((scanData) { - // Try to decode invite - try { - Map inviteMap = - jsonDecode(scanData.code!) as Map; - InviteData invite = InviteData.fromJson(inviteMap); - // Check if invite expired - if (invite.validUntil.difference(DateTime.now()).isNegative) { + _scanSubscription?.cancel(); + _scanSubscription = controller.scannedDataStream.listen(_onScan); + } + + bool _showScanToastOnce(String scanCode, String toastKey) { + if (!_shownToastForScan.add('$toastKey:$scanCode')) { + return false; + } + return true; + } + + Future _onScan(Barcode scanData) async { + if (_isProcessingScan || !mounted) return; + final scanCode = scanData.code; + if (scanCode == null) return; + + try { + final inviteMap = jsonDecode(scanCode) as Map; + final invite = InviteData.fromJson(inviteMap); + // Release builds only talk to HTTPS: tokens and metadata would otherwise + // travel in clear text. + if (!Utils.isAllowedServerUrl(invite.url)) { + if (_showScanToastOnce(scanCode, 'insecureServerUrl')) { + Fluttertoast.showToast( + msg: 'insecureServerUrl'.tr(), + backgroundColor: Colors.red, + ); + } + return; + } + if (invite.validUntil.difference(DateTime.now()).isNegative) { + if (_showScanToastOnce(scanCode, 'inviteExpired')) { Fluttertoast.showToast( msg: 'inviteExpired'.tr(), - backgroundColor: Colors.red); - } else { - // Push registration page - Navigator.push(context, - MaterialPageRoute(builder: (context) => RegisterPage(invite))); - return; + backgroundColor: Colors.red, + ); } - } catch (e) { + return; + } + + _isProcessingScan = true; + await _qrController?.pauseCamera(); + if (!mounted) return; + + await Navigator.push(context, stepRoute(RegisterPage(invite))); + } catch (_) { + if (_showScanToastOnce(scanCode, 'invalidQr')) { Fluttertoast.showToast( - msg: 'invalidQr'.tr(), - backgroundColor: Colors.red); + msg: 'invalidQr'.tr(), + backgroundColor: Colors.red, + ); + } + } finally { + if (_isProcessingScan) { + _isProcessingScan = false; + if (mounted) { + await _qrController?.resumeCamera(); + } } - }); + } + } + + @override + void dispose() { + _scanSubscription?.cancel(); + super.dispose(); } @override diff --git a/lib/pages/search_page.dart b/lib/pages/search_page.dart new file mode 100644 index 0000000..7d749aa --- /dev/null +++ b/lib/pages/search_page.dart @@ -0,0 +1,197 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +import '../models/user.dart'; +import '../utils/cache_utils.dart'; +import '../utils/chat_date.dart'; +import '../utils/message_search.dart'; + +/// Searches one conversation's local history. Messages are stored decrypted, +/// so this is a local scan: nothing is sent anywhere. +/// +/// The page returns the timestamp of the picked message; the chat it belongs to +/// jumps there. +class MessageSearchPage extends StatefulWidget { + const MessageSearchPage(this.peer, {super.key}); + + final User peer; + + @override + State createState() => _MessageSearchPageState(); +} + +class _MessageSearchPageState extends State { + final TextEditingController _controller = TextEditingController(); + Timer? _debounce; + List _hits = []; + bool _loading = false; + bool _searched = false; + + @override + void dispose() { + _debounce?.cancel(); + _controller.dispose(); + super.dispose(); + } + + void _onTextChanged(String _) { + _debounce?.cancel(); + _debounce = Timer(const Duration(milliseconds: 250), _run); + } + + Future _run() async { + final query = MessageSearchQuery( + text: _controller.text, + conversationId: widget.peer.id, + ); + if (query.isEmpty) { + setState(() { + _hits = []; + _searched = false; + }); + return; + } + setState(() { + _loading = true; + }); + final hits = await CacheUtils.searchMessages(query); + if (!mounted) { + return; + } + setState(() { + _hits = hits; + _loading = false; + _searched = true; + }); + } + + /// A result line with the found text highlighted. + Widget _snippetText(String text) { + final scheme = Theme.of(context).colorScheme; + final needle = _controller.text; + return Text.rich( + TextSpan( + children: [ + for (final part in highlightParts(snippet(text, needle), needle)) + TextSpan( + text: part.text, + style: part.match + ? TextStyle( + fontWeight: FontWeight.bold, + color: scheme.onPrimaryContainer, + backgroundColor: + scheme.primaryContainer.withValues(alpha: 0.8), + ) + : null, + ), + ], + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ); + } + + Widget _resultTile(MessageHit hit) { + final message = hit.message; + return ListTile( + leading: CircleAvatar( + radius: 20, + backgroundColor: widget.peer.avatarColor, + child: Text( + widget.peer.username.isNotEmpty + ? widget.peer.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 16, + color: widget.peer.avatarTextColor, + ), + ), + ), + title: _snippetText(message.preview), + subtitle: Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + chatDateLabel( + message.sentAt, + todayLabel: 'todayText'.tr(), + yesterdayLabel: 'yesterdayText'.tr(), + ), + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + onTap: () => Navigator.pop(context, message.sentAt), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text('searchInChat'.tr())), + body: SafeArea( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 4), + child: TextField( + controller: _controller, + autofocus: true, + textInputAction: TextInputAction.search, + onChanged: _onTextChanged, + onSubmitted: (_) => _run(), + decoration: InputDecoration( + hintText: 'searchHint'.tr(), + prefixIcon: const Icon(Icons.search), + suffixIcon: _controller.text.isEmpty + ? null + : IconButton( + icon: const Icon(Icons.clear), + tooltip: 'cancel'.tr(), + onPressed: () { + _controller.clear(); + _run(); + }, + ), + filled: true, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(24), + borderSide: BorderSide.none, + ), + ), + ), + ), + if (_loading) const LinearProgressIndicator(), + Expanded(child: _body()), + ], + ), + ), + ); + } + + Widget _body() { + if (!_searched) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'searchEmptyHint'.tr(), + textAlign: TextAlign.center, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ), + ); + } + if (_hits.isEmpty) { + return Center(child: Text('noSearchResults'.tr())); + } + return ListView.builder( + itemCount: _hits.length, + itemBuilder: (context, index) => _resultTile(_hits[index]), + ); + } +} diff --git a/lib/pages/search_user_page.dart b/lib/pages/search_user_page.dart index 1184727..12a0578 100644 --- a/lib/pages/search_user_page.dart +++ b/lib/pages/search_user_page.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/user.dart'; @@ -5,55 +7,114 @@ import '../utils/singleton.dart'; import '../utils/utils.dart'; import '../widgets/user_list_item.dart'; import 'chat_page.dart'; +import '../utils/nav_transitions.dart'; + +typedef UserSearchCallback = Future?> Function(String query); class SearchUserPage extends StatefulWidget { - const SearchUserPage({super.key}); + const SearchUserPage({this.onUserSelected, this.search, super.key}); + + /// When set, a tapped user is passed here instead of opening the chat. + final void Function(User)? onUserSelected; + + /// Search implementation; defaults to the server API. + final UserSearchCallback? search; @override State createState() => _SearchUserPageState(); } class _SearchUserPageState extends State { + static const _debounceDuration = Duration(milliseconds: 250); + final _controllerSearch = TextEditingController(); List _users = []; bool _loading = false; + bool _error = false; + bool _searched = false; + Timer? _debounce; - /// Search users - Future _searchUsers() async { - // Empty search - if (_controllerSearch.text.isEmpty) { - return; + /// Invalidates in-flight requests as soon as the query changes. + int _generation = 0; + + Future?> _performSearch(String query) async { + final search = widget.search; + if (search != null) { + return search(query); } + final users = + await Utils.callApi(() => Singleton().userApi.searchUsers(query)); + return users?.map(User.fromModel).toList(); + } + + void _onQueryChanged(String value) { + _debounce?.cancel(); + final query = value.trim(); + final generation = ++_generation; - if (context.mounted) { + if (query.isEmpty) { setState(() { - _loading = true; _users = []; + _loading = false; + _error = false; + _searched = false; }); + return; } - // Get users from server - var users = await Utils.callApi( - () => Singleton().userApi.searchUsers(_controllerSearch.text)); - if (context.mounted) { - setState(() { - if (users != null) { - for (var x in users) { - _users.add(User.fromModel(x)); - } - } - }); + setState(() { + _error = false; + }); + _debounce = Timer(_debounceDuration, () => _search(query, generation)); + } + + Future _search(String query, int generation) async { + if (!mounted || generation != _generation) { + return; } + setState(() { + _loading = true; + _error = false; + }); - if (context.mounted) { - setState(() { - _loading = false; - }); + final users = await _performSearch(query); + if (!mounted || generation != _generation) { + return; } + setState(() { + _loading = false; + _searched = true; + if (users == null) { + _error = true; + } else { + _users = users; + _error = false; + } + }); + } + + void _submitQuery(String value) { + _debounce?.cancel(); + final query = value.trim(); + if (query.isEmpty) { + return; + } + final generation = ++_generation; + _search(query, generation); + } + + void _retry() { + _submitQuery(_controllerSearch.text); + } + + void _clearQuery() { + _controllerSearch.clear(); + _onQueryChanged(''); } @override void dispose() { + _debounce?.cancel(); _controllerSearch.dispose(); super.dispose(); } @@ -64,7 +125,6 @@ class _SearchUserPageState extends State { appBar: AppBar( title: Text('searchUserPage'.tr()), ), - resizeToAvoidBottomInset: false, body: SafeArea( child: Padding( padding: const EdgeInsets.all(16.0), @@ -75,6 +135,9 @@ class _SearchUserPageState extends State { padding: const EdgeInsets.only(bottom: 15), child: TextField( controller: _controllerSearch, + onChanged: _onQueryChanged, + onSubmitted: _submitQuery, + textInputAction: TextInputAction.search, decoration: InputDecoration( hintText: 'enterUsername'.tr(), filled: true, @@ -85,46 +148,71 @@ class _SearchUserPageState extends State { borderRadius: BorderRadius.circular(30), borderSide: BorderSide.none, ), - suffixIcon: IconButton( - onPressed: _loading ? null : _searchUsers, - icon: const Icon(Icons.search), - ), + suffixIcon: _loading + ? const Padding( + padding: EdgeInsets.all(14), + child: SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ) + : _controllerSearch.text.isNotEmpty + ? IconButton( + tooltip: 'clearSearch'.tr(), + onPressed: _clearQuery, + icon: const Icon(Icons.close), + ) + : null, ), ), ), - // Loading - Visibility( - visible: _loading, - child: const Padding( - padding: EdgeInsets.only(top: 20, left: 7, right: 7), - child: CircularProgressIndicator(), - ), - ), - // Users list - Visibility( - visible: !_loading, - child: Expanded( - child: ListView.builder( - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics(), - ), - itemCount: _users.length, - itemBuilder: (context, index) { - return Padding( - padding: const EdgeInsets.only(bottom: 10), - child: UserListItem(_users[index], () async { - Navigator.pushAndRemoveUntil( - context, - MaterialPageRoute( - builder: (context) => ChatPage(_users[index])), - (route) => route - .isFirst, // Returns true only for Home page - ); - }), - ); - }, + if (_error) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + const Icon(Icons.error_outline, size: 20), + const SizedBox(width: 8), + Expanded(child: Text('userSearchFailed'.tr())), + TextButton( + onPressed: _retry, + child: Text('retry'.tr()), + ), + ], ), ), + Expanded( + child: _users.isEmpty + ? Center( + child: !_loading && !_error && _searched + ? Text('noUsersFound'.tr()) + : const SizedBox.shrink(), + ) + : ListView.builder( + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics(), + ), + itemCount: _users.length, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: UserListItem(_users[index], () async { + final onUserSelected = widget.onUserSelected; + if (onUserSelected != null) { + onUserSelected(_users[index]); + return; + } + Navigator.pushAndRemoveUntil( + context, + slideUpRoute(ChatPage(_users[index])), + (route) => route + .isFirst, // Returns true only for Home page + ); + }), + ); + }, + ), ), ], ), diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index f0fbc9a..6adc6d8 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -6,6 +6,8 @@ import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:sprintf/sprintf.dart'; import 'package:url_launcher/url_launcher.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import '../utils/auto_download.dart'; import '../utils/biometric_auth.dart'; import '../utils/cache_utils.dart'; import '../utils/singleton.dart'; @@ -13,6 +15,11 @@ import '../utils/dialog_utils.dart'; import '../utils/message_notifier.dart'; import '../utils/utils.dart'; import 'scan_invite_button_page.dart'; +import '../widgets/change_password_dialog.dart'; +import '../widgets/settings_tile.dart'; +import '../utils/nav_transitions.dart'; +import 'devices_page.dart'; +import 'storage_page.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @@ -23,6 +30,14 @@ class SettingsPage extends StatefulWidget { class _SettingsPageState extends State { bool _isBiometryEnabled = false; + bool _notificationPreview = false; + bool _typingIndicator = false; + bool _presence = false; + AutoDownloadPolicy _autoDownload = AutoDownloadPolicy.wifi; + + /// Guards the retention flow: the settings round-trip is slow, and without it + /// a second tap stacks another dialog on top of the first. + bool _retentionBusy = false; @override void initState() { @@ -32,303 +47,397 @@ class _SettingsPageState extends State { Future _loadSettings() async { _isBiometryEnabled = await CacheUtils.isBiometryEnabled(); + _notificationPreview = await CacheUtils.getNotificationPreview(); + _typingIndicator = await CacheUtils.isTypingIndicatorEnabled(); + _presence = await CacheUtils.isPresenceEnabled(); + _autoDownload = await CacheUtils.getAutoDownloadPolicy(); setState(() {}); } - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: Text('settingsPage'.tr()), - ), - body: SafeArea( - child: Column( + /// Server-side retention of the ciphertext archive. The shorter setting of + /// the two participants wins, so this is a limit, not a promise. + Future _showRetentionDialog() async { + if (_retentionBusy) { + return; + } + _retentionBusy = true; + try { + // Blocks the page while the request is in flight, so a fast second tap + // cannot reach the tile and nothing else can be tapped meanwhile. + showDialog( + context: context, + barrierDismissible: false, + builder: (_) => const PopScope( + canPop: false, + child: Center(child: CircularProgressIndicator()), + ), + ); + final current = + await Utils.callApi(() => Singleton().userApi.getRetention()); + if (!mounted) { + return; + } + Navigator.of(context).pop(); + final selected = await showDialog( + context: context, + builder: (dialogContext) => SimpleDialog( + title: Text('retentionTitle'.tr()), children: [ - // Theme - TextButton( - onPressed: () { - showDialog(context: context, builder: DialogUtils.themeDialog); - }, - child: Row( - children: [ - Icon( - Icons.palette, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'themeSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - ], - ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Text('retentionExplain'.tr()), ), - // Notifications - TextButton( - onPressed: null, - child: Row( - children: [ - Icon( - Icons.notifications, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'notificationSettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), + for (final days in const [7, 30, 90, 365]) + SimpleDialogOption( + onPressed: () => Navigator.of(dialogContext).pop(days), + child: Row( + children: [ + Icon( + current?.days == days + ? Icons.radio_button_checked + : Icons.radio_button_unchecked, + size: 20, + color: Theme.of(dialogContext).colorScheme.secondary, ), - ), - Spacer(), - Switch( - value: Singleton().profile.enableNotifications, - onChanged: (value) async { - setState(() { - Singleton().profile.enableNotifications = - !Singleton().profile.enableNotifications; - }); - await Singleton().profile.save(); - }, - ) - ], + const SizedBox(width: 8), + Text('retentionDays'.tr(args: [days.toString()])), + ], + ), ), - ), - - Divider(thickness: 1, indent: 10, endIndent: 10), + ], + ), + ); + if (selected == null || !mounted) { + return; + } + await Utils.callApi(() => Singleton() + .userApi + .setRetention(setRetentionInput: SetRetentionInput(days: selected))); + if (!mounted) { + return; + } + await Fluttertoast.showToast( + msg: 'retentionSaved'.tr(), backgroundColor: Colors.grey); + } finally { + _retentionBusy = false; + } + } - // Biometric authentication - TextButton( - onPressed: null, + /// Language is stored by easy_localization in SharedPreferences. + Future _showLanguageDialog() async { + final selected = await showDialog( + context: context, + builder: (dialogContext) => SimpleDialog( + title: Text('languageSettings'.tr()), + children: [ + for (final locale in context.supportedLocales) + SimpleDialogOption( + onPressed: () => Navigator.of(dialogContext).pop(locale), child: Row( children: [ Icon( - Icons.fingerprint, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'biometrySettings'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), + context.locale.languageCode == locale.languageCode + ? Icons.radio_button_checked + : Icons.radio_button_unchecked, + size: 20, + color: Theme.of(dialogContext).colorScheme.secondary, ), - Spacer(), - Switch( - value: _isBiometryEnabled, - onChanged: (value) async { - if (value) { - // Enable - final success = await BiometricAuth.storeEncryptionKey( - Singleton().boxCollectionKey, context); - if (success) { - await Fluttertoast.showToast( - msg: 'biometricsEnabled'.tr(), - backgroundColor: Colors.grey); - setState(() { - _isBiometryEnabled = true; - }); - } else { - await Fluttertoast.showToast( - msg: 'biometricSetupFailed'.tr(), - backgroundColor: Colors.red); - setState(() { - _isBiometryEnabled = false; - }); - } - } else { - // Disable - await CacheUtils.setBiometryEnabled(false); - await BiometricAuth.clearEncryptionKey(); - await Fluttertoast.showToast( - msg: 'biometricsDisabled'.tr(), - backgroundColor: Colors.grey); - setState(() { - _isBiometryEnabled = false; - }); - } - await Singleton().profile.save(); - }, - ) + const SizedBox(width: 8), + Text(_languageNames[locale.languageCode] ?? + locale.languageCode), ], ), ), + ], + ), + ); + if (selected == null || !mounted) { + return; + } + await context.setLocale(selected); + } - Divider(thickness: 1, indent: 10, endIndent: 10), + static const _languageNames = {'cs': 'Čeština', 'en': 'English'}; - // How it works - TextButton( - onPressed: () async { - var url = Uri.parse('https://github.com/jsfraz/whisper/wiki'); - if (!await launchUrl(url)) { - await Fluttertoast.showToast( - msg: sprintf('urlError'.tr(), [url.toString()]), - backgroundColor: Colors.red); - } - }, - child: Row( - children: [ - Icon( - Icons.help, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'wikiLink'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - SizedBox( - width: 24, - ), - ], - ), - ), + Future _toggleBiometry(bool switchValue) async { + if (switchValue) { + // Enable + final success = await BiometricAuth.storeEncryptionKey( + Singleton().boxCollectionKey, context); + if (success) { + await Fluttertoast.showToast( + msg: 'biometricsEnabled'.tr(), backgroundColor: Colors.grey); + setState(() { + _isBiometryEnabled = true; + }); + } else { + await Fluttertoast.showToast( + msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); + setState(() { + _isBiometryEnabled = false; + }); + } + } else { + // Disable + final success = await BiometricAuth.disableBiometricAuth(context); + if (success) { + await Fluttertoast.showToast( + msg: 'biometricsDisabled'.tr(), backgroundColor: Colors.grey); + setState(() { + _isBiometryEnabled = false; + }); + } else { + await Fluttertoast.showToast( + msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); + setState(() { + _isBiometryEnabled = true; + }); + } + } + } - // Repo - TextButton( - onPressed: () async { - var url = Uri.parse('https://github.com/jsfraz/whisper'); - if (!await launchUrl(url)) { - await Fluttertoast.showToast( - msg: sprintf('urlError'.tr(), [url.toString()]), - backgroundColor: Colors.red); - } - }, - child: Row( - children: [ - Icon( - Icons.code, - size: 24, - color: Theme.of(context).colorScheme.secondary, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'repoLink'.tr(), - style: TextStyle( - color: Theme.of(context).colorScheme.secondary), - ), - ), - SizedBox( - width: 24, - ), - ], + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('settingsPage'.tr()), + ), + body: SafeArea( + child: SingleChildScrollView( + child: Column( + children: [ + _settingsTile( + icon: Icons.palette, + label: 'themeSettings'.tr(), + onPressed: () => showDialog( + context: context, builder: DialogUtils.themeDialog), ), - ), - - Divider(thickness: 1, indent: 10, endIndent: 10), - - // TODO change password - - // Divider(thickness: 1, indent: 10, endIndent: 10), - - // Danger zone title - Padding( - padding: EdgeInsets.only(bottom: 5), - child: Text( - 'dangerZone'.tr(), - style: TextStyle( - color: Colors.red, - fontWeight: FontWeight.bold, - fontSize: 16), + _settingsTile( + icon: Icons.language, + label: 'languageSettings'.tr(), + onPressed: _showLanguageDialog, ), - ), - - // Delete all chats - TextButton( - onPressed: () async { - await DialogUtils.yesNoDialog( - context, - 'deleteAllChatsConfirm'.tr(), - 'deleteAllChatsConfirmText'.tr(), () async { - MessageNotifier().deleteAllChats(); - Navigator.pop(context); - }); - }, - child: Row( - children: [ - Icon( - Icons.delete_forever, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'deleteAllChats'.tr(), - style: TextStyle(color: Colors.red), - ), - ), - SizedBox( - width: 24, - ), - ], + _settingsTile( + icon: Icons.notifications, + label: 'notificationSettings'.tr(), + trailing: Switch( + value: Singleton().profile.enableNotifications, + onChanged: (value) async { + setState(() { + Singleton().profile.enableNotifications = + !Singleton().profile.enableNotifications; + }); + await Singleton().profile.save(); + }, + ), ), - ), - - // Logout (delete account) - TextButton( - onPressed: () async { - await DialogUtils.yesNoDialog( - context, 'logoutConfirm'.tr(), 'logoutConfirmText'.tr(), - () async { - // Delete everything and close app - try { - await Utils.callApi(() => Singleton().userApi.deleteMe()); - await CacheUtils.deleteCache(); - await Fluttertoast.showToast( - msg: 'accountDeleted1'.tr(), - backgroundColor: Colors.grey); - if (Platform.isIOS) { - // Apple (https://stackoverflow.com/a/57534684/19371130) - Navigator.pushReplacement( - context, - MaterialPageRoute( - builder: (context) => ScanInviteButtonPage())); - } else if (Platform.isAndroid) { - // Android - SystemNavigator.pop(); + _settingsTile( + icon: Icons.visibility, + label: 'notificationPreview'.tr(), + trailing: Switch( + value: _notificationPreview, + onChanged: (value) async { + setState(() { + _notificationPreview = !_notificationPreview; + }); + await CacheUtils.setNotificationPreview( + _notificationPreview); + }, + ), + ), + // Both live-metadata switches are off by default: with them off + // no frame is ever sent and the server learns nothing. + _settingsTile( + icon: Icons.edit_notifications, + label: 'typingIndicator'.tr(), + trailing: Switch( + value: _typingIndicator, + onChanged: (value) async { + setState(() { + _typingIndicator = !_typingIndicator; + }); + await CacheUtils.setTypingIndicatorEnabled( + _typingIndicator); + }, + ), + ), + _settingsTile( + icon: Icons.circle, + label: 'presence'.tr(), + trailing: Switch( + value: _presence, + onChanged: (value) async { + setState(() { + _presence = !_presence; + }); + await CacheUtils.setPresenceEnabled(_presence); + // Turning it on announces right away; turning it off tells + // the peers, so nobody keeps a stale "online". + if (_presence) { + await Utils.announcePresence(); + } else { + await Utils.withdrawPresence(); } - } catch (e) { - await Fluttertoast.showToast( - msg: e.toString(), backgroundColor: Colors.red); - } - }); - }, - child: Row( - children: [ - Icon( - Icons.logout, - size: 24, - color: Colors.red, - ), - Padding( - padding: EdgeInsets.only(left: 5), - child: Text( - 'logoutAndDelete'.tr(), - style: TextStyle(color: Colors.red), + }, + ), + ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + _settingsTile( + icon: Icons.fingerprint, + label: 'biometrySettings'.tr(), + trailing: Switch( + value: _isBiometryEnabled, + onChanged: _toggleBiometry, + ), + ), + _settingsTile( + icon: Icons.devices, + label: 'devicesSettings'.tr(), + onPressed: () async { + await Navigator.push(context, stepRoute(const DevicesPage())); + }, + ), + _settingsTile( + icon: Icons.storage, + label: 'storageTitle'.tr(), + onPressed: () async { + await Navigator.push(context, stepRoute(const StoragePage())); + }, + ), + _settingsTile( + icon: Icons.download_for_offline_outlined, + label: 'autoDownloadTitle'.tr(), + trailing: DropdownButton( + value: _autoDownload, + underline: const SizedBox.shrink(), + onChanged: (policy) async { + if (policy == null) { + return; + } + setState(() => _autoDownload = policy); + await CacheUtils.setAutoDownloadPolicy(policy); + }, + items: [ + DropdownMenuItem( + value: AutoDownloadPolicy.always, + child: Text('autoDownloadAlways'.tr()), ), - ), - SizedBox( - width: 24, - ), - ], + DropdownMenuItem( + value: AutoDownloadPolicy.wifi, + child: Text('autoDownloadWifi'.tr()), + ), + DropdownMenuItem( + value: AutoDownloadPolicy.never, + child: Text('autoDownloadNever'.tr()), + ), + ], + ), ), - ), - ], + _settingsTile( + icon: Icons.archive, + label: 'retentionSettings'.tr(), + onPressed: _showRetentionDialog, + ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + _settingsTile( + icon: Icons.help, + label: 'wikiLink'.tr(), + onPressed: () => + _openUrl('https://github.com/jsfraz/shept/wiki'), + ), + _settingsTile( + icon: Icons.code, + label: 'repoLink'.tr(), + onPressed: () => _openUrl('https://github.com/jsfraz/shept'), + ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + _settingsTile( + icon: Icons.password, + label: 'changePassword'.tr(), + onPressed: () async { + final changed = await showDialog( + context: context, + builder: (context) => const ChangePasswordDialog()); + if (changed == true) { + await Fluttertoast.showToast(msg: 'passwordChanged'.tr()); + } + }, + ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + _settingsTile( + icon: Icons.delete_forever, + label: 'deleteAllChats'.tr(), + color: Colors.red, + onPressed: () async { + await DialogUtils.yesNoDialog( + context, + 'deleteAllChatsConfirm'.tr(), + 'deleteAllChatsConfirmText'.tr(), () async { + MessageNotifier().deleteAllChats(); + Navigator.pop(context); + }); + }, + ), + _settingsTile( + icon: Icons.logout, + label: 'logoutAndDelete'.tr(), + color: Colors.red, + onPressed: () async { + await DialogUtils.yesNoDialog( + context, 'logoutConfirm'.tr(), 'logoutConfirmText'.tr(), + () async { + // Delete everything and close app + try { + await Utils.callApi(() => Singleton().userApi.deleteMe()); + await CacheUtils.deleteCache(); + await Fluttertoast.showToast( + msg: 'accountDeleted1'.tr(), + backgroundColor: Colors.grey); + if (Platform.isIOS) { + // Apple (https://stackoverflow.com/a/57534684/19371130) + Navigator.pushReplacement( + context, fadeRoute(ScanInviteButtonPage())); + } else if (Platform.isAndroid) { + // Android + SystemNavigator.pop(); + } + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } + }); + }, + ), + ], + ), ), ), ); } + + /// One settings row in the app's accent colour. + Widget _settingsTile({ + required IconData icon, + required String label, + VoidCallback? onPressed, + Widget? trailing, + Color? color, + }) { + return SettingsTile( + icon: icon, + label: label, + onPressed: onPressed, + trailing: trailing, + color: color ?? Theme.of(context).colorScheme.secondary, + ); + } + + Future _openUrl(String url) async { + final uri = Uri.parse(url); + if (!await launchUrl(uri)) { + await Fluttertoast.showToast( + msg: sprintf('urlError'.tr(), [uri.toString()]), + backgroundColor: Colors.red); + } + } } diff --git a/lib/pages/whisper_page.dart b/lib/pages/shept_page.dart similarity index 52% rename from lib/pages/whisper_page.dart rename to lib/pages/shept_page.dart index ec588e9..62e8e82 100644 --- a/lib/pages/whisper_page.dart +++ b/lib/pages/shept_page.dart @@ -1,14 +1,28 @@ import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../utils/app_navigator.dart'; import '../utils/page_navigator_observer.dart'; import '../utils/theme_notifier.dart'; import '../pages/scan_invite_button_page.dart'; import 'password_page.dart'; import '../utils/cache_utils.dart'; -class WhisperPage extends StatelessWidget { - const WhisperPage({super.key}); +class SheptPage extends StatelessWidget { + const SheptPage({super.key}); + + /// Fade-through everywhere so `MaterialPageRoute` pushes (forward, search, + /// registration) use the same timing as the rest of the app. + static const PageTransitionsTheme _pageTransitionsTheme = + PageTransitionsTheme(builders: { + TargetPlatform.android: FadeForwardsPageTransitionsBuilder(), + TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.linux: FadeForwardsPageTransitionsBuilder(), + TargetPlatform.macOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.windows: FadeForwardsPageTransitionsBuilder(), + TargetPlatform.fuchsia: FadeForwardsPageTransitionsBuilder(), + }); /// Returns default page based on user in cache. Future _getDefaultPage() async { @@ -39,22 +53,29 @@ class WhisperPage extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( + navigatorKey: appNavigatorKey, navigatorObservers: [PageNavigatorObserver()], debugShowCheckedModeBanner: true, + // Every DateFormat in the app (chat rows, bubbles, day headers, search) + // follows the selected language instead of the platform default. + builder: (context, child) { + Intl.defaultLocale = context.locale.toString(); + return child ?? const SizedBox.shrink(); + }, // Light theme theme: ThemeData.from( - colorScheme: ColorScheme.fromSeed( - seedColor: Provider.of(context).appTheme.color, - brightness: Brightness.light), - useMaterial3: - Provider.of(context).appTheme.useMaterial3), + colorScheme: ColorScheme.fromSeed( + seedColor: Provider.of(context).appTheme.color, + brightness: Brightness.light), + useMaterial3: true) + .copyWith(pageTransitionsTheme: _pageTransitionsTheme), // Dark theme darkTheme: ThemeData.from( - colorScheme: ColorScheme.fromSeed( - seedColor: Provider.of(context).appTheme.color, - brightness: Brightness.dark), - useMaterial3: - Provider.of(context).appTheme.useMaterial3), + colorScheme: ColorScheme.fromSeed( + seedColor: Provider.of(context).appTheme.color, + brightness: Brightness.dark), + useMaterial3: true) + .copyWith(pageTransitionsTheme: _pageTransitionsTheme), // Light / Dark / System themeMode: Provider.of(context).appTheme.themeMode, localizationsDelegates: context.localizationDelegates, diff --git a/lib/pages/storage_page.dart b/lib/pages/storage_page.dart new file mode 100644 index 0000000..7b34d1e --- /dev/null +++ b/lib/pages/storage_page.dart @@ -0,0 +1,153 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/cache_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/storage_utils.dart'; +import '../widgets/settings_tile.dart'; + +/// What attachments cost on this device: per conversation, plus the two ways to +/// get the space back. +class StoragePage extends StatefulWidget { + const StoragePage({super.key}); + + @override + State createState() => _StoragePageState(); +} + +class _StoragePageState extends State { + /// Auto-delete choices in days; 0 keeps the media forever. + static const List _autoDeleteChoices = [0, 7, 30, 90]; + + List _usage = const []; + Map _names = {}; + int _days = 0; + bool _loading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + final usage = await StorageUtils.usageByConversation(); + final names = {}; + for (final entry in usage) { + final user = await CacheUtils.getUserById(entry.conversationId); + names[entry.conversationId] = user?.username ?? entry.conversationId; + } + final days = await CacheUtils.getAutoDeleteMediaDays(); + if (!mounted) { + return; + } + setState(() { + _usage = usage; + _names = names; + _days = days; + _loading = false; + }); + } + + Future _setDays(int days) async { + setState(() => _days = days); + await CacheUtils.setAutoDeleteMediaDays(days); + final freed = days == 0 ? 0 : await StorageUtils.purgeOlderThanDays(days); + await _load(); + if (freed > 0 && mounted) { + await Fluttertoast.showToast( + msg: '${'storagePurged'.tr()} ${MediaUtils.formatBytes(freed)}'); + } + } + + Future _clearCache() async { + await StorageUtils.clearCache(); + if (mounted) { + await Fluttertoast.showToast(msg: 'storageCacheCleared'.tr()); + } + } + + @override + Widget build(BuildContext context) { + final totalBytes = _usage.fold(0, (sum, entry) => sum + entry.bytes); + final totalFiles = + _usage.fold(0, (sum, entry) => sum + entry.attachments); + return Scaffold( + appBar: AppBar(title: Text('storageTitle'.tr())), + body: SafeArea( + child: _loading + ? const Center(child: CircularProgressIndicator()) + : ListView( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 24, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(MediaUtils.formatBytes(totalBytes), + style: Theme.of(context).textTheme.headlineMedium), + Text( + '${'storageTotal'.tr()} · $totalFiles ${'storageMediaCount'.tr()}', + ), + ], + ), + ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + SettingsTile( + icon: Icons.auto_delete, + label: 'storageAutoDelete'.tr(), + onPressed: () => _setDays(_days), + trailing: DropdownButton( + value: _days, + underline: const SizedBox.shrink(), + onChanged: (days) { + if (days != null) { + _setDays(days); + } + }, + items: [ + for (final days in _autoDeleteChoices) + DropdownMenuItem( + value: days, + child: Text(days == 0 + ? 'storageNever'.tr() + : '$days ${'storageDaysSuffix'.tr()}'), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text( + 'storageSingleDelivery'.tr(), + style: Theme.of(context).textTheme.bodySmall, + ), + ), + SettingsTile( + icon: Icons.cleaning_services, + label: 'storageClearCache'.tr(), + onPressed: _clearCache, + ), + const Divider(thickness: 1, indent: 10, endIndent: 10), + if (_usage.isEmpty) + Padding( + padding: const EdgeInsets.all(16), + child: Text('storageEmpty'.tr()), + ) + else + for (final usage in _usage) + ListTile( + leading: const Icon(Icons.folder_outlined), + title: Text(_names[usage.conversationId] ?? ''), + subtitle: Text( + '${usage.attachments} ${'storageMediaCount'.tr()}', + ), + trailing: Text(MediaUtils.formatBytes(usage.bytes)), + ), + ], + ), + ), + ); + } +} diff --git a/lib/pages/video_trim_page.dart b/lib/pages/video_trim_page.dart new file mode 100644 index 0000000..22b648a --- /dev/null +++ b/lib/pages/video_trim_page.dart @@ -0,0 +1,204 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:video_trimmer/video_trimmer.dart'; + +/// Picks the part of a video that is worth sending. +/// +/// The platform encoder does the cut (Media3 on Android), so the output is a +/// plain mp4 that every recipient can play. Returns the trimmed file from +/// [open], or null when the user backs out. +class VideoTrimPage extends StatefulWidget { + const VideoTrimPage(this.file, {super.key}); + + final File file; + + static Future open(BuildContext context, File file) { + return Navigator.push( + context, MaterialPageRoute(builder: (_) => VideoTrimPage(file))); + } + + @override + State createState() => _VideoTrimPageState(); +} + +class _VideoTrimPageState extends State { + final Trimmer _trimmer = Trimmer(); + + /// Selection in milliseconds, as the trim viewer reports it. + double _startValue = 0; + double _endValue = 0; + bool _ready = false; + bool _playing = false; + bool _saving = false; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + await _trimmer.loadVideo(videoPath: widget.file.path); + // The viewer starts on the whole clip; without this the selection would be + // the 0..0 range it is initialised with. + final durationMs = _trimmer + .videoPlayerController?.value.duration.inMilliseconds + .toDouble() ?? + 0; + if (mounted) { + setState(() { + _ready = true; + _endValue = durationMs; + }); + } + } + + Future _togglePlayback() async { + final playing = await _trimmer.videoPlaybackControl( + startValue: _startValue, + endValue: _endValue, + ); + if (mounted && playing != _playing) { + setState(() => _playing = playing); + } + } + + Future _save() async { + setState(() => _saving = true); + await _trimmer.saveTrimmedVideo( + startValue: _startValue, + endValue: _endValue, + onSave: (path) { + if (!mounted) { + return; + } + Navigator.pop(context, path == null ? null : File(path)); + }, + ); + if (mounted) { + setState(() => _saving = false); + } + } + + @override + void dispose() { + _trimmer.dispose(); + super.dispose(); + } + + String _format(double milliseconds) { + final total = Duration(milliseconds: milliseconds.round()); + final minutes = total.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = total.inSeconds.remainder(60).toString().padLeft(2, '0'); + final tenths = (total.inMilliseconds.remainder(1000) ~/ 100); + return '$minutes:$seconds.$tenths'; + } + + @override + Widget build(BuildContext context) { + final hasRange = _endValue > _startValue; + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + backgroundColor: Colors.black, + foregroundColor: Colors.white, + title: Text('trimVideo'.tr()), + bottom: _saving + ? const PreferredSize( + preferredSize: Size.fromHeight(2), + child: LinearProgressIndicator(minHeight: 2), + ) + : null, + ), + body: !_ready + ? const Center(child: CircularProgressIndicator()) + : SafeArea( + child: Column( + children: [ + // The picture gets the room: this is where the cut is judged. + Expanded( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 0), + child: VideoViewer( + trimmer: _trimmer, + borderColor: Colors.white24, + ), + ), + ), + const SizedBox(height: 8), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(_format(_startValue), + style: const TextStyle( + color: Colors.white70, + fontFeatures: [FontFeature.tabularFigures()])), + Text(_format(_endValue - _startValue), + style: const TextStyle( + color: Color(0xFFFFC400), + fontWeight: FontWeight.w600)), + Text(_format(_endValue), + style: const TextStyle( + color: Colors.white70, + fontFeatures: [FontFeature.tabularFigures()])), + ], + ), + ), + Padding( + padding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: TrimViewer( + trimmer: _trimmer, + viewerWidth: MediaQuery.sizeOf(context).width - 32, + viewerHeight: 56, + showDuration: false, + paddingFraction: 0.15, + onChangeStart: (value) => + setState(() => _startValue = value), + onChangeEnd: (value) => setState(() => _endValue = value), + onChangePlaybackState: (value) => + setState(() => _playing = value), + ), + ), + IconButton( + iconSize: 56, + color: Colors.white, + onPressed: hasRange ? _togglePlayback : null, + icon: Icon( + _playing + ? Icons.pause_circle_filled + : Icons.play_circle_fill, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 12), + child: Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: + _saving ? null : () => Navigator.pop(context), + child: Text('cancel'.tr()), + ), + ), + const SizedBox(width: 12), + Expanded( + child: FilledButton.icon( + onPressed: hasRange && !_saving ? _save : null, + icon: const Icon(Icons.content_cut), + label: Text('applyTrim'.tr()), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/utils/admin_format.dart b/lib/utils/admin_format.dart new file mode 100644 index 0000000..c61b3c1 --- /dev/null +++ b/lib/utils/admin_format.dart @@ -0,0 +1,27 @@ +import '../models/user.dart'; + +/// Remaining lifetime of an invite, bucketed for a list row. +/// +/// Returns the largest sensible unit and its value, or `null` once the +/// invite expired. `min` is clamped to at least 1 so a fresh invite never +/// reads "in 0 min". +({int value, String unit})? inviteRemaining(Duration remaining) { + if (remaining.isNegative) { + return null; + } + if (remaining.inMinutes < 60) { + return (value: remaining.inMinutes.clamp(1, 59), unit: 'min'); + } + if (remaining.inHours < 24) { + return (value: remaining.inHours, unit: 'h'); + } + return (value: remaining.inDays, unit: 'd'); +} + +/// Users sorted by name, the way the admin list shows them. +List sortedByUsername(List users) { + final sorted = [...users]; + sorted.sort( + (a, b) => a.username.toLowerCase().compareTo(b.username.toLowerCase())); + return sorted; +} diff --git a/lib/utils/app_navigator.dart b/lib/utils/app_navigator.dart new file mode 100644 index 0000000..19d5d32 --- /dev/null +++ b/lib/utils/app_navigator.dart @@ -0,0 +1,5 @@ +import 'package:flutter/widgets.dart'; + +/// Navigator of the running app, for code that has no widget of its own: an +/// inbound share has to open a chat picker before any screen exists. +final GlobalKey appNavigatorKey = GlobalKey(); diff --git a/lib/utils/auto_download.dart b/lib/utils/auto_download.dart new file mode 100644 index 0000000..1a0c969 --- /dev/null +++ b/lib/utils/auto_download.dart @@ -0,0 +1,60 @@ +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +import 'cache_utils.dart'; + +/// When an incoming attachment is downloaded without asking. +enum AutoDownloadPolicy { + /// Always, on any network. + always, + + /// Only on Wi-Fi, so a photo does not eat the mobile data plan. + wifi, + + /// Never automatically; the bubble offers a download button. + never, +} + +/// Decides whether an incoming attachment may be downloaded right away. +/// +/// The setting exists because attachments are the only part of a chat that can +/// quietly cost money: they arrive on their own, unlike a message. +class AutoDownload { + AutoDownload._(); + + /// Attachments below this size are always fetched: a voice message or a + /// sticker is what makes the chat readable at all. + static const int smallAttachmentBytes = 1024 * 1024; + + /// Whether [reference] may be downloaded now. + static Future allows(MediaReference reference) async { + if (reference.type == MediaType.voice || + reference.type == MediaType.sticker || + reference.size <= smallAttachmentBytes) { + return true; + } + switch (await CacheUtils.getAutoDownloadPolicy()) { + case AutoDownloadPolicy.always: + return true; + case AutoDownloadPolicy.wifi: + return await onWifi(); + case AutoDownloadPolicy.never: + return false; + } + } + + /// Whether the device is on an unmetered network right now. + /// + /// Unknown reads as "not on Wi-Fi": guessing the other way spends the user's + /// mobile data on a policy that says not to. + static Future onWifi() async { + try { + final results = await Connectivity().checkConnectivity(); + return results.contains(ConnectivityResult.wifi) || + results.contains(ConnectivityResult.ethernet); + } catch (_) { + return false; + } + } +} diff --git a/lib/utils/biometric_auth.dart b/lib/utils/biometric_auth.dart index a39b584..1fb4aa2 100644 --- a/lib/utils/biometric_auth.dart +++ b/lib/utils/biometric_auth.dart @@ -10,7 +10,7 @@ import 'cache_utils.dart'; class BiometricAuth { static final LocalAuthentication _auth = LocalAuthentication(); static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); - static const String _biometricKeyStorageKey = 'whisper_secure_key'; + static const String _biometricKeyStorageKey = 'shept_secure_key'; /// Checks if biometric authentication is available on the device static Future isBiometricAvailable() async { @@ -19,7 +19,8 @@ class BiometricAuth { try { canAuthenticateWithBiometrics = await _auth.canCheckBiometrics; - canAuthenticate = canAuthenticateWithBiometrics || await _auth.isDeviceSupported(); + canAuthenticate = + canAuthenticateWithBiometrics || await _auth.isDeviceSupported(); } on PlatformException catch (e) { debugPrint(e.toString()); return false; @@ -40,32 +41,54 @@ class BiometricAuth { } /// Saves the decryption key to a secure storage protected by biometrics - static Future storeEncryptionKey(List key, BuildContext context) async { + static Future storeEncryptionKey( + List key, BuildContext context) async { try { // Convert the key to a string for storage final String keyString = key.join(','); // Verify biometric credentials before storing the key bool authenticated = await authenticate( - 'biometricSetupReason'.tr(), - 'biometricSetupAuth'.tr(), - context); - + 'biometricSetupReason'.tr(), 'biometricSetupAuth'.tr(), context); + if (authenticated) { // Store the key securely - await _secureStorage.write(key: _biometricKeyStorageKey, value: keyString); + await _secureStorage.write( + key: _biometricKeyStorageKey, value: keyString); // Enable biometric authentication await CacheUtils.setBiometryEnabled(true); return true; } - + return false; } catch (e) { debugPrint('Error storing encryption key: $e'); await Fluttertoast.showToast( - msg: 'biometricSetupFailed'.tr(), - backgroundColor: Colors.red - ); + msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); + return false; + } + } + + /// Delete the decryption key from secure storage and disable biometric authentication + static Future disableBiometricAuth(BuildContext context) async { + try { + // Verify biometric credentials before storing the key + bool authenticated = await authenticate( + 'biometricSetupReason'.tr(), 'biometricSetupAuth'.tr(), context); + + if (authenticated) { + // Delete the stored key + await _secureStorage.delete(key: _biometricKeyStorageKey); + // Disable biometric authentication + await CacheUtils.setBiometryEnabled(false); + return true; + } + + return false; + } catch (e) { + debugPrint('Error disabling encryption key: $e'); + await Fluttertoast.showToast( + msg: 'biometricSetupFailed'.tr(), backgroundColor: Colors.red); return false; } } @@ -75,19 +98,18 @@ class BiometricAuth { try { // Verify biometric credentials before retrieving the key bool authenticated = await authenticate( - 'biometricAuthReason'.tr(), - 'biometricAuthPrompt'.tr(), - context); - + 'biometricAuthReason'.tr(), 'biometricAuthPrompt'.tr(), context); + if (authenticated) { // Get the stored key - final String? keyString = await _secureStorage.read(key: _biometricKeyStorageKey); + final String? keyString = + await _secureStorage.read(key: _biometricKeyStorageKey); if (keyString != null && keyString.isNotEmpty) { // Convert the string back to a list of bytes return keyString.split(',').map((s) => int.parse(s)).toList(); } } - + return null; } catch (e) { debugPrint('Error retrieving encryption key: $e'); @@ -101,22 +123,19 @@ class BiometricAuth { } /// Performs biometric authentication - static Future authenticate(String reason, String authString, BuildContext context) async { + static Future authenticate( + String reason, String authString, BuildContext context) async { try { return await _auth.authenticate( localizedReason: reason, - options: const AuthenticationOptions( - stickyAuth: true, - biometricOnly: true, - ) + biometricOnly: true, + persistAcrossBackgrounding: true, ); - } on PlatformException catch (e) { - debugPrint('Authentication error: $e'); + } on LocalAuthException catch (e) { + debugPrint('Authentication error: ${e.code} - ${e.description}'); await Fluttertoast.showToast( - msg: 'biometricAuthFailed'.tr(), - backgroundColor: Colors.red - ); + msg: 'biometricAuthFailed'.tr(), backgroundColor: Colors.red); return false; } } -} \ No newline at end of file +} diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index c988989..adbb85b 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -1,10 +1,21 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' show Color; + import 'package:bcrypt/bcrypt.dart'; +import 'package:uuid/uuid.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:hive/hive.dart'; -import 'package:whisper/utils/biometric_auth.dart'; +import '../utils/biometric_auth.dart'; import '../models/app_theme.dart'; import '../models/private_message.dart'; import '../models/profile.dart'; import '../models/user.dart'; +import 'color_utils.dart'; +import 'crypto_utils.dart'; +import 'auto_download.dart'; +import 'media_utils.dart'; +import 'message_search.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -15,7 +26,90 @@ class CacheUtils { static const _privateMessagesKey = 'privateMessages'; static const _userKey = 'user'; static const _messageConceptKey = 'messageConcept'; + static const _pendingSendsKey = 'pendingSends'; + static const _settingsKey = 'settings'; + static const _notificationPreviewKey = 'notificationPreview'; + static const _typingIndicatorKey = 'typingIndicator'; + static const _presenceKey = 'presence'; static const _biometry = 'biometry'; + static const _playbackSpeed = 'playbackSpeed'; + static const String _saltStorageKey = 'shept_pbkdf2_salt'; + static const String _deviceIdKey = 'shept_device_id'; + static const String _syncSeqKey = 'syncSeq'; + static const String _syncEventSeqKey = 'syncEventSeq'; + static const FlutterSecureStorage _secureStorage = FlutterSecureStorage(); + static const _chatThemeKeyPrefix = 'chatTheme:'; + + /// Id of this installation, created once and kept in secure storage. + /// + /// It is the device the server registers, revokes and reports in the login + /// JWT. Losing it (a reinstall) is deliberately the same as a new device. + static Future getOrCreateDeviceId() async { + final stored = await _secureStorage.read(key: _deviceIdKey); + if (stored != null && stored.isNotEmpty) { + return stored; + } + final id = const Uuid().v4(); + await _secureStorage.write(key: _deviceIdKey, value: id); + return id; + } + + /// Human readable name of this platform, shown in the device list. + static String get deviceLabel { + if (Platform.isAndroid) { + return 'Android'; + } + if (Platform.isIOS) { + return 'iOS'; + } + if (Platform.isLinux) { + return 'Linux'; + } + if (Platform.isMacOS) { + return 'macOS'; + } + if (Platform.isWindows) { + return 'Windows'; + } + return Platform.operatingSystem; + } + + /// Server platform tag of this installation. + static String get devicePlatform => Platform.operatingSystem; + + /// Highest archive `seq` stored on this device. A reconnect asks the server + /// for everything above it instead of receiving a full queue dump. + static Future getSyncSeq() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_syncSeqKey) as int? ?? 0; + } + + /// Advances the archive cursor. It never moves backwards: a sync page can + /// arrive out of order after two overlapping requests. + static Future setSyncSeq(int seq) async { + Box box = await Hive.openBox(_settingsKey); + final stored = box.get(_syncSeqKey) as int? ?? 0; + if (seq > stored) { + await box.put(_syncSeqKey, seq); + } + } + + /// Highest mutation-log `eventSeq` stored on this device. Edits, deletions, + /// reactions and pins only reach a device that was offline through this + /// cursor. + static Future getSyncEventSeq() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_syncEventSeqKey) as int? ?? 0; + } + + /// Advances the mutation cursor; like [setSyncSeq] it never moves backwards. + static Future setSyncEventSeq(int seq) async { + Box box = await Hive.openBox(_settingsKey); + final stored = box.get(_syncEventSeqKey) as int? ?? 0; + if (seq > stored) { + await box.put(_syncEventSeqKey, seq); + } + } /// Opens box with password hash static Future _openPasswordHashBox() async { @@ -40,6 +134,22 @@ class CacheUtils { return BCrypt.checkpw(password, hash!); } + /// Returns the PBKDF2 salt, or null for installs created before salts became + /// random (those still derive it from the password). + static Future?> getSalt() async { + final String? stored = await _secureStorage.read(key: _saltStorageKey); + if (stored == null || stored.isEmpty) { + return null; + } + return base64.decode(stored); + } + + /// Stores the PBKDF2 salt. + static Future setSalt(List salt) async { + await _secureStorage.write( + key: _saltStorageKey, value: base64.encode(salt)); + } + /// Opens encrypted box static Future _openBoxCollection(Set boxNames) async { return BoxCollection.open('_encrypted', boxNames, @@ -81,17 +191,24 @@ class CacheUtils { await passwordBox.deleteFromDisk(); Box themeBox = await _openThemeBox(); await themeBox.deleteFromDisk(); + await _secureStorage.delete(key: _saltStorageKey); Box privateMessagesBox = await _openPrivateMessagesBox(); await privateMessagesBox.deleteFromDisk(); Box userBox = await _openUserBox(); userBox.deleteFromDisk(); Box messageConceptBox = await _openMessageConceptBox(); messageConceptBox.deleteFromDisk(); + Box pendingSendsBox = await _openPendingSendsBox(); + pendingSendsBox.deleteFromDisk(); + Box settingsBox = await Hive.openBox(_settingsKey); + settingsBox.deleteFromDisk(); if (await isBiometryEnabled()) { await BiometricAuth.clearEncryptionKey(); } Box biometryBox = await _openBiometryBox(); await biometryBox.deleteFromDisk(); + // Remove every locally stored media file. + await MediaUtils.clearMediaDir(); } /// Opens box with theme @@ -111,6 +228,110 @@ class CacheUtils { await box.put(_themeKey, theme); } + /// Changes the local password (app lock + at-rest encryption key). + /// + /// Returns false when [currentPassword] is wrong. Media files are staged + /// under the new key first and only swapped in after the profile box has been + /// rewritten, so a failure leaves the old password valid and the data intact. + static Future changePassword( + String currentPassword, String newPassword) async { + if (!await isCorrectPassword(currentPassword)) { + return false; + } + final List oldKey = List.from(Singleton().boxCollectionKey); + final List salt = CryptoUtils.generateSalt(); + final List newKey = await CryptoUtils.pbkdf2(newPassword, salt); + await _rekeyData(oldKey, newKey); + await setSalt(salt); + await setPasswordHash(newPassword); + return true; + } + + /// One-time migration from the legacy `md5(password)` salt to a random one. + /// Returns true when the data was re-encrypted; false when there is nothing + /// to migrate. + static Future migrateSalt(String password) async { + if (await getSalt() != null) { + return false; + } + if (!await isCorrectPassword(password)) { + return false; + } + final List oldKey = await CryptoUtils.legacyPbkdf2(password); + final List salt = CryptoUtils.generateSalt(); + final List newKey = await CryptoUtils.pbkdf2(password, salt); + Singleton().boxCollectionKey = oldKey; + await _rekeyData(oldKey, newKey); + await setSalt(salt); + return true; + } + + /// Re-encrypts the profile box and every at-rest media file from [oldKey] to + /// [newKey]. Media is staged first and swapped in only after the profile is + /// written; the profile box is backed up, so a failure keeps [oldKey] valid. + static Future _rekeyData(List oldKey, List newKey) async { + final Profile loaded = await getProfile(); + // A fresh instance: the loaded one is still attached to the box we are + // about to replace, and Hive refuses to store it in a second box. + final Profile profile = Profile( + loaded.url, + loaded.user, + loaded.publicKey, + loaded.privateKey, + loaded.accessToken, + loaded.refreshToken, + loaded.enableNotifications); + // Hive stores the collection as `_encrypted/_encrypted_.hive`. + final File boxFile = File( + '${await Utils.getCacheDir()}_encrypted/_encrypted_$_profileKey.hive'); + final File backup = File('${boxFile.path}.bak'); + + final List staged = await MediaUtils.stageRekey(oldKey, newKey); + try { + await Hive.close(); + if (await boxFile.exists()) { + await boxFile.rename(backup.path); + } + Singleton().boxCollectionKey = newKey; + await setProfile(profile); + } catch (e) { + // Roll back to the old key and the old profile box. + await Hive.close(); + Singleton().boxCollectionKey = oldKey; + if (await boxFile.exists()) { + await boxFile.delete(); + } + if (await backup.exists()) { + await backup.rename(boxFile.path); + } + await MediaUtils.discardRekey(staged); + rethrow; + } + if (await backup.exists()) { + await backup.delete(); + } + await MediaUtils.commitRekey(staged); + } + + /// Returns per-chat theme color, null means the global theme is used + static Future getChatTheme(String userId) async { + Box box = await _openThemeBox(); + String? hex = box.get('$_chatThemeKeyPrefix$userId'); + return hex == null ? null : ColorUtils.colorFromHex(hex); + } + + /// Sets per-chat theme color + static Future setChatTheme(String userId, Color color) async { + Box box = await _openThemeBox(); + await box.put('$_chatThemeKeyPrefix$userId', ColorUtils.colorToHex(color)); + } + + /// Clears per-chat theme color, the chat falls back to the global theme + static Future clearChatTheme(String userId) async { + Box box = await _openThemeBox(); + await box.delete('$_chatThemeKeyPrefix$userId'); + } + /// Opens box with biometry static Future _openBiometryBox() async { return Hive.openBox(_biometry); @@ -128,44 +349,700 @@ class CacheUtils { await box.put(_biometry, enabled); } - /// Opens box with private messages + /// Whether notifications may show the decrypted message text. Default off: + /// the text stays hidden until the user opts in. + static Future getNotificationPreview() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_notificationPreviewKey) as bool? ?? false; + } + + /// Sets whether notifications may show the message text. + static Future setNotificationPreview(bool value) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_notificationPreviewKey, value); + } + + /// Whether this device tells its peers that it is typing. Default off: with + /// it off no frame is ever sent, so the server has nothing to relay. + static Future isTypingIndicatorEnabled() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_typingIndicatorKey) as bool? ?? false; + } + + /// Turns the typing indicator on or off. + static Future setTypingIndicatorEnabled(bool value) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_typingIndicatorKey, value); + } + + /// Whether this device announces its presence and last seen. Default off. + static Future isPresenceEnabled() async { + Box box = await Hive.openBox(_settingsKey); + return box.get(_presenceKey) as bool? ?? false; + } + + /// Turns presence on or off. + static Future setPresenceEnabled(bool value) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_presenceKey, value); + } + + /// Opens box with playback preferences + static Future _openPlaybackBox() async { + return Hive.openBox(_playbackSpeed); + } + + /// Returns the voice message playback speed, 1x until changed + static Future getPlaybackSpeed() async { + Box box = await _openPlaybackBox(); + return (box.get(_playbackSpeed) as num?)?.toDouble() ?? 1.0; + } + + /// Sets the voice message playback speed + static Future setPlaybackSpeed(double speed) async { + Box box = await _openPlaybackBox(); + await box.put(_playbackSpeed, speed); + } + + /// Session of an unfinished attachment upload, keyed by `|`. + /// Encrypted like the rest of the cache: it names the attachment in flight. + static const String _pendingUploadsKey = 'pendingUploads'; + + /// The recorded upload session of one attachment, or null. + static Future getPendingUpload(String key) async { + CollectionBox box = await _openBox(_pendingUploadsKey); + return await box.get(key); + } + + /// Records the upload session of one attachment so a retry can resume it. + static Future setPendingUpload(String key, String value) async { + CollectionBox box = await _openBox(_pendingUploadsKey); + await box.put(key, value); + } + + /// Forgets the upload session of one attachment. + static Future removePendingUpload(String key) async { + CollectionBox box = await _openBox(_pendingUploadsKey); + await box.delete(key); + } + + static const String _autoDeleteMediaKey = 'autoDeleteMediaDays'; + static const String _autoDownloadKey = 'autoDownloadPolicy'; + static const String _stickersKey = 'stickers'; + + /// Sticker ids mapped to their encrypted-at-rest file, oldest first. + static Future> getStickers() async { + CollectionBox box = await _openBox(_stickersKey); + final stickers = {}; + for (final entry in (await box.getAllValues()).entries) { + final value = entry.value; + if (value is String) { + stickers[entry.key] = value; + } + } + return stickers; + } + + /// Records one imported sticker. + static Future putSticker(String id, String path) async { + CollectionBox box = await _openBox(_stickersKey); + await box.put(id, path); + } + + /// Forgets one sticker; the caller deletes its file. + static Future deleteSticker(String id) async { + CollectionBox box = await _openBox(_stickersKey); + await box.delete(id); + } + + /// When an incoming attachment is downloaded automatically. Default Wi-Fi: + /// arriving photos must not spend a mobile data plan on their own. + static Future getAutoDownloadPolicy() async { + Box box = await Hive.openBox(_settingsKey); + final stored = box.get(_autoDownloadKey) as String?; + return AutoDownloadPolicy.values.firstWhere( + (policy) => policy.name == stored, + orElse: () => AutoDownloadPolicy.wifi, + ); + } + + /// Sets when attachments are downloaded automatically. + static Future setAutoDownloadPolicy(AutoDownloadPolicy policy) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_autoDownloadKey, policy.name); + } + + /// Days after which this device drops an attachment's local copy, 0 = never. + static Future getAutoDeleteMediaDays() async { + Box box = await Hive.openBox(_settingsKey); + return (box.get(_autoDeleteMediaKey) as num?)?.toInt() ?? 0; + } + + /// Sets how long attachments are kept on this device, 0 = never. + static Future setAutoDeleteMediaDays(int days) async { + Box box = await Hive.openBox(_settingsKey); + await box.put(_autoDeleteMediaKey, days); + } + + /// Every stored message grouped by conversation, from one box scan. Callers + /// that need the whole history (storage usage, media purge) would otherwise + /// reopen the box per conversation. + static Future>> + getAllConversationMessages() async { + Box box = await _openPrivateMessagesBox(); + final result = >{}; + for (final key in box.keys) { + final value = box.get(key); + if (value is! PrivateMessage) { + continue; + } + final conversation = conversationOfKey(key); + if (conversation == null) { + continue; + } + (result[conversation] ??= []).add(value); + } + return result; + } + + /// Opens the message box. One key per message, so a write touches one entry + /// instead of rewriting a whole conversation. static Future _openPrivateMessagesBox() async { return Hive.openBox(_privateMessagesKey); } - /// Add user message to cache + /// Separates the conversation id from the timestamp in a message key. + static const String _messageKeySeparator = '|'; + + /// Key of one stored message: conversation id plus client timestamp. + /// + /// One key per message instead of one list per conversation: adding a message + /// writes a single entry instead of rewriting the whole chat. + static String messageKey(String userId, DateTime sentAt) => + '$userId$_messageKeySeparator${sentAt.microsecondsSinceEpoch}'; + + /// Conversation id of a stored message key, null for legacy keys. + static String? conversationOfKey(dynamic key) { + if (key is! String) { + return null; + } + final index = key.lastIndexOf(_messageKeySeparator); + if (index <= 0) { + return null; + } + return key.substring(0, index); + } + + static int _timestampOfKey(String key) { + final index = key.lastIndexOf(_messageKeySeparator); + return int.tryParse(key.substring(index + 1)) ?? 0; + } + + /// The key of a stored message of [userId], null when it is not on this + /// device. + /// + /// Hive keeps a [DateTime] to the millisecond, so a message read from disk + /// carries a shorter [sentAt] than the microsecond key it was written under + /// (a live one still matches, the box hands back the same instance). Every + /// lookup by instant therefore falls back to the millisecond. + static String? _storedKey(Box box, String userId, DateTime sentAt) { + final exact = messageKey(userId, sentAt); + if (box.containsKey(exact)) { + return exact; + } + final millis = sentAt.millisecondsSinceEpoch; + for (final key in _conversationKeys(box, userId)) { + if (_timestampOfKey(key) ~/ 1000 == millis) { + return key; + } + } + return null; + } + + /// Keys of one conversation, in box order. + static Iterable _conversationKeys(Box box, String userId) { + return box.keys.whereType().where((key) { + final index = key.lastIndexOf(_messageKeySeparator); + return index > 0 && key.substring(0, index) == userId; + }); + } + + /// Older versions stored a whole conversation under the user id. Move those + /// messages into per-message keys once, then drop the old entry. + static Future _migrateLegacyConversation(Box box, String userId) async { + if (!box.containsKey(userId)) { + return; + } + final legacy = box.get(userId); + if (legacy is List) { + for (final entry in legacy) { + if (entry is PrivateMessage) { + await box.put(messageKey(userId, entry.sentAt), entry); + } + } + } + await box.delete(userId); + } + + /// Migrates every legacy conversation entry in the box. + static Future _migrateLegacyMessages(Box box) async { + for (final key in box.keys.whereType().toList()) { + if (conversationOfKey(key) != null) { + continue; + } + await _migrateLegacyConversation(box, key); + } + } + + /// Add messages to a conversation. + /// + /// A message that is already stored is skipped: the server re-sends + /// unacknowledged messages, and the stored copy may already carry the read + /// flag. static Future addPrivateMessages( - int userId, List messages) async { + String userId, List messages) async { Box box = await _openPrivateMessagesBox(); - List chatMessages = await getPrivateMessages(userId); - chatMessages.addAll(messages); - await box.put(userId, chatMessages); + await _migrateLegacyConversation(box, userId); + for (final message in messages) { + final key = messageKey(userId, message.sentAt); + final stored = box.get(key); + if (stored is PrivateMessage) { + // Rows written before the transport key was kept cannot edit their + // caption; the archive page brings the reference back, so fill it in. + if (stored.mediaRefJson == null && message.mediaRefJson != null) { + stored.mediaRefJson = message.mediaRefJson; + await box.put(key, stored); + } + continue; + } + await box.put(key, message); + } } - /// Get user messages and mark them as read - static Future> getPrivateMessages(int userId, + /// Get user messages, oldest first, and mark them as read + static Future> getPrivateMessages(String userId, {bool markAsRead = false}) async { Box box = await _openPrivateMessagesBox(); - List? messages = box.get(userId); - // Mark as read - if (markAsRead && messages != null) { - for (PrivateMessage msg in messages) { - msg.read = true; + await _migrateLegacyConversation(box, userId); + final entries = >[]; + for (final key in _conversationKeys(box, userId)) { + final value = box.get(key); + if (value is PrivateMessage) { + entries.add(MapEntry(key, value)); + } + } + entries.sort((a, b) => a.value.sentAt.compareTo(b.value.sentAt)); + // Mark as read, but only write the messages that actually changed: this + // runs on every chat rebuild. + for (final entry in entries) { + if (markAsRead && !entry.value.read) { + entry.value.read = true; + await box.put(entry.key, entry.value); } - await box.put(userId, messages); } - return messages == null - ? [] - : messages.map((e) => e as PrivateMessage).toList(); + return entries.map((entry) => entry.value).toList(); + } + + /// Delete a single message locally (and its media file). Nothing is sent to + /// the server, so the other side keeps the message. + static Future deletePrivateMessage( + String userId, PrivateMessage message) async { + Box box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + // Removing the key also removes an emptied conversation from the list. + final key = _storedKey(box, userId, message.sentAt); + if (key != null) { + await box.delete(key); + } + await _deletePendingSend(userId, message.sentAt); + for (final path in message.localPaths) { + await MediaUtils.deleteLocalFile(path); + } + } + + /// Deletes one stored message by its timestamp. Used for a server tombstone: + /// the other side deleted the message for everyone. + static Future deletePrivateMessageAt( + String userId, DateTime sentAt) async { + final box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + await _deletePendingSend(userId, sentAt); + return; + } + final value = box.get(key); + if (value is PrivateMessage) { + for (final path in value.localPaths) { + await MediaUtils.deleteLocalFile(path); + } + await setMessagePinned(userId, value.id, null); + } + await _deletePendingSend(userId, sentAt); + await box.delete(key); + } + + /// Deletes every stored message whose disappearing deadline passed, together + /// with its media files. [userId] limits the sweep to one chat. + static Future purgeExpiredMessages({String? userId}) async { + final box = await _openPrivateMessagesBox(); + final now = DateTime.now(); + final expired = {}; + for (final key in box.keys) { + if (key is! String) { + continue; + } + if (userId != null && !key.startsWith('$userId|')) { + continue; + } + final value = box.get(key); + if (value is PrivateMessage && + value.expiresAt != null && + value.expiresAt!.isBefore(now)) { + expired[key] = value; + } + } + for (final entry in expired.entries) { + await box.delete(entry.key); + for (final path in entry.value.localPaths) { + await MediaUtils.deleteLocalFile(path); + } + } + return expired.length; + } + + /// Stores the newest text of an edited message, or drops the edit when the + /// message is not on this device. + static Future markMessageEdited( + String userId, DateTime sentAt, String text, DateTime editedAt) async { + final box = await _openPrivateMessagesBox(); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + return; + } + final value = box.get(key); + if (value is! PrivateMessage) { + return; + } + value.message = text; + value.editedAt = editedAt; + await box.put(key, value); + } + + /// Marks a stored message as opened by the receiver and drops its local + /// media: the one view is spent, so the bytes must not survive on any side. + /// A message that is not on this device is skipped. + static Future markMessageOpened( + String userId, DateTime sentAt, DateTime openedAt) async { + final box = await _openPrivateMessagesBox(); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + return; + } + final value = box.get(key); + if (value is! PrivateMessage) { + return; + } + final paths = value.localPaths; + value.openedAt = openedAt; + value.localPath = null; + // A spent location leaves nothing behind either; the bubble reads the + // opened instant, not the coordinates. The text goes too: for a location it + // is the coordinates, and for media it is the caption, so a chat list + // preview or a notification must not still be able to show it. + value.locationJson = null; + if (value.viewOnce) { + value.message = ''; + } + for (final item in value.album) { + item.localPath = null; + } + await box.put(key, value); + for (final path in paths) { + await MediaUtils.deleteLocalFile(path); + } + } + + /// Marks a stored message as deleted for everyone and drops its content: the + /// text, the media reference and the local file all go, the row stays so the + /// chat keeps a tombstone where the bubble used to be. A message that is not + /// on this device is skipped. + static Future markMessageDeleted( + String userId, DateTime sentAt, DateTime deletedAt) async { + final box = await _openPrivateMessagesBox(); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + return; + } + final value = box.get(key); + if (value is! PrivateMessage) { + return; + } + final paths = value.localPaths; + value + ..deletedAt = deletedAt + ..message = '' + ..mediaId = null + ..mediaTypeStr = null + ..albumJson = null + ..mediaRefJson = null + ..localPath = null + ..viewOnce = false + ..openedAt = null + ..reactions = null + ..locationJson = null + // Nothing is left to read, so a tombstone must not raise an unread badge. + ..read = true; + await box.put(key, value); + for (final path in paths) { + await MediaUtils.deleteLocalFile(path); + } + } + + /// Sets or clears one participant's reaction on a stored message. + static Future setMessageReaction( + String userId, DateTime sentAt, String reactorId, String? emoji) async { + final box = await _openPrivateMessagesBox(); + final key = _storedKey(box, userId, sentAt); + if (key == null) { + return; + } + final value = box.get(key); + if (value is! PrivateMessage) { + return; + } + final reactions = Map.from(value.reactions ?? const {}); + if (emoji == null) { + reactions.remove(reactorId); + } else { + reactions[reactorId] = emoji; + } + value.reactions = reactions.isEmpty ? null : reactions; + await box.put(key, value); } /// Delete user messages - static Future deletePrivateMessagesWithUser(int userId) async { + static Future deletePrivateMessagesWithUser(String userId) async { Box messageBox = await _openPrivateMessagesBox(); - await messageBox.delete(userId); + // Delete on-disk media files for this conversation first. + await _deleteMediaFilesForUser(userId); + for (final key in _conversationKeys(messageBox, userId).toList()) { + await messageBox.delete(key); + } + if (messageBox.containsKey(userId)) { + await messageBox.delete(userId); + } Box userBox = await _openUserBox(); await userBox.delete(userId); await deleteMessageConcept(userId); + // Pin state goes with the conversation. + final conversationsBox = await _openConversationsBox(); + await conversationsBox.delete(userId); + } + + /// Delete the encrypted-at-rest media files of all messages with [userId]. + static Future _deleteMediaFilesForUser(String userId) async { + final messages = await getPrivateMessages(userId); + for (final msg in messages) { + for (final path in msg.localPaths) { + await MediaUtils.deleteLocalFile(path); + } + } + } + + /// Update the local media state of a stored message (download progress). + /// [mediaSize] replaces the reference's encrypted size with the real one. + static Future updatePrivateMessageMedia(String userId, String mediaId, + {String? localPath, int? downloadStatus, int? mediaSize}) async { + Box box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + final keys = _conversationKeys(box, userId).toList(); + if (keys.isEmpty) { + return; + } + final updated = []; + for (final key in keys) { + final dynamic m = box.get(key); + if (m is! PrivateMessage) { + continue; + } + bool changed = false; + final msg = m; + if (msg.mediaId == mediaId) { + if (localPath != null) { + msg.localPath = localPath; + } + if (downloadStatus != null) { + msg.downloadStatus = downloadStatus; + } + if (mediaSize != null) { + msg.mediaSize = mediaSize; + } + changed = true; + } + // Album attachment: update the matching item. + if (msg.isAlbum) { + final items = msg.album; + var itemChanged = false; + for (final item in items) { + if (item.mediaId != mediaId) { + continue; + } + if (localPath != null) { + item.localPath = localPath; + } + if (downloadStatus != null) { + item.status = downloadStatus; + } + if (mediaSize != null) { + item.size = mediaSize; + } + itemChanged = true; + } + if (itemChanged) { + msg.setAlbum(items); + // The message-level flag follows the album, so the bubble can show a + // single state for "still downloading" vs "done". + if (downloadStatus != null) { + final allReady = + items.every((item) => item.status == MediaDownloadStatus.ready); + final anyFailed = items.any((item) => + item.status == MediaDownloadStatus.failed || + item.status == MediaDownloadStatus.expired); + msg.downloadStatus = allReady + ? MediaDownloadStatus.ready + : (anyFailed + ? MediaDownloadStatus.failed + : MediaDownloadStatus.pending); + } + changed = true; + } + } + if (changed) { + updated.add(key); + } + } + for (final key in updated) { + final message = box.get(key); + if (message is PrivateMessage) { + await box.put(key, message); + } + } + } + + /// Apply [update] to the stored copy of [message] and persist it. + /// + /// The message is identified by conversation and client timestamp, the same + /// identity the delete path and the delivery ack use. + static Future updateStoredMessage(String userId, PrivateMessage message, + void Function(PrivateMessage stored) update) async { + Box box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + final key = _storedKey(box, userId, message.sentAt); + if (key == null) { + return; + } + final stored = box.get(key); + if (stored is! PrivateMessage) { + return; + } + update(stored); + await box.put(key, stored); + } + + /// Move a stored message to a fresh client timestamp and key, and return the + /// stored copy. Used when a failed send is retried too long after it was + /// written for the server to accept the original timestamp. + static Future retimestampMessage( + String userId, PrivateMessage message) async { + Box box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + final oldKey = _storedKey(box, userId, message.sentAt); + if (oldKey == null) { + return null; + } + final stored = box.get(oldKey); + if (stored is! PrivateMessage) { + return null; + } + final oldSentAt = stored.sentAt; + // Never collide with the key it already occupies. + do { + stored.sentAt = DateTime.now(); + } while (messageKey(userId, stored.sentAt) == oldKey); + // Hive refuses one object under two keys, so the old entry goes first. + await box.delete(oldKey); + await box.put(messageKey(userId, stored.sentAt), stored); + await _deletePendingSend(userId, oldSentAt); + return stored; + } + + /// Marks the message the server acknowledged as sent. + + /// + /// [receiverId] and [sentAt] are the values the server echoes back; the pair + /// identifies the stored message without keeping a client message id. + static Future markMessageSent(String receiverId, DateTime sentAt, + {String? id}) async { + Box box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, receiverId); + final key = _storedKey(box, receiverId, sentAt); + if (key == null) { + return; + } + final stored = box.get(key); + if (stored is! PrivateMessage) { + return; + } + stored.sendStatus = SendStatus.sent; + // The ack carries the archive id: without it the bubble could only be + // deleted for this device until the next sync handed the id over. + stored.id ??= id; + await box.put(key, stored); + await _deletePendingSend(receiverId, sentAt); + } + + /// Remembers a message that is waiting for its delivery ack, so a reconnect + /// can resend exactly those. + static Future addPendingSend(String receiverId, DateTime sentAt) async { + Box box = await _openPendingSendsBox(); + await box.put(messageKey(receiverId, sentAt), receiverId); + } + + static Future _deletePendingSend( + String receiverId, DateTime sentAt) async { + Box box = await _openPendingSendsBox(); + await box.delete(messageKey(receiverId, sentAt)); + } + + /// Messages still waiting for a delivery ack, grouped by conversation. + static Future>> getPendingSends() async { + Box pending = await _openPendingSendsBox(); + Box box = await _openPrivateMessagesBox(); + final byConversation = >{}; + for (final entry in pending.toMap().entries) { + final key = entry.key; + if (key is! String) { + continue; + } + final receiverId = entry.value as String; + final message = box.get(key); + if (message is! PrivateMessage || + message.sendStatus != SendStatus.sending) { + // Acked, deleted or already given up: forget the marker. + await pending.delete(key); + continue; + } + byConversation.putIfAbsent(receiverId, () => []).add(message); + } + for (final messages in byConversation.values) { + messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); + } + return byConversation; + } + + static Future _openPendingSendsBox() { + return Hive.openBox(_pendingSendsKey); } /// Opens box with users @@ -173,14 +1050,20 @@ class CacheUtils { return Hive.openBox(_userKey); } + /// Every cached contact, for pickers that are not tied to one chat. + static Future> getAllUsers() async { + Box box = await _openUserBox(); + return box.values.whereType().toList(); + } + /// Gets user by ID - static Future getUserById(int userId) async { + static Future getUserById(String userId) async { Box box = await _openUserBox(); return box.get(userId); } // Check if user with ID exists - static Future userExists(int userId) async { + static Future userExists(String userId) async { Box box = await _openUserBox(); return box.containsKey(userId); } @@ -191,19 +1074,424 @@ class CacheUtils { await box.put(user.id, user); } - /// Get Map of all conversations with their last messages + /// Local-only chat list state (pinned, and later archived). Nothing here + /// reaches the server: until F8 syncs it, it is this device's business. + static const String _conversationsKey = 'conversations'; + + static Future _openConversationsBox() async { + return Hive.openBox(_conversationsKey); + } + + /// Serializes the read-modify-write of the per-chat metadata map, so a pin, + /// an archive page and a read cursor cannot overwrite each other. + static Future _metaLock = Future.value(); + + static Future _serializedMeta(Future Function() action) { + final result = _metaLock.then((_) => action()); + _metaLock = result.then((_) {}, onError: (_) {}); + return result; + } + + static Map _metaOf(Box box, String userId) { + final stored = box.get(userId); + return stored is Map ? Map.from(stored) : {}; + } + + /// Whether [userId] is pinned to the top of the chat list. + static Future isConversationPinned(String userId) async { + final box = await _openConversationsBox(); + return _metaOf(box, userId)['pinned'] == true; + } + + /// Pins or unpins a conversation. The entry is dropped once it is empty, so + /// the box only holds chats that differ from the default. + static Future setConversationPinned(String userId, bool pinned) { + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (pinned) { + meta['pinned'] = true; + } else { + meta.remove('pinned'); + } + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + }); + } + + /// Pinned message ids of one chat, with the instant each was pinned. + static Future> getPinnedMessages(String userId) async { + final box = await _openConversationsBox(); + final raw = _metaOf(box, userId)['pins']; + if (raw is! Map) { + return {}; + } + return { + for (final entry in raw.entries) + if (entry.key is String && entry.value is int) + entry.key as String: + DateTime.fromMillisecondsSinceEpoch(entry.value as int), + }; + } + + /// Pins or unpins one message of a chat. Pins are shared between both + /// participants, so this is written from a pin event or a history page. + static Future setMessagePinned( + String userId, String? messageId, DateTime? pinnedAt) { + if (messageId == null || messageId.isEmpty) { + return Future.value(); + } + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + final pins = Map.from( + meta['pins'] is Map ? meta['pins'] as Map : const {}); + if (pinnedAt == null) { + pins.remove(messageId); + } else { + pins[messageId] = pinnedAt.millisecondsSinceEpoch; + } + await _putPins(box, userId, meta, pins); + }); + } + + /// Replaces the pins of a chat with a server answer, so an unpin that happened + /// on another device does not survive on a stale local entry. + static Future replacePinnedMessages( + String userId, Map pins) { + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + await _putPins(box, userId, meta, { + for (final entry in pins.entries) + entry.key: entry.value.millisecondsSinceEpoch, + }); + }); + } + + static Future _putPins( + Box box, String userId, Map meta, Map pins) async { + if (pins.isEmpty) { + meta.remove('pins'); + } else { + meta['pins'] = pins; + } + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + } + + /// Whether this chat sends and shows read receipts. Off by default; one + /// switch governs both directions, so ticks only appear when both sides opted + /// in (a side that is off never publishes its cursor). + static Future isReadReceiptsEnabled(String userId) async { + final box = await _openConversationsBox(); + return _metaOf(box, userId)['readReceipts'] == true; + } + + /// Turns read receipts of one chat on or off. + static Future setReadReceiptsEnabled( + String userId, bool enabled) async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (enabled) { + meta['readReceipts'] = true; + } else { + meta.remove('readReceipts'); + } + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + } + + /// Active disappearing-message timer of one chat in seconds, 0 when off. + /// Both participants store the same value after they agree on it. + static Future getDisappearingSeconds(String userId) async { + final box = await _openConversationsBox(); + final value = _metaOf(box, userId)['disappearing']; + return value is int ? value : 0; + } + + /// Stores the agreed disappearing-message timer of one chat. 0 turns it off. + static Future setDisappearingSeconds(String userId, int seconds) { + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (seconds > 0) { + meta['disappearing'] = seconds; + } else { + meta.remove('disappearing'); + } + await _putMeta(box, userId, meta); + }); + } + + /// Timer the other participant proposed and this device has not answered yet, + /// null when there is none. + static Future getDisappearingProposal(String userId) async { + final box = await _openConversationsBox(); + final value = _metaOf(box, userId)['disappearingProposal']; + return value is int ? value : null; + } + + /// Stores or clears the proposal of the other participant. + static Future setDisappearingProposal(String userId, int? seconds) { + return _serializedMeta(() async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (seconds == null) { + meta.remove('disappearingProposal'); + } else { + meta['disappearingProposal'] = seconds; + } + await _putMeta(box, userId, meta); + }); + } + + static Future _putMeta(Box box, String userId, Map meta) async { + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + } + + /// Instant up to which the other participant has read this chat, null when + /// they never published one. + static Future getPeerReadAt(String userId) async { + final box = await _openConversationsBox(); + final raw = _metaOf(box, userId)['peerReadAt']; + return raw is int ? _decodePeerReadAt(raw) : null; + } + + /// Read cursors of every chat that publishes receipts, keyed by peer id: one + /// box read for the whole chat list instead of one per row. + static Future> peerReadAts() async { + final box = await _openConversationsBox(); + final cursors = {}; + for (final entry in box.toMap().entries) { + final meta = entry.value; + if (meta is! Map || meta['readReceipts'] != true) { + continue; + } + final raw = meta['peerReadAt']; + if (raw is int) { + cursors[entry.key as String] = _decodePeerReadAt(raw); + } + } + return cursors; + } + + /// A cursor carries the sentAt of the newest message the peer read, and + /// sentAt has microseconds: rounding it to milliseconds made the cursor a + /// little older than the message, so the tick only appeared once the peer + /// sent something newer. Values below this bound are the old encoding. + static DateTime _decodePeerReadAt(int raw) { + return raw < 100000000000000 + ? DateTime.fromMillisecondsSinceEpoch(raw) + : DateTime.fromMicrosecondsSinceEpoch(raw); + } + + /// Remembers the peer's read cursor. It only moves forward, so a frame that + /// arrives out of order cannot take the tick back. + static Future setPeerReadAt(String userId, DateTime readAt) { + return _serializedMeta(() async { + final stored = await getPeerReadAt(userId); + if (stored != null && !readAt.isAfter(stored)) { + return; + } + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + meta['peerReadAt'] = readAt.microsecondsSinceEpoch; + await box.put(userId, meta); + }); + } + + /// Instant up to which the account deleted this conversation, null when it + /// never did. Everything at or before it is gone for good. + static Future conversationClearedAt(String userId) async { + final box = await _openConversationsBox(); + final raw = _metaOf(box, userId)['clearedAt']; + return raw is int ? DateTime.fromMillisecondsSinceEpoch(raw) : null; + } + + /// Remembers the server's cut and drops what this device still holds of it. + /// The later of the two instants wins, so a stale page cannot undo a delete. + static Future applyConversationClearedAt( + String userId, DateTime clearedAt) async { + final cut = await _serializedMeta(() async { + final box = await _openConversationsBox(); + final stored = await conversationClearedAt(userId); + final cut = + stored != null && stored.isAfter(clearedAt) ? stored : clearedAt; + final meta = _metaOf(box, userId); + meta['clearedAt'] = cut.millisecondsSinceEpoch; + await box.put(userId, meta); + return cut; + }); + // Outside the lock: purging calls setMessagePinned, which takes it. + await purgeConversationUpTo(userId, cut); + } + + /// Deletes the stored messages sent at or before [cut], media included. + static Future purgeConversationUpTo(String userId, DateTime cut) async { + final box = await _openPrivateMessagesBox(); + await _migrateLegacyConversation(box, userId); + for (final key in _conversationKeys(box, userId).toList()) { + final value = box.get(key); + if (value is! PrivateMessage || value.sentAt.isAfter(cut)) { + continue; + } + for (final path in value.localPaths) { + await MediaUtils.deleteLocalFile(path); + } + await _deletePendingSend(userId, value.sentAt); + await setMessagePinned(userId, value.id, null); + await box.delete(key); + } + } + + /// Ids of the pinned conversations. + static Future> getPinnedConversations() async { + final box = await _openConversationsBox(); + return { + for (final entry in box.toMap().entries) + if (entry.value is Map && (entry.value as Map)['pinned'] == true) + entry.key as String, + }; + } + + /// Unread incoming messages per conversation, for the chat list badge. + static Future> getUnreadCounts() async { + final box = await _openPrivateMessagesBox(); + final counts = {}; + for (final key in box.keys.whereType()) { + final userId = conversationOfKey(key); + if (userId == null) { + continue; + } + final value = box.get(key); + if (value is PrivateMessage && !value.read) { + counts[userId] = (counts[userId] ?? 0) + 1; + } + } + return counts; + } + + /// Searches the stored conversations, newest hit first. + /// + /// The message box holds decrypted text, so this is a local scan: the query + /// never reaches the server. + static Future> searchMessages( + MessageSearchQuery query) async { + final box = await _openPrivateMessagesBox(); + final hits = []; + for (final key in box.keys.whereType()) { + final conversationId = conversationOfKey(key); + if (conversationId == null) { + continue; + } + final value = box.get(key); + if (value is PrivateMessage) { + hits.add(MessageHit(conversationId, value)); + } + } + return filterMessages(hits, query); + } + + /// Whether the attachment [mediaId] already sits on this device, either as a + /// single attachment or as one item of an album. + /// + /// The server deletes its copy once delivery is confirmed, so downloading a + /// media that is already here can only fail with 404 and would overwrite a + /// healthy attachment with an error state. A history page or a sync + /// redelivers messages that are already stored, which is exactly when this + /// check matters. + static Future hasMediaLocally(String userId, String mediaId) async { + final box = await _openPrivateMessagesBox(); + for (final key in _conversationKeys(box, userId)) { + final value = box.get(key); + if (value is! PrivateMessage) { + continue; + } + if (value.mediaId == mediaId && value.localPath != null) { + return true; + } + for (final item in value.album) { + if (item.mediaId == mediaId && item.localPath != null) { + return true; + } + } + } + return false; + } + + /// Oldest unread message of a conversation: the anchor of the "new messages" + /// divider, taken before the chat marks everything read. + static Future firstUnreadSentAt(String userId) async { + final box = await _openPrivateMessagesBox(); + DateTime? first; + for (final key in _conversationKeys(box, userId)) { + final value = box.get(key); + if (value is! PrivateMessage || value.read) { + continue; + } + if (first == null || value.sentAt.isBefore(first)) { + first = value.sentAt; + } + } + return first; + } + + /// Get Map of all conversations with their last messages. + /// + /// Only the newest message of each conversation is deserialized, so the list + /// does not pay for the whole history. Pinned conversations come first. static Future> getLatestPrivateMessages() async { Box box = await _openPrivateMessagesBox(); + await _migrateLegacyMessages(box); + + final newestKey = {}; + final newestTimestamp = {}; + for (final key in box.keys.whereType()) { + final userId = conversationOfKey(key); + if (userId == null) { + continue; + } + final timestamp = _timestampOfKey(key); + if (timestamp > (newestTimestamp[userId] ?? -1)) { + newestTimestamp[userId] = timestamp; + newestKey[userId] = key; + } + } + Map conversations = {}; - for (var entry in box.toMap().entries) { - User? user = await getUserById(entry.key as int); - List messages = entry.value; - conversations[user ?? User(entry.key as int, '', '', false)] = - messages.last as PrivateMessage; + for (final entry in newestKey.entries) { + final message = box.get(entry.value); + if (message is! PrivateMessage) { + continue; + } + User? user = await getUserById(entry.key); + conversations[user ?? User(entry.key, '', '', false)] = message; } - // Sort conversations by last message date + // Pinned conversations first, then by last message date + final pinnedIds = await getPinnedConversations(); var sortedEntries = conversations.entries.toList() - ..sort((a, b) => b.value.receivedAt.compareTo(a.value.receivedAt)); + ..sort((a, b) { + final aPinned = pinnedIds.contains(a.key.id); + final bPinned = pinnedIds.contains(b.key.id); + if (aPinned != bPinned) { + return aPinned ? -1 : 1; + } + return b.value.receivedAt.compareTo(a.value.receivedAt); + }); return Map.fromEntries(sortedEntries); } @@ -212,9 +1500,15 @@ class CacheUtils { Box messageBox = await _openPrivateMessagesBox(); Box userBox = await _openUserBox(); Box conceptBox = await _openMessageConceptBox(); + Box pendingBox = await _openPendingSendsBox(); + Box conversationsBox = await _openConversationsBox(); await userBox.clear(); await messageBox.clear(); await conceptBox.clear(); + await pendingBox.clear(); + await conversationsBox.clear(); + // Remove every locally stored media file. + await MediaUtils.clearMediaDir(); } /// Opens box with message concepts @@ -223,20 +1517,20 @@ class CacheUtils { } /// Sets message concept for user - static Future setMessageConcept(int userId, String message) async { + static Future setMessageConcept(String userId, String message) async { Box box = await _openMessageConceptBox(); await box.put(userId, message); } /// Return message concept for user - static Future getMessageConcept(int userId) async { + static Future getMessageConcept(String userId) async { Box box = await _openMessageConceptBox(); String? value = await box.get(userId); return value; } /// Delete message concept if it exists - static Future deleteMessageConcept(int userId) async { + static Future deleteMessageConcept(String userId) async { Box box = await _openMessageConceptBox(); await box.delete(userId); } diff --git a/lib/utils/chat_date.dart b/lib/utils/chat_date.dart new file mode 100644 index 0000000..768a8e0 --- /dev/null +++ b/lib/utils/chat_date.dart @@ -0,0 +1,36 @@ +import 'package:easy_localization/easy_localization.dart'; + +/// Date label of a conversation row and of a search result: today and +/// yesterday by name, then the weekday for the last week, then the date. +/// +/// [todayLabel] and [yesterdayLabel] are passed in because a pure helper +/// cannot reach the localization; [now] is injectable for tests. Patterns and +/// month names follow `Intl.defaultLocale`, which the app keeps in sync with +/// the selected language. +String chatDateLabel( + DateTime when, { + required String todayLabel, + required String yesterdayLabel, + DateTime? now, +}) { + final current = (now ?? DateTime.now()).toLocal(); + final date = when.toLocal(); + final time = DateFormat.Hm().format(date); + final days = DateTime(date.year, date.month, date.day) + .difference(DateTime(current.year, current.month, current.day)) + .inDays; + + if (days == 0) { + return '$todayLabel $time'; + } + if (days == -1) { + return '$yesterdayLabel $time'; + } + if (days >= -7) { + return '${DateFormat.EEEE().format(date)} $time'; + } + if (date.year == current.year) { + return DateFormat.MMMMd().format(date); + } + return DateFormat.yMMMMd().format(date); +} diff --git a/lib/utils/chat_scroll.dart b/lib/utils/chat_scroll.dart new file mode 100644 index 0000000..d4faa2d --- /dev/null +++ b/lib/utils/chat_scroll.dart @@ -0,0 +1,23 @@ +/// How many of the newest messages must be rendered for the message at +/// [index] to exist in the list at all. +/// +/// The rendered window is a slice of the tail, so reaching an older message +/// always means widening that slice. [margin] leaves a few messages above the +/// target, so it does not sit alone on the first line. +int windowForAddition(int messageCount, int index, {int margin = 5}) { + final needed = messageCount - index + margin; + if (needed < 1) { + return 1; + } + return needed > messageCount ? messageCount : needed; +} + +/// Next scroll offset while walking back towards newer messages that are not +/// built yet: one viewport at a time, never past the newest message. +double nextJumpOffset(double pixels, double viewport) { + final next = pixels - viewport; + if (next < 0) { + return 0; + } + return next > pixels ? pixels : next; +} diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart new file mode 100644 index 0000000..9e173c5 --- /dev/null +++ b/lib/utils/chat_sender.dart @@ -0,0 +1,672 @@ +import 'dart:convert'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; +import 'package:shept_websocket_client_dart/models/new_private_message.dart'; +import 'package:shept_websocket_client_dart/models/ws_message.dart'; + +import '../models/private_message.dart'; +import '../models/user.dart'; +import 'cache_utils.dart'; +import 'crypto_utils.dart'; +import 'media_upload.dart'; +import 'media_utils.dart'; +import 'message_notifier.dart'; +import 'singleton.dart'; +import 'text_envelope.dart'; +import 'utils.dart'; + +/// One attachment of an outgoing album (or a single media message). +class OutgoingAttachment { + final MediaType type; + final Uint8List bytes; + final int? width; + final int? height; + final int? durationMs; + final String? fileName; + + const OutgoingAttachment({ + required this.type, + required this.bytes, + this.width, + this.height, + this.durationMs, + this.fileName, + }); +} + +/// Sends messages to an arbitrary recipient. Shared by the chat page and the +/// forward page so both use one encrypted, persisted send path. +/// +/// The bubble is stored as `sending` before anything goes out and flipped to +/// `sent` only when the server acknowledges the message. Without an ack the +/// message stays pending and is resent on the next connect, so a lost frame is +/// visible instead of silent. +class ChatSender { + /// Transport references of media messages sent in this session, keyed by + /// [CacheUtils.messageKey]. Needed to resend a media message whose ack was + /// lost; the transport key is never persisted, so after a restart such a + /// message cannot be resent. + /// + /// shortcut: resending media only works in the session that uploaded it, + /// upgrade by persisting the transport key inside the encrypted profile box. + static final Map> _outgoingReferences = {}; + + /// Send a text message to [recipient], optionally quoting [reply] or marked + /// as forwarded. + static Future sendText(User recipient, String text, + {ReplyRef? reply, bool forwarded = false}) async { + final now = DateTime.now(); + final ttl = await _ttlFor(recipient); + final message = PrivateMessage( + Singleton().profile.user.id, text, now, now, true, + sendStatus: SendStatus.sending, + forwarded: forwarded, + expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null) + ..setReplyTo(reply); + try { + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); + } + await _sendText(recipient, message, ttl: ttl); + // No ack yet: the message stays `sending` until the server confirms. + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(recipient.id, message); + } + } + + /// Send [bytes] as a media attachment of [type] to [recipient]. The caller + /// supplies the probed metadata so `null` there is meaningful. + static Future sendMedia(User recipient, MediaType type, Uint8List bytes, + {String caption = '', + int? width, + int? height, + int? durationMs, + String? fileName, + List? waveform, + bool videoNote = false, + bool forwarded = false, + bool viewOnce = false}) async { + if (!MediaUtils.uploadFits(bytes.length)) { + _toastTooLarge(); + return false; + } + // Store the original media encrypted-at-rest first, so the bubble can show + // the content while the upload is still running. + final localPath = await MediaUtils.encryptAtRest(bytes); + final now = DateTime.now(); + // A view-once attachment lives a day whatever the chat timer says; anything + // else follows the agreed timer. + final ttl = viewOnce ? viewOnceTtlSeconds : await _ttlFor(recipient); + final message = PrivateMessage( + Singleton().profile.user.id, + caption, + now, + now, + true, + mediaTypeStr: type.name, + localPath: localPath, + mediaSize: bytes.length, + width: width, + height: height, + durationMs: durationMs, + downloadStatus: MediaDownloadStatus.ready, + fileName: fileName, + sendStatus: SendStatus.sending, + forwarded: forwarded, + viewOnce: viewOnce, + expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null, + ); + try { + await _persist(recipient, [message]); + if (videoNote) { + // The reference only exists after the upload, but the bubble has to know + // it is a round note from the first frame: mark it now, the finished + // reference overwrites this below. + await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { + stored.mediaRefJson = jsonEncode({'videoNote': true}); + }); + } + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); + } + final reference = await _uploadReference(recipient, type, bytes, + messageKey: CacheUtils.messageKey(recipient.id, message.sentAt), + width: width, + height: height, + durationMs: durationMs, + fileName: fileName, + waveform: waveform, + videoNote: videoNote); + if (reference == null) { + return await _fail(recipient.id, message); + } + _outgoingReferences[CacheUtils.messageKey(recipient.id, message.sentAt)] = + [reference]; + final envelope = MediaUtils.buildMediaEnvelope(reference, caption, + forwarded: forwarded, viewOnce: viewOnce); + await _sendEnvelope(recipient, envelope, message.sentAt, ttlSeconds: ttl); + await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { + stored.mediaId = reference.mediaId; + // Keep the reference (with its transport key) so the caption can be + // edited later without the original upload. + stored.mediaRefJson = jsonEncode(reference.toJson()); + // The sender never keeps the content of a view-once attachment: one + // open belongs to the recipient, so the local copy goes right away. + if (viewOnce) { + stored.localPath = null; + } + }); + if (viewOnce) { + await MediaUtils.deleteLocalFile(localPath); + } + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(recipient.id, message); + } + } + + /// Send several attachments as one album message: one bubble, one encrypted + /// envelope carrying all references, one WebSocket message. + static Future sendAlbum( + User recipient, List attachments, + {String caption = '', + bool forwarded = false, + bool viewOnce = false}) async { + if (attachments.isEmpty) { + return false; + } + for (final attachment in attachments) { + if (!MediaUtils.uploadFits(attachment.bytes.length)) { + _toastTooLarge(); + return false; + } + } + + // Local copies first: the album bubble is visible while uploading. + final localPaths = []; + for (final attachment in attachments) { + localPaths.add(await MediaUtils.encryptAtRest(attachment.bytes)); + } + final now = DateTime.now(); + // A view-once album follows the same one-day life as a single attachment. + final ttl = viewOnce ? viewOnceTtlSeconds : await _ttlFor(recipient); + final message = PrivateMessage( + Singleton().profile.user.id, + caption, + now, + now, + true, + downloadStatus: MediaDownloadStatus.ready, + sendStatus: SendStatus.sending, + forwarded: forwarded, + viewOnce: viewOnce, + expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null, + ); + message.setAlbum([ + for (var i = 0; i < attachments.length; i++) + AlbumItem( + mediaId: '', + type: attachments[i].type.name, + size: attachments[i].bytes.length, + width: attachments[i].width, + height: attachments[i].height, + durationMs: attachments[i].durationMs, + fileName: attachments[i].fileName, + localPath: localPaths[i], + status: MediaDownloadStatus.ready, + ) + ]); + + try { + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); + } + + // The server takes one file per request, so the album is N uploads. + final references = []; + final messageKey = CacheUtils.messageKey(recipient.id, message.sentAt); + for (var i = 0; i < attachments.length; i++) { + final attachment = attachments[i]; + final reference = await _uploadReference( + recipient, attachment.type, attachment.bytes, + messageKey: messageKey, + index: i, + width: attachment.width, + height: attachment.height, + durationMs: attachment.durationMs, + fileName: attachment.fileName); + if (reference == null) { + return await _fail(recipient.id, message); + } + references.add(reference); + } + + _outgoingReferences[CacheUtils.messageKey(recipient.id, message.sentAt)] = + references; + final envelope = MediaUtils.buildAlbumEnvelope(references, caption, + forwarded: forwarded, viewOnce: viewOnce); + await _sendEnvelope(recipient, envelope, message.sentAt, ttlSeconds: ttl); + await CacheUtils.updateStoredMessage(recipient.id, message, (stored) { + final items = stored.album; + for (var i = 0; i < items.length && i < references.length; i++) { + items[i].mediaId = references[i].mediaId; + items[i].keyB64 = base64Encode(references[i].key); + // A view-once album keeps no copy on the sending side. + if (viewOnce) { + items[i].localPath = null; + } + } + stored.setAlbum(items); + }); + if (viewOnce) { + for (final path in localPaths) { + await MediaUtils.deleteLocalFile(path); + } + } + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(recipient.id, message); + } + } + + /// Media references of an already stored message, for re-encrypting it with a + /// new caption. Prefers what the row kept, then the upload cache, and only + /// re-uploads the local copies when neither has it (a message from a build + /// that did not keep the key yet). + static Future?> mediaReferencesFor( + User recipient, PrivateMessage message) async { + final kept = message.mediaReferences; + if (kept != null && kept.isNotEmpty) { + return kept; + } + final cached = _outgoingReferences[ + CacheUtils.messageKey(recipient.id, message.sentAt)]; + if (cached != null && cached.isNotEmpty) { + return cached; + } + return _uploadLocalCopies(recipient, message); + } + + /// Resend every message that never received a delivery ack. + /// + /// Called after a WebSocket reconnect: the server deduplicates by + /// (receiver, sentAt), so a message that did arrive is not delivered twice. + static Future resendPending() async { + if (!Singleton().wsClient.isConnected) { + return; + } + final pending = await CacheUtils.getPendingSends(); + for (final entry in pending.entries) { + final recipient = await CacheUtils.getUserById(entry.key); + if (recipient == null || recipient.publicKey.isEmpty) { + continue; + } + for (final message in entry.value) { + try { + final fresh = await _withAcceptedSentAt(entry.key, message); + if (fresh != null) { + await _sendStored(recipient, fresh); + } + } catch (e) { + if (kDebugMode) { + debugPrint('resend failed: $e'); + } + } + } + } + } + + /// Resend a single stored message after its send failed (bubble long-press). + /// + /// The original timestamp is kept while the server still accepts it, so the + /// server deduplicates against the failed attempt and the bubble stays put. + static Future resend(String receiverId, PrivateMessage message) async { + final recipient = await CacheUtils.getUserById(receiverId); + if (recipient == null || recipient.publicKey.isEmpty) { + Fluttertoast.showToast( + msg: 'userNotFound'.tr(), backgroundColor: Colors.red); + return false; + } + final fresh = await _withAcceptedSentAt(receiverId, message); + if (fresh == null) { + return false; + } + await CacheUtils.updateStoredMessage(receiverId, fresh, (stored) { + stored.sendStatus = SendStatus.sending; + }); + fresh.sendStatus = SendStatus.sending; + await CacheUtils.addPendingSend(receiverId, fresh.sentAt); + MessageNotifier().notify(); + try { + if (!await _ensureConnected()) { + return await _fail(receiverId, fresh); + } + await _sendStored(recipient, fresh); + // No ack yet: the message stays `sending` until the server confirms. + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(receiverId, fresh); + } + } + + /// How old a client timestamp may be and still be accepted by the server + /// (`models.MaxSentAtSkew`, minus a minute for clock drift between the two). + static const Duration _maxSentAtAge = Duration(minutes: 4); + + /// The stored message to send again, with a timestamp the server will take. + /// + /// Returns null when the message is gone. A timestamp older than the server + /// accepts is replaced with now, which moves the bubble to the end of the + /// chat. + /// + /// shortcut: a retry that late cannot dedupe against the first attempt, so a + /// message that did arrive with a lost ack is delivered twice; upgrade by + /// keeping the server-side dedup key separate from the display time. + static Future _withAcceptedSentAt( + String receiverId, PrivateMessage message) async { + if (DateTime.now().difference(message.sentAt) <= _maxSentAtAge) { + return message; + } + final moved = await CacheUtils.retimestampMessage(receiverId, message); + if (moved != null) { + // The old marker is gone with the old key; keep the new one watchable. + await CacheUtils.addPendingSend(receiverId, moved.sentAt); + } + return moved; + } + + /// Mark a message as sent after the server acknowledged it. + static Future confirmSent(String receiverId, DateTime sentAt, + {String? id}) async { + await CacheUtils.markMessageSent(receiverId, sentAt, id: id); + _outgoingReferences.remove(CacheUtils.messageKey(receiverId, sentAt)); + MessageNotifier().notify(); + } + + /// Hand an already stored message to the WebSocket again. + /// + /// Media needs its transport references; when this session no longer holds + /// them (an offline send, or a restart), the copies on disk are re-encrypted + /// and uploaded once more. + static Future _sendStored( + User recipient, PrivateMessage message) async { + if (!message.isMedia) { + await _sendText(recipient, message); + return; + } + final key = CacheUtils.messageKey(recipient.id, message.sentAt); + final references = _outgoingReferences[key] ?? + await _uploadLocalCopies(recipient, message); + if (references == null || references.isEmpty) { + throw Exception('mediaUploadFailed'.tr()); + } + _outgoingReferences[key] = references; + final envelope = message.isAlbum + ? MediaUtils.buildAlbumEnvelope(references, message.message, + forwarded: message.forwarded) + : MediaUtils.buildMediaEnvelope(references.first, message.message, + forwarded: message.forwarded); + await _sendEnvelope(recipient, envelope, message.sentAt); + } + + /// Re-upload the attachments stored on this device. Null when a local copy + /// is missing or the upload failed. + static Future?> _uploadLocalCopies( + User recipient, PrivateMessage message) async { + final messageKey = CacheUtils.messageKey(recipient.id, message.sentAt); + Future upload(String? path, MediaType? type, int index, + {int? width, + int? height, + int? durationMs, + String? fileName, + List? waveform}) async { + if (path == null || type == null) { + return null; + } + final bytes = await MediaUtils.decryptAtRest(path); + if (!MediaUtils.uploadFits(bytes.length)) { + _toastTooLarge(); + return null; + } + return _uploadReference(recipient, type, bytes, + messageKey: messageKey, + index: index, + width: width, + height: height, + durationMs: durationMs, + fileName: fileName, + waveform: waveform, + // Only a single video is ever a note; the stored reference says so. + videoNote: message.mediaReferences?.first.videoNote ?? false); + } + + final references = []; + if (message.isAlbum) { + for (var i = 0; i < message.album.length; i++) { + final item = message.album[i]; + final reference = await upload(item.localPath, item.mediaType, i, + width: item.width, + height: item.height, + durationMs: item.durationMs, + fileName: item.fileName); + if (reference == null) { + return null; + } + references.add(reference); + } + } else { + final reference = await upload(message.localPath, message.mediaType, 0, + width: message.width, + height: message.height, + durationMs: message.durationMs, + fileName: message.fileName, + // A voice message keeps its recorded shape across a retry. + waveform: message.mediaReferences?.first.waveform); + if (reference == null) { + return null; + } + references.add(reference); + } + return references; + } + + /// Encrypt [message] for [recipient] and hand it to the WebSocket. The + /// original timestamp is kept so a resend maps onto the same server entry. + static Future _sendText(User recipient, PrivateMessage message, + {int ttl = 0, Uint8List? plaintextOverride}) async { + // A reply needs the quote next to the body; everything else stays raw text + // so an older client can still read it. + final reply = message.replyTo; + final plaintext = plaintextOverride ?? + (reply == null && !message.forwarded + ? utf8.encode(message.message) + : buildTextEnvelope(message.message, reply, + forwarded: message.forwarded)); + final data = await CryptoUtils.encryptMessageData( + plaintext, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( + recipient.id, + data['encryptedData']!, + data['encryptedKey']!, + data['nonce']!, + data['mac']!, + sentAt: message.sentAt, + ttlSeconds: ttl > 0 ? ttl : null))); + } + + /// Upload one attachment and build its reference. + /// + /// Returns null when the upload failed. The recorded session is kept, so the + /// retry of that message continues where the connection broke instead of + /// starting from zero. + static Future _uploadReference( + User recipient, + MediaType type, + Uint8List bytes, { + required String messageKey, + int index = 0, + int? width, + int? height, + int? durationMs, + String? fileName, + List? waveform, + bool videoNote = false, + }) async { + try { + final (mediaId, transport) = await MediaUploader.upload( + bytes, + receiverId: recipient.id, + messageKey: messageKey, + index: index, + ); + return MediaReference( + mediaId, + transport.key, + type, + transport.blob.length, + width: width, + height: height, + durationMs: durationMs, + fileName: fileName, + waveform: waveform, + videoNote: videoNote, + ); + } catch (e) { + if (kDebugMode) { + debugPrint('media upload failed: $e'); + } + Fluttertoast.showToast( + msg: 'mediaUploadFailed'.tr(), backgroundColor: Colors.red); + return null; + } + } + + /// E2E-encrypt [envelope] for [recipient] and hand it to the WebSocket. + static Future _sendEnvelope( + User recipient, Uint8List envelope, DateTime sentAt, + {int ttlSeconds = 0}) async { + final data = await CryptoUtils.encryptMessageData( + envelope, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( + recipient.id, + data['encryptedData']!, + data['encryptedKey']!, + data['nonce']!, + data['mac']!, + sentAt: sentAt, + ttlSeconds: ttlSeconds > 0 ? ttlSeconds : null))); + } + + /// Life of a view-once attachment: one day, whether or not the chat has a + /// disappearing timer. + static const int viewOnceTtlSeconds = 86400; + + /// Sends a static location: an ordinary text message whose envelope also + /// carries the coordinates. The server sees only the ciphertext. + static Future sendLocation(User recipient, double lat, double lng, + {double? accuracy, String? label, bool viewOnce = false}) async { + final now = DateTime.now(); + final ttl = viewOnce ? viewOnceTtlSeconds : await _ttlFor(recipient); + final location = LocationRef(lat, lng, accuracy: accuracy, label: label); + final message = PrivateMessage( + Singleton().profile.user.id, location.body, now, now, true, + sendStatus: SendStatus.sending, + locationJson: jsonEncode(location.toJson()), + viewOnce: viewOnce, + expiresAt: ttl > 0 ? now.add(Duration(seconds: ttl)) : null); + try { + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); + } + await _sendText(recipient, message, + ttl: ttl, + plaintextOverride: buildTextEnvelope(location.body, null, + location: location, viewOnce: viewOnce)); + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(recipient.id, message); + } + } + + /// The agreed disappearing timer of one chat in seconds, 0 when off. + static Future _ttlFor(User recipient) => + CacheUtils.getDisappearingSeconds(recipient.id); + + /// Sends one step of the disappearing-message agreement. The message is + /// archived and encrypted like any other, so the other device and a device + /// that syncs later all see the same state. + static Future sendSystem( + User recipient, String state, int seconds) async { + final now = DateTime.now(); + final message = PrivateMessage( + Singleton().profile.user.id, '', now, now, true, + sendStatus: SendStatus.sending, + systemState: state, + systemSeconds: seconds); + try { + await _persist(recipient, [message]); + if (!await _ensureConnected()) { + return await _fail(recipient.id, message); + } + await _sendEnvelope(recipient, buildSystemEnvelope(state, seconds), now); + return true; + } catch (e) { + Fluttertoast.showToast(msg: e.toString(), backgroundColor: Colors.red); + return await _fail(recipient.id, message); + } + } + + /// Connect the WebSocket if needed; toasts and reports false when offline. + static Future _ensureConnected() async { + await Utils.wsConnect(); + if (Singleton().wsClient.isConnected) { + return true; + } + Fluttertoast.showToast(msg: 'wsOffline'.tr(), backgroundColor: Colors.red); + return false; + } + + static void _toastTooLarge() { + Fluttertoast.showToast( + msg: + '${'fileTooLarge'.tr()} ${MediaUtils.formatBytes(MediaUtils.maxUploadBytes)}', + backgroundColor: Colors.red); + } + + /// Mark a persisted message as failed and report the failure. + static Future _fail(String userId, PrivateMessage message) async { + await CacheUtils.updateStoredMessage(userId, message, (stored) { + stored.sendStatus = SendStatus.failed; + }); + return false; + } + + /// Store the recipient and the sent message in the local cache. + static Future _persist( + User recipient, List messages) async { + if (recipient.publicKey != '' && + recipient.username != '' && + !recipient.isInBox) { + await CacheUtils.addUser(recipient); + } + await MessageNotifier().addMessages(recipient.id, messages); + for (final message in messages) { + await CacheUtils.addPendingSend(recipient.id, message.sentAt); + } + } +} diff --git a/lib/utils/crypto_utils.dart b/lib/utils/crypto_utils.dart index 6c0b25f..7fa01a3 100644 --- a/lib/utils/crypto_utils.dart +++ b/lib/utils/crypto_utils.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:math'; +import 'package:basic_utils/basic_utils.dart' as bu; import 'package:crypto/crypto.dart'; import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart' as djwt; import 'package:flutter/foundation.dart'; @@ -21,26 +22,40 @@ class CryptoUtils { static Future> getRSAKeyPair() async { final secureRandom = FortunaRandom(); + // Seed from the platform CSPRNG: a constant seed would make every keypair + // predictable and identical across installs. secureRandom.seed(KeyParameter( - Uint8List.fromList(List.generate(32, (i) => i)), + Uint8List.fromList( + List.generate(32, (_) => Random.secure().nextInt(256))), )); // Seed with random bytes return await compute(_getRSAKeyPair, secureRandom); } /// PBKDF2 password derivation (https://pub.dev/documentation/cryptography/latest/cryptography/Pbkdf2-class.html) - static Future> pbkdf2(String password) async { + static Future> pbkdf2(String password, List salt) async { final pbkdf2 = cryptography.Pbkdf2( macAlgorithm: cryptography.Hmac.sha256(), iterations: 310000, bits: 256, ); - List salt = md5.convert(utf8.encode(password)).bytes; // TODO Secure salt? final key = await pbkdf2.deriveKeyFromPassword(password: password, nonce: salt); return await key.extractBytes(); } + /// Legacy derivation with the old `md5(password)` salt. Only used to open + /// data created before salts became random, then migrated away from. + static Future> legacyPbkdf2(String password) { + return pbkdf2(password, md5.convert(utf8.encode(password)).bytes); + } + + /// Random 32-byte PBKDF2 salt. + static List generateSalt() { + final random = Random.secure(); + return List.generate(32, (_) => random.nextInt(256)); + } + /// Encrypt by RSA public key asynchronously. static Future rsaEncrypt( Uint8List message, RSAPublicKey publicKey) async { @@ -73,18 +88,75 @@ class CryptoUtils { return cipher.process(data['message']); } - /// Generates JWT token valid for 5 seconds asynchronously. - static Future generateRsaJwt( - int userId, RSAPrivateKey privateKey) async { - return await compute( - _generateRsaJwt, {'userId': userId, 'privateKey': privateKey}); + /// Decrypts a batch of hybrid-encrypted messages inside one isolate. + /// + /// A burst of incoming messages used to cost one RSA key parse and one + /// isolate spawn per message; here it costs one of each per batch. + /// Messages that fail to decrypt come back as null. + static Future> decryptMessageBatch( + List> messages, String privateKeyPem) async { + return compute( + _decryptMessageBatch, {'messages': messages, 'pem': privateKeyPem}); + } + + static Future> _decryptMessageBatch( + Map data) async { + final privateKey = + bu.CryptoUtils.rsaPrivateKeyFromPem(data['pem'] as String); + final messages = data['messages'] as List; + final aesAlgorithm = cryptography.AesGcm.with256bits(); + final decrypted = []; + for (final entry in messages) { + final message = (entry as Map).cast(); + try { + final cipher = PKCS1Encoding(RSAEngine()) + ..init(false, PrivateKeyParameter(privateKey)); + final aesKeyBytes = cipher.process(message['key'] as Uint8List); + final plainText = await aesAlgorithm.decrypt( + cryptography.SecretBox( + message['data'] as Uint8List, + nonce: message['nonce'] as Uint8List, + mac: cryptography.Mac(message['mac'] as Uint8List), + ), + secretKey: cryptography.SecretKey(aesKeyBytes), + ); + decrypted.add(Uint8List.fromList(plainText)); + } catch (_) { + decrypted.add(null); + } + } + return decrypted; + } + + /// Generates the login JWT, valid for 5 seconds, asynchronously. + /// + /// [nonce] is the one-time challenge from the server: it is signed into the + /// token and spent on use, so a captured token cannot be replayed. + /// + /// [deviceId] is signed too (`did`), so the request body cannot name a + /// different device than the one that proved the account key. + static Future generateRsaJwt(String userId, RSAPrivateKey privateKey, + {required String nonce, required String deviceId}) async { + return await compute(_generateRsaJwt, { + 'userId': userId, + 'privateKey': privateKey, + 'nonce': nonce, + 'deviceId': deviceId, + }); } /// Generate JWT token synchronously. static String _generateRsaJwt(Map data) { - final jwt = djwt.JWT({'sub': data['userId']}); + final jwt = djwt.JWT({ + 'sub': data['userId'], + 'did': data['deviceId'], + 'nonce': data['nonce'], + }); Duration expiresIn = Duration(seconds: 5); - Duration notBefore = Duration.zero; + // dart_jsonwebtoken writes `nbf = now + notBefore`, so a negative value + // backdates the token and a server clock a few seconds behind the phone no + // longer rejects it as "not valid yet". + Duration notBefore = const Duration(seconds: -30); return jwt.sign(djwt.RSAPrivateKey.raw(data['privateKey']), algorithm: djwt.JWTAlgorithm.RS256, expiresIn: expiresIn, @@ -103,10 +175,11 @@ class CryptoUtils { // Generate a random nonce (initialization vector) final secureRandom = FortunaRandom(); secureRandom.seed(KeyParameter( - Uint8List.fromList(List.generate(32, (i) => Random.secure().nextInt(256))), + Uint8List.fromList( + List.generate(32, (i) => Random.secure().nextInt(256))), )); - final nonce = Uint8List.fromList( - List.generate(12, (_) => secureRandom.nextUint8())); + final nonce = + Uint8List.fromList(List.generate(12, (_) => secureRandom.nextUint8())); // Encrypt data using AES-GCM final secretBox = await aesAlgorithm.encrypt( diff --git a/lib/utils/dialog_utils.dart b/lib/utils/dialog_utils.dart index a05b6cf..24be7d3 100644 --- a/lib/utils/dialog_utils.dart +++ b/lib/utils/dialog_utils.dart @@ -6,7 +6,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_colorpicker/flutter_colorpicker.dart'; import 'package:provider/provider.dart'; import '../utils/cache_utils.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import '../widgets/theme_palette.dart'; +import 'color_utils.dart'; import 'singleton.dart'; import 'theme_notifier.dart'; import 'utils.dart'; @@ -88,99 +90,97 @@ class DialogUtils { /// Returns theme dialog static Widget themeDialog(BuildContext context) { /// Change theme via notifier - changeTheme() { + void changeTheme() { Provider.of(context, listen: false) .changeTheme(Singleton().appTheme); } + /// Applies a change live: the preview and the page behind the dialog move + /// with it, so there is no apply button to forget. + Future apply(VoidCallback mutate) async { + mutate(); + changeTheme(); + await CacheUtils.setTheme(Singleton().appTheme); + } + return StatefulBuilder(builder: (context, setState) { - /// Open color picker dialog/// Open color picker dialog + /// Open the color wheel; the palette covers the common cases. Future openColorPickerDialog() async { - await showDialog( - context: context, - builder: (context) => - colorPickerDialog(context, Singleton().appTheme.color)) - .then((value) async { - if (value != null) { - setState(() { - Singleton().appTheme.color = value; - changeTheme(); - }); - await CacheUtils.setTheme(Singleton().appTheme); - } - }); + final value = await showDialog( + context: context, + builder: (context) => + colorPickerDialog(context, Singleton().appTheme.color)); + if (value != null) { + setState(() { + Singleton().appTheme.color = value; + }); + await apply(() {}); + } } + final theme = Singleton().appTheme; + final seed = theme.color; + return BackdropFilter( filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), child: AlertDialog( + // The dialog had a quarter of the screen; a seed palette and a + // preview need the width, and 380 keeps it readable on a tablet. + constraints: const BoxConstraints(maxWidth: 380), title: Text('themeSettings'.tr()), content: SizedBox( - width: MediaQuery.of(context).size.width / 4, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Theme mode - Row( - children: [ - Text( - 'themeMode'.tr(), - style: TextStyle(fontSize: 16), - ), - Spacer(), - DropdownButton( - value: Singleton().appTheme.themeMode, - items: ThemeMode.values.map((ThemeMode mode) { - return DropdownMenuItem( - value: mode, - child: Text('${mode.name}Text'.tr()), - ); - }).toList(), - onChanged: (ThemeMode? value) async { + width: double.maxFinite, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ThemePreview(seed: seed), + const SizedBox(height: 16), + Center( + child: SegmentedButton( + showSelectedIcon: false, + segments: [ + for (final mode in ThemeMode.values) + ButtonSegment( + value: mode, + icon: Icon( + switch (mode) { + ThemeMode.system => Icons.brightness_auto, + ThemeMode.light => Icons.light_mode, + ThemeMode.dark => Icons.dark_mode, + }, + // The icons carry the label for the screen reader; + // three labels would not fit next to each other. + semanticLabel: '${mode.name}Text'.tr(), + ), + ), + ], + selected: {theme.themeMode}, + onSelectionChanged: (selection) async { setState(() { - Singleton().appTheme.themeMode = value!; - changeTheme(); + theme.themeMode = selection.first; }); - await CacheUtils.setTheme(Singleton().appTheme); + await apply(() {}); }, - ) - ], - ), - // Theme color - Row( - children: [ - Text( - 'themeColor'.tr(), - style: TextStyle(fontSize: 16), ), - Spacer(), - ElevatedButton( - onPressed: openColorPickerDialog, - child: Text('chooseColor'.tr()), - ), - ], - ), - // Use material 3 - Row( - children: [ - Text( - 'useMat3'.tr(), - style: TextStyle(fontSize: 16), - ), - Spacer(), - Switch( - value: Singleton().appTheme.useMaterial3, - onChanged: (_) { - setState(() { - Singleton().appTheme.useMaterial3 = - !Singleton().appTheme.useMaterial3; - changeTheme(); - CacheUtils.setTheme(Singleton().appTheme); - }); - }) - ], - ) - ], + ), + const SizedBox(height: 20), + Text('themeColor'.tr(), + style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 8), + ThemePalette( + selected: seed, + onPicked: (color) async { + setState(() { + theme.color = color; + }); + await apply(() {}); + }, + onCustom: openColorPickerDialog, + ), + ], + ), ), ), actionsAlignment: MainAxisAlignment.center, @@ -197,7 +197,8 @@ class DialogUtils { onPressed: Navigator.of(context).pop, child: Text( 'okText'.tr(), - style: TextStyle(color: Theme.of(context).colorScheme.surface), + style: + TextStyle(color: Theme.of(context).colorScheme.onPrimary), ), ), ], @@ -206,51 +207,193 @@ class DialogUtils { }); } - /// Returns color picker dialog - static Widget colorPickerDialog(BuildContext context, Color initialColor) { - Color pickerColor = initialColor; + /// Returns the per-chat theme dialog: the same palette and preview as the app + /// theme, plus a tile that hands the chat back to the global color. Mode and + /// Material version stay global, so they are not offered here. + /// + /// [onChanged] receives the picked color, or null for "use the global theme", + /// and is awaited before the next tap, so the page can persist it. + static Widget chatThemeDialog( + BuildContext context, { + required Color? current, + required Future Function(Color? color) onChanged, + }) { + // Outside the builder: a rebuild must not reset the pick back to the value + // the page had when the dialog opened. + Color? picked = current; + return StatefulBuilder(builder: (context, setState) { + Future openColorPickerDialog() async { + final value = await showDialog( + context: context, + builder: (context) => colorPickerDialog( + context, picked ?? Singleton().appTheme.color)); + if (value != null) { + setState(() { + picked = value; + }); + await onChanged(value); + } + } - return BackdropFilter( - filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), - child: AlertDialog( - title: Text('pickColor'.tr()), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ColorPicker( - enableAlpha: false, - labelTypes: [], - pickerColor: initialColor, - onColorChanged: (color) => pickerColor = color, + return BackdropFilter( + filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), + child: AlertDialog( + constraints: const BoxConstraints(maxWidth: 380), + title: Text('chatTheme'.tr()), + content: SizedBox( + width: double.maxFinite, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ThemePreview(seed: picked), + const SizedBox(height: 20), + Text('themeColor'.tr(), + style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 8), + ThemePalette( + selected: picked, + inheritSelected: picked == null, + onInherit: () async { + setState(() { + picked = null; + }); + await onChanged(null); + }, + onPicked: (color) async { + setState(() { + picked = color; + }); + await onChanged(color); + }, + onCustom: openColorPickerDialog, + ), + ], + ), + ), + ), + actionsAlignment: MainAxisAlignment.center, + actions: [ + TextButton( + style: ButtonStyle( + backgroundColor: WidgetStateProperty.all( + Theme.of(context).colorScheme.primary), + shape: WidgetStateProperty.all( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(35)), + ), + ), + onPressed: Navigator.of(context).pop, + child: Text('okText'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.onPrimary)), ), ], ), - actionsAlignment: MainAxisAlignment.center, - actions: [ - ElevatedButton( - onPressed: () => Navigator.of(context).pop(pickerColor), - style: ButtonStyle( - backgroundColor: WidgetStateProperty.all( - Theme.of(context).colorScheme.primary), - shape: WidgetStateProperty.all( - RoundedRectangleBorder(borderRadius: BorderRadius.circular(35)), + ); + }); + } + + /// Returns color picker dialog + static Widget colorPickerDialog(BuildContext context, Color initialColor) { + Color pickerColor = initialColor; + String hexOf(Color color) => '#' + '${color.toARGB32().toRadixString(16).padLeft(8, '0').substring(2).toUpperCase()}'; + final hexController = TextEditingController(text: hexOf(initialColor)); + + return StatefulBuilder(builder: (context, setState) { + void pick(Color color) { + setState(() { + pickerColor = color; + hexController.text = hexOf(color); + }); + } + + return BackdropFilter( + filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), + child: AlertDialog( + constraints: const BoxConstraints(maxWidth: 380), + title: Text('pickColor'.tr()), + content: SizedBox( + width: double.maxFinite, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // What the wheel currently holds, before the hex field: the + // wheel alone does not say which color is selected. + Container( + height: 36, + decoration: BoxDecoration( + color: pickerColor, + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: Theme.of(context).colorScheme.outlineVariant), + ), + ), + const SizedBox(height: 8), + TextField( + controller: hexController, + decoration: const InputDecoration( + isDense: true, + hintText: '#RRGGBB', + prefixIcon: Icon(Icons.tag, size: 18), + ), + onChanged: (value) { + try { + final parsed = ColorUtils.colorFromHex(value); + setState(() { + pickerColor = parsed; + }); + } catch (_) { + // Half-typed hex: keep the last valid color. + } + }, + ), + const SizedBox(height: 8), + ColorPicker( + enableAlpha: false, + labelTypes: const [], + displayThumbColor: true, + pickerColor: pickerColor, + onColorChanged: pick, + ), + ], ), ), - child: Text('okText'.tr(), - style: TextStyle(color: Theme.of(context).colorScheme.surface)), ), - ], - ), - ); + actionsAlignment: MainAxisAlignment.center, + actions: [ + ElevatedButton( + onPressed: () => Navigator.of(context).pop(pickerColor), + style: ButtonStyle( + backgroundColor: WidgetStateProperty.all( + Theme.of(context).colorScheme.primary), + shape: WidgetStateProperty.all( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(35)), + ), + ), + child: Text('okText'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.onPrimary)), + ), + ], + ), + ); + }); } - /// Returns yes/no dialog + /// Returns yes/no dialog. [theme] carries the chat colour when the dialog is + /// opened from a chat, whose Theme does not reach the Navigator's overlay. static Future yesNoDialog( - BuildContext context, String title, String content, Function onYes) { + BuildContext context, String title, String content, Function onYes, + {ThemeData? theme}) { return showDialog( context: context, - builder: (BuildContext context) { - return BackdropFilter( + builder: (dialogContext) { + final dialog = BackdropFilter( filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10), child: AlertDialog( title: Text(title), @@ -295,6 +438,7 @@ class DialogUtils { ], ), ); + return theme == null ? dialog : Theme(data: theme, child: dialog); }, ); } diff --git a/lib/utils/disappearing.dart b/lib/utils/disappearing.dart new file mode 100644 index 0000000..f8dba5c --- /dev/null +++ b/lib/utils/disappearing.dart @@ -0,0 +1,18 @@ +import 'package:easy_localization/easy_localization.dart'; + +/// Timers a chat can agree on: an hour, a day, a week. [0] turns the timer off. +const List disappearingOptions = [3600, 86400, 604800, 0]; + +/// Compact label of a timer in seconds, e.g. "1 h", "24 h", "7 d". +String disappearingLabel(int seconds) { + if (seconds <= 0) { + return 'disappearingOff'.tr(); + } + if (seconds % 86400 == 0) { + return '${seconds ~/ 86400} d'; + } + if (seconds % 3600 == 0) { + return '${seconds ~/ 3600} h'; + } + return '${seconds ~/ 60} min'; +} diff --git a/lib/utils/link_utils.dart b/lib/utils/link_utils.dart new file mode 100644 index 0000000..8c9ab68 --- /dev/null +++ b/lib/utils/link_utils.dart @@ -0,0 +1,43 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:sprintf/sprintf.dart'; +import 'package:url_launcher/url_launcher.dart'; + +/// Absolute http(s) addresses in a message text. +final RegExp _urlPattern = RegExp(r'https?://[^\s<>"]+', caseSensitive: false); + +/// Splits [text] into plain pieces and links, in order. +/// +/// `url` is null for plain text. A sentence-final dot, comma, semicolon or +/// colon is not treated as part of the address. +List<({String text, String? url})> splitLinks(String text) { + final parts = <({String text, String? url})>[]; + var index = 0; + for (final match in _urlPattern.allMatches(text)) { + var end = match.end; + while (end > match.start && '.,;:'.contains(text[end - 1])) { + end--; + } + if (match.start > index) { + parts.add((text: text.substring(index, match.start), url: null)); + } + final url = text.substring(match.start, end); + parts.add((text: url, url: url)); + index = end; + } + if (index < text.length) { + parts.add((text: text.substring(index), url: null)); + } + return parts; +} + +/// Opens [url] in the browser and reports a failure the way the app does. +Future openLink(String url) async { + if (!await launchUrl(Uri.parse(url))) { + await Fluttertoast.showToast( + msg: sprintf('urlError'.tr(), [url]), + backgroundColor: Colors.red, + ); + } +} diff --git a/lib/utils/live_location.dart b/lib/utils/live_location.dart new file mode 100644 index 0000000..de30db9 --- /dev/null +++ b/lib/utils/live_location.dart @@ -0,0 +1,221 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart' show Colors; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:geolocator/geolocator.dart'; + +import '../models/user.dart'; +import 'crypto_utils.dart'; +import 'singleton.dart'; + +/// One live position as the peer sees it: where, and until when. +class LiveLocationPoint { + final double lat; + final double lng; + final double? accuracy; + final DateTime until; + + const LiveLocationPoint(this.lat, this.lng, + {this.accuracy, required this.until}); + + String get coordinates => + '${lat.toStringAsFixed(5)}, ${lng.toStringAsFixed(5)}'; + + factory LiveLocationPoint.fromJson(Map json) { + return LiveLocationPoint( + (json['lat'] as num).toDouble(), + (json['lng'] as num).toDouble(), + accuracy: (json['accuracy'] as num?)?.toDouble(), + until: DateTime.parse(json['until'] as String), + ); + } + + Map toJson() => { + 'lat': lat, + 'lng': lng, + if (accuracy != null) 'accuracy': accuracy, + 'until': until.toUtc().toIso8601String(), + }; +} + +/// Wraps the four parts of one hybrid-encrypted position into one string the +/// WebSocket frame can carry. The server relays it and sees no coordinates. +String encodeEncryptedPayload(Map data) { + return base64Encode(utf8.encode(jsonEncode({ + 'data': base64Encode(data['encryptedData']!), + 'key': base64Encode(data['encryptedKey']!), + 'nonce': base64Encode(data['nonce']!), + 'mac': base64Encode(data['mac']!), + }))); +} + +/// Reverses [encodeEncryptedPayload]; null for anything malformed. +Map? decodeEncryptedPayload(String payload) { + try { + final raw = jsonDecode(utf8.decode(base64Decode(payload))); + if (raw is! Map) { + return null; + } + return { + 'encryptedData': base64Decode(raw['data'] as String), + 'encryptedKey': base64Decode(raw['key'] as String), + 'nonce': base64Decode(raw['nonce'] as String), + 'mac': base64Decode(raw['mac'] as String), + }; + } catch (_) { + return null; + } +} + +/// Decrypts one relayed position with this device's key. +Future decryptLiveLocation(String payload) async { + final parts = decodeEncryptedPayload(payload); + if (parts == null) { + return null; + } + try { + final plain = await CryptoUtils.decryptMessageData( + parts['encryptedData']!, + parts['encryptedKey']!, + parts['nonce']!, + parts['mac']!, + bu.CryptoUtils.rsaPrivateKeyFromPem(Singleton().profile.privateKey)); + return LiveLocationPoint.fromJson( + Map.from(jsonDecode(utf8.decode(plain)) as Map)); + } catch (_) { + return null; + } +} + +/// Shares this device's position for a limited time. Nothing is archived: the +/// frames stop at the deadline, and the peer keeps only the last point in +/// memory. +class LiveLocationSharer { + LiveLocationSharer._(); + + static final LiveLocationSharer instance = LiveLocationSharer._(); + + /// How often a fresh position is sent while sharing. + static const Duration interval = Duration(seconds: 10); + + Timer? _timer; + String? _peerId; + DateTime? _until; + DateTime? _started; + User? _peer; + LiveLocationPoint? _last; + + bool isSharing(String peerId) => _timer != null && _peerId == peerId; + + DateTime? get until => _until; + + /// When the running session started; the bubble sits at this instant in the + /// conversation instead of being pinned to the bottom. + DateTime? get startedAt => _started; + + /// Starts a session with [peer]. Returns false when there is no fix, which is + /// also what a refused permission looks like. + Future start(User peer, Duration duration) async { + await stop(); + final position = await currentPosition(); + if (position == null) { + await Fluttertoast.showToast( + msg: 'locationUnavailable'.tr(), backgroundColor: Colors.red); + return false; + } + _peerId = peer.id; + _peer = peer; + final now = DateTime.now(); + _started = now; + _until = now.add(duration); + await _send(peer, position); + _timer = Timer.periodic(interval, (_) async { + final next = await currentPosition(); + if (next != null) { + await _send(peer, next); + } + final deadline = _until; + if (deadline != null && DateTime.now().isAfter(deadline)) { + await stop(); + } + }); + return true; + } + + /// Ends the session. A peer that is still connected is told right away with + /// a last point that is already expired, so stopping early really stops it + /// for them too instead of waiting out the announced deadline. + Future stop() async { + final peer = _peer; + final last = _last; + final until = _until; + _timer?.cancel(); + _timer = null; + _peerId = null; + _peer = null; + _until = null; + _started = null; + _last = null; + if (peer != null && last != null && until != null) { + await _relay( + peer, + LiveLocationPoint(last.lat, last.lng, + accuracy: last.accuracy, until: DateTime.now()), + ); + } + } + + Future _send(User peer, Position position) async { + final deadline = _until; + if (deadline == null || !Singleton().wsClient.isConnected) { + return; + } + final point = LiveLocationPoint(position.latitude, position.longitude, + accuracy: position.accuracy, until: deadline); + _last = point; + await _relay(peer, point); + } + + /// Encrypts one point for [peer] and hands it to the socket. Nothing about a + /// live position is archived, so the socket is the only way in. + Future _relay(User peer, LiveLocationPoint point) async { + if (!Singleton().wsClient.isConnected) { + return; + } + try { + final data = await CryptoUtils.encryptMessageData( + utf8.encode(jsonEncode(point.toJson())), + bu.CryptoUtils.rsaPublicKeyFromPem(peer.publicKey)); + Singleton() + .wsClient + .sendLiveLocation(peer.id, encodeEncryptedPayload(data)); + } catch (_) { + // A frame that cannot be encrypted is dropped; the next tick retries. + } + } + + /// One fix from the platform, null when the user refused the permission or + /// location is switched off. + static Future currentPosition() async { + try { + if (!await Geolocator.isLocationServiceEnabled()) { + return null; + } + var permission = await Geolocator.checkPermission(); + if (permission == LocationPermission.denied) { + permission = await Geolocator.requestPermission(); + } + if (permission == LocationPermission.denied || + permission == LocationPermission.deniedForever) { + return null; + } + return await Geolocator.getCurrentPosition(); + } catch (_) { + return null; + } + } +} diff --git a/lib/utils/media_autoplay.dart b/lib/utils/media_autoplay.dart new file mode 100644 index 0000000..094f3a3 --- /dev/null +++ b/lib/utils/media_autoplay.dart @@ -0,0 +1,60 @@ +import 'package:flutter/foundation.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +import '../models/private_message.dart'; +import 'cache_utils.dart'; + +/// Chains messages that play on their own: when one finishes, the next one of +/// the same chat starts. +/// +/// The request is the key of the message that should play, and only the player +/// owning that key picks it up, so no bubble has to reach into another one. +class MediaAutoplay { + MediaAutoplay._(); + + /// Key of the message that should start playing, consumed by its player. + static final ValueNotifier request = ValueNotifier(null); + + /// Asks the next voice message after [afterSentAt] in [conversationId] to + /// play. + static Future next(String conversationId, DateTime afterSentAt) => + _next(conversationId, afterSentAt, + (message) => message.mediaType == MediaType.voice); + + /// Asks the next round note after [afterSentAt] in [conversationId] to play. + static Future nextRoundNote( + String conversationId, DateTime afterSentAt) => + _next(conversationId, afterSentAt, (message) => message.isVideoNote); + + /// The chain is for listening to the other side: it stops at our own message + /// instead of playing it back. It also stops at the end of the chat, and + /// skips a message that is not on this device, since that one could not play + /// anyway. + /// + /// shortcut: a player only exists while its bubble is built, so a request for + /// an off-screen message is dropped; upgrade by hoisting playback into a + /// service that owns the queue. + static Future _next(String conversationId, DateTime afterSentAt, + bool Function(PrivateMessage message) matches) async { + final messages = await CacheUtils.getPrivateMessages(conversationId); + messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); + for (final message in messages) { + if (!message.sentAt.isAfter(afterSentAt)) { + continue; + } + if (!matches(message)) { + continue; + } + // Our own message ends the chain: playback continues only into what the + // other side said. + if (message.isMe) { + return; + } + if (message.localPath == null) { + continue; + } + request.value = CacheUtils.messageKey(conversationId, message.sentAt); + return; + } + } +} diff --git a/lib/utils/media_upload.dart b/lib/utils/media_upload.dart new file mode 100644 index 0000000..0fb4274 --- /dev/null +++ b/lib/utils/media_upload.dart @@ -0,0 +1,180 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:http/http.dart' as http; +import 'package:shept_openapi_client_dart/api.dart'; + +import 'cache_utils.dart'; +import 'media_utils.dart'; +import 'singleton.dart'; +import 'utils.dart'; + +/// One recorded upload session of an unfinished attachment. +class _Record { + final String id; + final int totalSize; + final Uint8List key; + final Uint8List nonce; + + const _Record(this.id, this.totalSize, this.key, this.nonce); +} + +/// Resumable upload of one attachment. +/// +/// The server appends one chunk per request and reports the offset it holds, so +/// a connection that dies halfway costs only the bytes since the last accepted +/// chunk. While an upload is unfinished its session is recorded together with +/// the transport key and nonce, which is what lets a retry continue it (even +/// after a restart) instead of uploading the whole ciphertext again: the same +/// key and nonce reproduce the same bytes. +class MediaUploader { + MediaUploader._(); + + /// Upload the plaintext [bytes] of one attachment for [receiverId] and return + /// the media id and the transport encryption used. + /// + /// [messageKey] and [index] identify the attachment of a stored message; when + /// a session is recorded for that pair it is resumed. + /// + /// shortcut: the plaintext and its whole ciphertext are held in memory + /// together, so the 100 MiB cap can still exhaust a low-end phone; upgrade by + /// encrypting and sending one chunk at a time. + static Future<(String, TransportEncryption)> upload( + Uint8List bytes, { + required String receiverId, + String? messageKey, + int index = 0, + }) async { + final recordKey = messageKey == null ? null : '$messageKey|$index'; + final totalSize = bytes.length + MediaUtils.transportOverheadBytes; + TransportEncryption? transport; + String? uploadId; + var received = 0; + + final record = await _read(recordKey); + if (record != null && record.totalSize == totalSize) { + transport = await MediaUtils.encryptForTransport(bytes, + key: record.key, nonce: record.nonce); + final state = await _state(record.id); + if (state != null && state.totalSize == totalSize) { + uploadId = record.id; + received = state.received; + } + } + + transport ??= await MediaUtils.encryptForTransport(bytes); + if (uploadId == null) { + final session = await Utils.callApi( + () => Singleton().mediaApi.createMediaUpload( + createMediaUploadInput: CreateMediaUploadInput( + receiverId: receiverId, + totalSize: totalSize, + ), + ), + rethrowErr: true, + ); + if (session == null) { + throw Exception('mediaUploadFailed'.tr()); + } + uploadId = session.id; + received = session.received; + if (recordKey != null) { + await CacheUtils.setPendingUpload( + recordKey, + jsonEncode({ + 'id': uploadId, + 'totalSize': totalSize, + 'key': base64Encode(transport.key), + 'nonce': base64Encode(transport.nonce), + 'receiverId': receiverId, + })); + } + } + + final blob = transport.blob; + while (received < blob.length) { + final start = received; + final end = min(start + MediaUtils.uploadChunkBytes, blob.length); + final chunk = http.MultipartFile.fromBytes( + 'chunk', blob.sublist(start, end), + filename: 'chunk.bin'); + try { + final session = await Utils.callApi( + () => Singleton().mediaApi.uploadMediaChunk(uploadId!, start, chunk), + rethrowErr: true, + showError: false, + ); + received = session == null ? end : session.received; + } on ApiException catch (e) { + if (e.code != 409) { + rethrow; + } + // 409 is the resume path: the server holds a different offset. + final state = await _state(uploadId); + if (state == null || state.totalSize != totalSize) { + // The session expired or belongs to another file: start over. + if (recordKey != null) { + await CacheUtils.removePendingUpload(recordKey); + } + return upload(bytes, + receiverId: receiverId, messageKey: messageKey, index: index); + } + received = state.received; + } + } + + final completed = await Utils.callApi( + () => Singleton().mediaApi.completeMediaUpload(uploadId!), + rethrowErr: true, + ); + if (completed == null) { + throw Exception('mediaUploadFailed'.tr()); + } + if (recordKey != null) { + await CacheUtils.removePendingUpload(recordKey); + } + return (completed.id, transport); + } + + /// The recorded session of one attachment, or null. + static Future<_Record?> _read(String? recordKey) async { + if (recordKey == null) { + return null; + } + final raw = await CacheUtils.getPendingUpload(recordKey); + if (raw == null) { + return null; + } + try { + final json = jsonDecode(raw) as Map; + return _Record( + json['id'] as String, + (json['totalSize'] as num).toInt(), + base64Decode(json['key'] as String), + base64Decode(json['nonce'] as String), + ); + } catch (_) { + await CacheUtils.removePendingUpload(recordKey); + return null; + } + } + + /// The server's view of one session, or null when it is gone. + static Future _state( + String uploadId) async { + try { + return await Utils.callApi( + () => Singleton().mediaApi.getMediaUpload(uploadId), + rethrowErr: true, + showError: false, + ); + } on ApiException catch (e) { + if (e.code == 404) { + return null; + } + rethrow; + } + } +} diff --git a/lib/utils/media_utils.dart b/lib/utils/media_utils.dart new file mode 100644 index 0000000..df80bcd --- /dev/null +++ b/lib/utils/media_utils.dart @@ -0,0 +1,783 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:cryptography/cryptography.dart' as cryptography; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart' + show BuildContext, IconData, Icons, MediaQuery; +import 'package:image_picker/image_picker.dart'; +import 'package:mime/mime.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:record/record.dart'; +import 'package:uuid/uuid.dart'; +import 'package:video_player/video_player.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +import 'singleton.dart'; +import 'utils.dart'; + +/// Result of encrypting a file for transport: the uploadable [blob] +/// (`nonce || mac || ciphertext`) and the ephemeral symmetric [key] that goes +/// into the [MediaReference]. +class TransportEncryption { + final Uint8List blob; + final Uint8List key; + + /// Nonce of [blob]; kept so a resumed upload reproduces the same ciphertext. + final Uint8List nonce; + + const TransportEncryption(this.blob, this.key, this.nonce); +} + +/// Metadata extracted from a media file before sending. +class MediaProbe { + final int? width; + final int? height; + final int? durationMs; + + const MediaProbe({this.width, this.height, this.durationMs}); +} + +/// Arguments passed to the AES-GCM compute() workers. +class _GcmArgs { + final Uint8List data; + final Uint8List key; + + /// Pinned nonce, used to reproduce a blob that is already partly uploaded. + final Uint8List? nonce; + + const _GcmArgs(this.data, this.key, [this.nonce]); +} + +/// AES-GCM nonce length (bytes). +const int _nonceLength = 12; + +/// AES-GCM MAC length (bytes). +const int _macLength = 16; + +/// Encrypt [data] with AES-256-GCM and return `nonce || mac || ciphertext`. +/// Top-level so it can run in a background isolate via [compute]. +Future _gcmEncrypt(_GcmArgs args) async { + final algorithm = cryptography.AesGcm.with256bits(); + final secretKey = cryptography.SecretKey(args.key); + final box = await algorithm.encrypt(args.data, + secretKey: secretKey, nonce: args.nonce); + final nonce = box.nonce; + final mac = box.mac.bytes; + final out = Uint8List(nonce.length + mac.length + box.cipherText.length); + out.setRange(0, nonce.length, nonce); + out.setRange(nonce.length, nonce.length + mac.length, mac); + out.setRange(nonce.length + mac.length, out.length, box.cipherText); + return out; +} + +/// Decrypt a `nonce || mac || ciphertext` blob produced by [_gcmEncrypt]. +Future _gcmDecrypt(_GcmArgs args) async { + final blob = args.data; + final nonce = blob.sublist(0, _nonceLength); + final mac = blob.sublist(_nonceLength, _nonceLength + _macLength); + final cipher = blob.sublist(_nonceLength + _macLength); + final algorithm = cryptography.AesGcm.with256bits(); + final secretKey = cryptography.SecretKey(args.key); + final box = cryptography.SecretBox( + cipher, + nonce: nonce, + mac: cryptography.Mac(mac), + ); + final clear = await algorithm.decrypt(box, secretKey: secretKey); + return Uint8List.fromList(clear); +} + +/// Central helper for media attachments: transport + at-rest encryption, +/// pickers, the voice recorder, and metadata/thumbnail extraction. +/// +/// Two independent encryption layers are used (keys never leave the device +/// unencrypted): +/// * Transport: a random per-file AES-256-GCM key encrypts the bytes that are +/// uploaded to the server. The key travels (RSA+AES wrapped) inside the +/// message [MediaReference]. +/// * At-rest: downloaded/sent plaintext is re-encrypted with the app master +/// key ([Singleton.boxCollectionKey]) and stored on disk. +class MediaUtils { + MediaUtils._(); + + static const Uuid _uuid = Uuid(); + static final ImagePicker _imagePicker = ImagePicker(); + + /// Version marker used by a single-media message envelope. + static const int envelopeVersion = 1; + + /// Version marker used by an album envelope (media is a list of references). + static const int envelopeVersionAlbum = 2; + + // --------------------------------------------------------------------------- + // Transport encryption + // --------------------------------------------------------------------------- + + /// Encrypt [bytes] for upload. + /// + /// A fresh key and nonce per file, unless [key] and [nonce] are given: a + /// resumed upload must append the bytes the server already holds, so it + /// re-encrypts with the same pair. + static Future encryptForTransport(Uint8List bytes, + {Uint8List? key, Uint8List? nonce}) async { + var keyBytes = key; + if (keyBytes == null) { + final algorithm = cryptography.AesGcm.with256bits(); + keyBytes = Uint8List.fromList( + await (await algorithm.newSecretKey()).extractBytes()); + } + final blob = await compute(_gcmEncrypt, _GcmArgs(bytes, keyBytes, nonce)); + return TransportEncryption( + blob, keyBytes, Uint8List.fromList(blob.sublist(0, _nonceLength))); + } + + /// Decrypt a downloaded [blob] using the transport [key] from the reference. + static Future decryptTransport(Uint8List blob, Uint8List key) { + return compute(_gcmDecrypt, _GcmArgs(blob, key)); + } + + // --------------------------------------------------------------------------- + // At-rest encryption (local persistence) + // --------------------------------------------------------------------------- + + /// Encrypt plaintext [bytes] with the app master key and write them to the + /// media directory. Returns the absolute path of the stored encrypted file. + static Future encryptAtRest(Uint8List bytes) async { + final key = Uint8List.fromList(Singleton().boxCollectionKey); + final blob = await compute(_gcmEncrypt, _GcmArgs(bytes, key)); + final dir = await mediaDir(); + final path = '$dir/${_uuid.v4()}'; + await File(path).writeAsBytes(blob, flush: true); + return path; + } + + /// Decrypt an at-rest file written by [encryptAtRest]. + /// + /// Throttled: decrypting spawns an isolate per call, so a chat full of + /// attachments would otherwise spawn one burst per scroll. Decrypted bytes + /// are kept for the most recently shown attachments: a list disposes its + /// rows when they leave the viewport, and decrypting the same photo again + /// every time it scrolls back is what kept the spinner up. + static Future decryptAtRest(String path) async { + final cached = _mediaCache.remove(path); + if (cached != null) { + _mediaCache[path] = cached; + return cached; + } + return _withDecryptSlot(() async { + final blob = await File(path).readAsBytes(); + final key = Uint8List.fromList(Singleton().boxCollectionKey); + final plain = await compute(_gcmDecrypt, _GcmArgs(blob, key)); + _cacheBytes(path, plain); + return plain; + }); + } + + /// Decoded media kept in memory, oldest first. + static final Map _mediaCache = {}; + static const int _maxCachedMedia = 24; + static const int _maxCachedBytes = 64 << 20; + static int _cachedBytes = 0; + + static void _cacheBytes(String path, Uint8List bytes) { + final previous = _mediaCache.remove(path); + if (previous != null) { + _cachedBytes -= previous.length; + } + if (bytes.length > _maxCachedBytes) { + return; + } + _mediaCache[path] = bytes; + _cachedBytes += bytes.length; + while (_mediaCache.length > _maxCachedMedia || + _cachedBytes > _maxCachedBytes) { + _cachedBytes -= _mediaCache.remove(_mediaCache.keys.first)!.length; + } + } + + /// Drops the plaintext attachments held in memory, e.g. when the local media + /// files are deleted. + static void clearDecryptCache() { + _mediaCache.clear(); + _cachedBytes = 0; + } + + /// Decode width for [Image.memory]: a camera photo must not be decoded at its + /// full resolution for a thumbnail-sized box. + static int decodeWidth(BuildContext context, double logicalWidth) => + (logicalWidth * MediaQuery.devicePixelRatioOf(context)).round(); + + static const int _maxConcurrentDecrypts = 2; + static int _activeDecrypts = 0; + static final List> _decryptWaiters = []; + + /// Runs [task] while at most [_maxConcurrentDecrypts] decrypts are alive. + static Future _withDecryptSlot(Future Function() task) async { + while (_activeDecrypts >= _maxConcurrentDecrypts) { + final waiter = Completer(); + _decryptWaiters.add(waiter); + await waiter.future; + } + _activeDecrypts++; + try { + return await task(); + } finally { + _activeDecrypts--; + if (_decryptWaiters.isNotEmpty) { + _decryptWaiters.removeAt(0).complete(); + } + } + } + + /// Encrypt bytes with an explicit AES-GCM key (no singleton lookup). + static Future encryptWith(Uint8List bytes, List key) { + return compute(_gcmEncrypt, _GcmArgs(bytes, Uint8List.fromList(key))); + } + + /// Decrypt a blob with an explicit AES-GCM key (no singleton lookup). + static Future decryptWith(Uint8List blob, List key) { + return compute(_gcmDecrypt, _GcmArgs(blob, Uint8List.fromList(key))); + } + + /// Phase 1 of a password change: decrypts every at-rest media file with + /// [oldKey] and writes `.new` encrypted with [newKey]. Originals stay + /// untouched until [commitRekey], so an interrupted change loses nothing. + static Future> stageRekey( + List oldKey, List newKey) async { + final dir = Directory(await mediaDir()); + final staged = []; + try { + await for (final entity in dir.list()) { + if (entity is! File || entity.path.endsWith('.new')) { + continue; + } + final blob = await entity.readAsBytes(); + final Uint8List plain; + try { + plain = await decryptWith(blob, oldKey); + } catch (e) { + // A file that does not decrypt with the current key is already + // unreadable; leave it alone instead of failing the whole change. + debugPrint('rekey skipped ${entity.path}: $e'); + continue; + } + final encrypted = await encryptWith(plain, newKey); + final target = '${entity.path}.new'; + await File(target).writeAsBytes(encrypted, flush: true); + staged.add(target); + } + } catch (e) { + await discardRekey(staged); + rethrow; + } + return staged; + } + + /// Phase 2: replaces the originals with the staged files. + static Future commitRekey(List staged) async { + for (final path in staged) { + await File(path).rename(path.substring(0, path.length - '.new'.length)); + } + } + + /// Drops staged files after a failed key change. + static Future discardRekey(List staged) async { + for (final path in staged) { + try { + await File(path).delete(); + } catch (_) { + // Staged files are disposable. + } + } + } + + /// Decrypt an at-rest file into a temporary plaintext file (for the platform + /// video/audio players). The caller is responsible for deleting it on dispose. + static Future materializeTempFile(String path, String extension) async { + final bytes = await decryptAtRest(path); + final tmpDir = await getTemporaryDirectory(); + final file = File('${tmpDir.path}/shept_media_${_uuid.v4()}$extension'); + await file.writeAsBytes(bytes, flush: true); + return file; + } + + // --------------------------------------------------------------------------- + // Filesystem helpers + // --------------------------------------------------------------------------- + + /// Directory where encrypted-at-rest media files live. + static Future mediaDir() async { + final dir = '${await Utils.getCacheDir()}/media'; + await Directory(dir).create(recursive: true); + return dir; + } + + /// Writes plaintext bytes to a temporary file, e.g. for keyboard-inserted + /// GIFs that then go through the media pipeline. Never into [mediaDir], + /// which must only hold encrypted files. + static Future writeTempBytes(Uint8List bytes, String extension) async { + final tmpDir = await getTemporaryDirectory(); + final file = File('${tmpDir.path}/shept_send_${_uuid.v4()}.$extension'); + await file.writeAsBytes(bytes, flush: true); + return file; + } + + /// Whether a file name belongs to the app's plaintext temp files. + static bool isTempMediaName(String name) => + name.startsWith('shept_media_') || name.startsWith('shept_send_'); + + /// Remove plaintext media left in the temp directory. + /// + /// Playback materializes decrypted files and the keyboard writes plaintext + /// GIFs; both are deleted on dispose, but a crash leaves them behind. At + /// rest they must not exist. + static Future clearTempFiles() async { + try { + final dir = await getTemporaryDirectory(); + await for (final entity in dir.list()) { + if (entity is! File) { + continue; + } + if (isTempMediaName(baseName(entity.path))) { + await entity.delete(); + } + } + } catch (e) { + if (kDebugMode) { + debugPrint('Failed to clear temp media: $e'); + } + } + } + + /// Forgets the decrypted copies kept in memory. They are plaintext, so + /// dropping them is the cheapest way to take readable media out of reach. + static void clearDecryptedCache() { + _mediaCache.clear(); + } + + /// Delete a single (encrypted) media file, ignoring errors. + static Future deleteLocalFile(String? path) async { + if (path == null) { + return; + } + try { + final file = File(path); + if (await file.exists()) { + await file.delete(); + } + } catch (e) { + if (kDebugMode) { + debugPrint('Failed to delete media file $path: $e'); + } + } + } + + /// Remove every locally stored media file (used on full cache wipe). + static Future clearMediaDir() async { + clearDecryptCache(); + try { + final dir = Directory('${await Utils.getCacheDir()}/media'); + if (await dir.exists()) { + await dir.delete(recursive: true); + } + } catch (e) { + if (kDebugMode) { + debugPrint('Failed to clear media dir: $e'); + } + } + } + + // --------------------------------------------------------------------------- + // Type detection & extensions + // --------------------------------------------------------------------------- + + /// Detect the [MediaType] of a file from its mime type / extension. + static MediaType detectType(String path, {String? mimeType}) { + final mime = mimeType ?? lookupMimeType(path) ?? ''; + final lower = path.toLowerCase(); + if (mime == 'image/gif' || lower.endsWith('.gif')) { + return MediaType.gif; + } + if (mime.startsWith('image/')) { + return MediaType.image; + } + if (mime.startsWith('video/')) { + return MediaType.video; + } + if (mime.startsWith('audio/')) { + return MediaType.voice; + } + // Anything else is sent as a plain file. + return MediaType.file; + } + + /// Default file extension used when materializing a temp file for playback, + /// or as a last resort when a real name is not known. + static String extensionForType(MediaType type) { + switch (type) { + case MediaType.image: + return '.jpg'; + case MediaType.gif: + return '.gif'; + case MediaType.video: + return '.mp4'; + case MediaType.voice: + return '.m4a'; + case MediaType.sticker: + return '.png'; + case MediaType.file: + return ''; + } + } + + /// Largest upload the server accepts (mirrors MEDIA_MAX_UPLOAD_SIZE). + /// + /// shortcut: a file is still encrypted, chunked and decrypted in memory, so + /// raising this much further needs streaming GCM before it is safe. + static const int maxUploadBytes = 100 * 1024 * 1024; + + /// Upload chunk size (mirrors what the server appends per request). + static const int uploadChunkBytes = 1024 * 1024; + + /// AES-GCM overhead added to every uploaded file (nonce + mac). + static const int transportOverheadBytes = _nonceLength + _macLength; + + /// Whether a plaintext file of [plaintextBytes] fits the server limit once + /// it is encrypted for transport. + static bool uploadFits(int plaintextBytes) => + plaintextBytes + transportOverheadBytes <= maxUploadBytes; + + /// Last path segment of [path], i.e. the file name with its extension. + static String baseName(String path) => path.split(RegExp(r'[\\/]')).last; + + /// Icon for a document, picked from its extension. Everything unknown falls + /// back to a plain file. + static IconData iconForFileName(String? fileName) { + final dot = fileName?.lastIndexOf('.') ?? -1; + final extension = dot >= 0 && dot < (fileName!.length - 1) + ? fileName.substring(dot + 1).toLowerCase() + : ''; + switch (extension) { + case 'pdf': + return Icons.picture_as_pdf; + case 'doc': + case 'docx': + case 'odt': + case 'rtf': + return Icons.description; + case 'xls': + case 'xlsx': + case 'ods': + case 'csv': + return Icons.table_chart; + case 'ppt': + case 'pptx': + case 'odp': + return Icons.slideshow; + case 'zip': + case 'rar': + case '7z': + case 'tar': + case 'gz': + return Icons.folder_zip; + case 'json': + case 'xml': + case 'yaml': + case 'yml': + case 'html': + return Icons.code; + case 'txt': + case 'md': + case 'log': + return Icons.article; + default: + return Icons.insert_drive_file; + } + } + + /// Human readable size, e.g. `1.4 MB`. + static String formatBytes(int bytes) { + if (bytes < 1024) { + return '$bytes B'; + } + const units = ['KB', 'MB', 'GB']; + double value = bytes / 1024; + var unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; + } + return '${value.toStringAsFixed(value >= 10 ? 0 : 1)} ${units[unit]}'; + } + + /// Translation key for a short human label of a media type (used in previews + /// and notifications). + static String labelKeyForType(MediaType type) { + switch (type) { + case MediaType.image: + return 'mediaPhoto'; + case MediaType.gif: + return 'mediaGif'; + case MediaType.video: + return 'mediaVideo'; + case MediaType.voice: + return 'mediaVoice'; + case MediaType.sticker: + return 'mediaSticker'; + case MediaType.file: + return 'mediaFile'; + } + } + + // --------------------------------------------------------------------------- + // Metadata & thumbnails + // --------------------------------------------------------------------------- + + /// Decode the pixel dimensions of an encoded image (png/jpg/gif/webp). + static Future imageDimensions(Uint8List bytes) async { + try { + final codec = await ui.instantiateImageCodec(bytes); + final frame = await codec.getNextFrame(); + final image = frame.image; + final probe = MediaProbe(width: image.width, height: image.height); + image.dispose(); + codec.dispose(); + return probe; + } catch (_) { + return const MediaProbe(); + } + } + + /// Read width/height/duration of a video by briefly initializing a controller. + static Future videoMetadata(String filePath) async { + final controller = VideoPlayerController.file(File(filePath)); + try { + await controller.initialize(); + // The player reports the size with the recorded rotation already applied + // (a portrait clip comes back 480x720 from a 720x480 frame), so applying + // the rotation again here would lay it back on its side. + final size = controller.value.size; + return MediaProbe( + width: size.width.round(), + height: size.height.round(), + durationMs: controller.value.duration.inMilliseconds, + ); + } catch (_) { + return const MediaProbe(); + } finally { + await controller.dispose(); + } + } + + // --------------------------------------------------------------------------- + // Message envelope codec + // --------------------------------------------------------------------------- + + /// Build the plaintext (pre-encryption) bytes for a media message: a JSON + /// envelope wrapping the [reference] and optional [caption]. [viewOnce] marks + /// a single-view attachment; the flag rides inside the ciphertext, so only + /// the two participants know. + static Uint8List buildMediaEnvelope(MediaReference reference, String caption, + {bool forwarded = false, bool viewOnce = false}) { + final map = { + 'sheptMsg': envelopeVersion, + 'kind': 'media', + 'caption': caption, + 'media': reference.toJson(), + if (forwarded) 'forwarded': true, + if (viewOnce) 'viewOnce': true, + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); + } + + /// Build the plaintext (pre-encryption) bytes for an album message: a JSON + /// envelope wrapping [references] and an optional [caption]. + static Uint8List buildAlbumEnvelope( + List references, String caption, + {bool forwarded = false, bool viewOnce = false}) { + final map = { + 'sheptMsg': envelopeVersionAlbum, + 'kind': 'media', + 'caption': caption, + 'media': references.map((reference) => reference.toJson()).toList(), + if (forwarded) 'forwarded': true, + if (viewOnce) 'viewOnce': true, + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); + } + + /// Try to parse decrypted [plaintext] as a media envelope (single or album). + /// Returns null when the bytes are not a media envelope (i.e. plain text). + static ParsedMediaEnvelope? tryParseMediaEnvelope(Uint8List plaintext) { + try { + final decoded = jsonDecode(utf8.decode(plaintext)); + if (decoded is Map && decoded['kind'] == 'media') { + final caption = (decoded['caption'] as String?) ?? ''; + final forwarded = decoded['forwarded'] == true; + final viewOnce = decoded['viewOnce'] == true; + if (decoded['sheptMsg'] == envelopeVersion && decoded['media'] is Map) { + final reference = MediaReference.fromJson( + Map.from(decoded['media'] as Map)); + return ParsedMediaEnvelope([reference], caption, + forwarded: forwarded, viewOnce: viewOnce); + } + if (decoded['sheptMsg'] == envelopeVersionAlbum && + decoded['media'] is List) { + final references = (decoded['media'] as List) + .whereType() + .map((item) => + MediaReference.fromJson(Map.from(item))) + .toList(); + if (references.isNotEmpty) { + return ParsedMediaEnvelope(references, caption, + forwarded: forwarded, viewOnce: viewOnce); + } + } + } + } catch (_) { + // Not JSON / not a media envelope -> treat as plain text. + } + return null; + } + + // --------------------------------------------------------------------------- + // Pickers + // --------------------------------------------------------------------------- + + /// Pick one arbitrary file. + static Future pickFile() async { + final picked = await FilePicker.pickFile(type: FileType.any); + final path = picked?.path; + return path == null ? null : File(path); + } + + /// Pick several images/videos from the gallery at once (album). + static Future> pickMultipleMediaFromGallery() async { + final picked = await _imagePicker.pickMultipleMedia(); + return picked.map((x) => File(x.path)).toList(); + } + + /// Pick several arbitrary files at once (album). + static Future> pickMultipleFiles() async { + final picked = await FilePicker.pickFiles(type: FileType.any); + return picked + .map((file) => file.path) + .whereType() + .map((path) => File(path)) + .toList(); + } + + /// Whether [file] is a photo, gif or video (the "File" attachment must not + /// send those; the gallery and camera entries are for them). + static bool isVisualMedia(File file) { + final type = detectType(file.path); + return type == MediaType.image || + type == MediaType.gif || + type == MediaType.video; + } +} + +/// Parsed media envelope: one or more [MediaReference]s plus the caption. +class ParsedMediaEnvelope { + final List references; + final String caption; + + /// The sender passed on somebody else's attachment instead of writing it. + final bool forwarded; + + /// A single-view attachment: one open, then gone for both sides. + final bool viewOnce; + + const ParsedMediaEnvelope(this.references, this.caption, + {this.forwarded = false, this.viewOnce = false}); +} + +/// Thin wrapper around the [AudioRecorder] for hold-to-record voice messages. +class MediaRecorderController { + final AudioRecorder _recorder = AudioRecorder(); + String? _path; + DateTime? _startedAt; + final List _waveform = []; + StreamSubscription? _amplitudeSub; + + /// Ten minutes of samples at one per 100 ms: a longer recording keeps its + /// shape from the first ten minutes rather than growing without bound. + static const int maxWaveformSamples = 600; + + /// Loudness samples of the recording, 0-100, oldest first. + /// + /// The recipient cannot derive these without decoding the file, so they + /// travel in the message reference. + List get waveform => List.unmodifiable(_waveform); + + Future hasPermission() => _recorder.hasPermission(); + + /// Start recording to a temporary .m4a file. + Future start() async { + final dir = await getTemporaryDirectory(); + _path = '${dir.path}/shept_voice_${const Uuid().v4()}.m4a'; + await _recorder.start( + const RecordConfig(encoder: AudioEncoder.aacLc, numChannels: 1), + path: _path!, + ); + _startedAt = DateTime.now(); + _waveform.clear(); + _amplitudeSub = + _recorder.onAmplitudeChanged(const Duration(milliseconds: 100)).listen( + (amplitude) { + if (_waveform.length >= maxWaveformSamples) { + return; + } + // dBFS sits around -60..0 for speech; anything quieter is silence. + final level = ((amplitude.current + 60) / 60 * 100).clamp(0.0, 100.0); + _waveform.add(level.round()); + }, + onError: (_) {}, + ); + } + + /// Stop recording and return the resulting file and its duration. + Future stop() async { + await _amplitudeSub?.cancel(); + _amplitudeSub = null; + final path = await _recorder.stop(); + final durationMs = _startedAt == null + ? 0 + : DateTime.now().difference(_startedAt!).inMilliseconds; + if (path == null) { + return null; + } + return RecordedVoice(File(path), durationMs); + } + + /// Abort recording and discard the partial file. + Future cancel() async { + await _amplitudeSub?.cancel(); + _amplitudeSub = null; + try { + await _recorder.stop(); + } catch (_) { + // ignore + } + await MediaUtils.deleteLocalFile(_path); + } + + Future dispose() async { + await _amplitudeSub?.cancel(); + _amplitudeSub = null; + await _recorder.dispose(); + } +} + +/// A finished voice recording. +class RecordedVoice { + final File file; + final int durationMs; + + const RecordedVoice(this.file, this.durationMs); +} diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart new file mode 100644 index 0000000..0407320 --- /dev/null +++ b/lib/utils/message_actions.dart @@ -0,0 +1,640 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:easy_localization/easy_localization.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:share_plus/share_plus.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; +import 'package:shept_openapi_client_dart/api.dart'; + +import '../models/private_message.dart'; +import '../pages/forward_page.dart'; +import 'cache_utils.dart'; +import 'chat_sender.dart'; +import 'crypto_utils.dart'; +import 'dialog_utils.dart'; +import 'media_utils.dart'; +import 'message_notifier.dart'; +import 'singleton.dart'; +import 'text_envelope.dart'; +import 'utils.dart'; +import '../utils/nav_transitions.dart'; + +/// Actions for a single message, offered by the bubble long-press sheet and by +/// the attachment viewer's overflow menu. +class MessageActions { + /// Icons shared by the bubble sheet and the viewer's overflow menu, so both + /// offer the same actions with the same icons. + static const IconData copyIcon = Icons.copy; + static const IconData forwardIcon = Icons.forward; + static const IconData saveIcon = Icons.download; + static const IconData deleteIcon = Icons.delete; + static const IconData resendIcon = Icons.refresh; + static const IconData editIcon = Icons.edit; + static const IconData pinIcon = Icons.push_pin_outlined; + static const IconData unpinIcon = Icons.push_pin; + static const IconData selectIcon = Icons.checklist; + + /// Reaction a double-tap adds, toggled off by a second double-tap. + static const String quickReaction = '❤️'; + + /// Emoji offered by the reaction row. A short fixed set keeps reacting one + /// tap instead of opening a picker. + static const List reactionEmojis = [ + '👍', + '❤️', + '😂', + '😮', + '😢', + '🙏' + ]; + + /// Whether [message] can be saved or forwarded (the file must be on disk). + static bool canSave(PrivateMessage message) => + message.isMedia && message.localPath != null; + + /// A view-once attachment may not be passed on: it is one open, for one + /// conversation. + static bool canForward(PrivateMessage message) => !message.viewOnce; + + /// Opens a static location in the platform map app. The coordinates leave the + /// app only through this explicit tap. + static Future openLocation(LocationRef location, + {void Function()? onError}) async { + final uri = Uri.parse( + 'geo:${location.lat},${location.lng}?q=${location.lat},${location.lng}'); + final opened = await launchUrl(uri, mode: LaunchMode.externalApplication); + if (!opened) { + onError?.call(); + } + } + + /// Spends the one view of a view-once attachment: the local copy goes, the + /// archive row stays as a tombstone and the server records the instant, so + /// the sender learns it too. The server call is best effort — a torn network + /// only costs the sender the signal, never the one-view rule. + static Future consumeViewOnce( + String conversationUserId, PrivateMessage message) async { + final id = message.id; + if (id != null && id.isNotEmpty) { + try { + await Utils.callApi(() => Singleton().messagesApi.openMessage(id)); + } catch (_) { + // The tombstone is local either way. + } + } + await CacheUtils.markMessageOpened( + conversationUserId, message.sentAt, DateTime.now()); + MessageNotifier().notify(); + } + + /// The emoji row of a reaction sheet: one tap sets the caller's reaction, or + /// takes it back when it is the one already picked. + static Widget reactionRow( + BuildContext context, PrivateMessage message, String conversationUserId) { + final mine = message.reactions?[Singleton().profile.user.id]; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + for (final emoji in reactionEmojis) + IconButton( + style: emoji == mine + ? IconButton.styleFrom( + backgroundColor: + Theme.of(context).colorScheme.primaryContainer, + side: BorderSide( + color: Theme.of(context).colorScheme.primary), + ) + : null, + onPressed: () { + Navigator.pop(context); + react(message, conversationUserId, emoji); + }, + icon: Text(emoji, style: const TextStyle(fontSize: 22)), + ), + ], + ), + ); + } + + /// Reactions grouped by emoji, most used first, with the name of every + /// participant. [nameOf] resolves a user id, so the grouping stays free of + /// the user cache and can be tested on its own. + static List>> groupReactions( + Map reactions, String Function(String userId) nameOf) { + final grouped = >{}; + for (final entry in reactions.entries) { + grouped.putIfAbsent(entry.value, () => []).add(nameOf(entry.key)); + } + final rows = grouped.entries.toList() + ..sort((a, b) { + final byCount = b.value.length.compareTo(a.value.length); + return byCount != 0 ? byCount : a.key.compareTo(b.key); + }); + return rows; + } + + /// Who reacted with what. Names come from the local user cache, so this is a + /// cache read and never a server call. + static Future showReactions(BuildContext context, + PrivateMessage message, String conversationUserId) async { + final reactions = message.reactions ?? const {}; + if (reactions.isEmpty) { + return; + } + final me = Singleton().profile.user.id; + final names = {me: 'meText'.tr()}; + for (final id in reactions.keys) { + if (names.containsKey(id)) { + continue; + } + names[id] = (await CacheUtils.getUserById(id))?.username ?? '?'; + } + if (!context.mounted) { + return; + } + final rows = groupReactions(reactions, (id) => names[id] ?? '?'); + + await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + // The list is also where a reaction is given: tapping the badge + // used to open the action sheet, and a read-only list would take + // that away. + if (message.id?.isNotEmpty ?? false) + reactionRow(ctx, message, conversationUserId), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: Text('reactionsTitle'.tr(), + style: Theme.of(ctx).textTheme.titleMedium), + ), + for (final row in rows) + ListTile( + leading: Text(row.key, style: const TextStyle(fontSize: 22)), + title: Text(row.value.join(', ')), + ), + ], + ), + ), + ); + } + + /// Bubble long-press sheet with all actions that apply to [message]. + /// [conversationUserId] is the other side of the conversation. + static Future showSheet( + BuildContext context, PrivateMessage message, String conversationUserId, + {VoidCallback? onDeleted, bool pinned = false, VoidCallback? onSelect}) { + return showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (ctx) { + final canAddress = + message.id?.isNotEmpty ?? false; // needs the archive id + // A tombstone carries nothing to act on; hiding it for this account is + // the only thing left. + if (message.isDeleted) { + return SafeArea( + child: Wrap( + children: [ + ListTile( + leading: const Icon(deleteIcon), + title: Text('deleteMessageForMe'.tr()), + onTap: () { + Navigator.pop(ctx); + delete(context, message, conversationUserId, + onDeleted: onDeleted); + }, + ), + ], + ), + ); + } + return SafeArea( + child: Wrap( + children: [ + // Reactions first: one tap, and the same emoji again removes it. + if (canAddress) reactionRow(ctx, message, conversationUserId), + if (message.isMe && !message.isUndecryptable && canAddress) + ListTile( + leading: const Icon(editIcon), + title: Text('editMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + edit(context, message, conversationUserId); + }, + ), + if (canAddress) + ListTile( + leading: Icon(pinned ? unpinIcon : pinIcon), + title: Text(pinned ? 'unpinMessage'.tr() : 'pinMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + togglePin(message, conversationUserId, pinned: pinned); + }, + ), + if (onSelect != null) + ListTile( + leading: const Icon(selectIcon), + title: Text('selectMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + onSelect(); + }, + ), + if (message.isMe && message.sendStatus == SendStatus.failed) + ListTile( + leading: const Icon(resendIcon), + title: Text('resendMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + ChatSender.resend(conversationUserId, message); + }, + ), + if (message.message.isNotEmpty) + ListTile( + leading: const Icon(copyIcon), + title: Text('copyMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + copy(message); + }, + ), + if (canForward(message)) + ListTile( + leading: const Icon(forwardIcon), + title: Text('forwardMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + forward(context, [message]); + }, + ), + if (canShare(message)) + ListTile( + leading: const Icon(Icons.ios_share), + title: Text('shareMessage'.tr()), + onTap: () { + Navigator.pop(ctx); + shareToApp(message); + }, + ), + if (canSave(message)) + ListTile( + leading: const Icon(saveIcon), + title: Text('saveAttachment'.tr()), + onTap: () { + Navigator.pop(ctx); + save(message); + }, + ), + // In the debug self-chat the other side is you, so "for + // everyone" would mean exactly the same as "for me". + if (message.isMe && + conversationUserId != Singleton().profile.user.id && + (message.id?.isNotEmpty ?? false)) + ListTile( + leading: const Icon(deleteIcon), + title: Text('deleteMessageForEveryone'.tr()), + onTap: () { + Navigator.pop(ctx); + deleteForEveryone(context, message, conversationUserId, + onDeleted: onDeleted); + }, + ), + ListTile( + leading: const Icon(deleteIcon), + title: Text('deleteMessageForMe'.tr()), + onTap: () { + Navigator.pop(ctx); + delete(context, message, conversationUserId, + onDeleted: onDeleted); + }, + ), + ], + ), + ); + }, + ); + } + + /// Copy the message text (the caption for media messages). + static Future copy(PrivateMessage message) async { + await Clipboard.setData(ClipboardData(text: message.message)); + Fluttertoast.showToast(msg: 'copiedText'.tr()); + } + + /// Sets the caller's reaction, or removes it when the same emoji is picked + /// again. The emoji travels encrypted like the message body. + static Future react( + PrivateMessage message, String conversationUserId, String emoji) async { + final id = message.id; + if (id == null || id.isEmpty) { + return; + } + final me = Singleton().profile.user.id; + final removing = message.reactions?[me] == emoji; + try { + if (removing) { + await Utils.callApi(() => Singleton().messagesApi.removeReaction(id), + rethrowErr: true); + } else { + final peer = await CacheUtils.getUserById(conversationUserId); + if (peer == null) { + return; + } + final data = await CryptoUtils.encryptMessageData( + Uint8List.fromList(utf8.encode(emoji)), + bu.CryptoUtils.rsaPublicKeyFromPem(peer.publicKey)); + await Utils.callApi( + () => Singleton().messagesApi.setReaction( + id, + setReactionInput: SetReactionInput( + content: data['encryptedData']!, + key: data['encryptedKey']!, + nonce: data['nonce']!, + mac: data['mac']!, + ), + ), + rethrowErr: true); + } + await CacheUtils.setMessageReaction( + conversationUserId, message.sentAt, me, removing ? null : emoji); + MessageNotifier().notify(); + } catch (_) { + // The server refused; nothing changed locally either. + } + } + + /// Pins or unpins the message for both participants. + static Future togglePin( + PrivateMessage message, String conversationUserId, + {required bool pinned}) async { + final id = message.id; + if (id == null || id.isEmpty) { + return; + } + try { + await Utils.callApi( + () => pinned + ? Singleton().messagesApi.unpinMessage(id) + : Singleton().messagesApi.pinMessage(id), + rethrowErr: true); + await CacheUtils.setMessagePinned( + conversationUserId, id, pinned ? null : DateTime.now()); + MessageNotifier().notify(); + } catch (_) { + // Left as it was. + } + } + + /// Rewrites the text of an own message: new ciphertext, server stamp, same + /// bubble. + static Future edit(BuildContext context, PrivateMessage message, + String conversationUserId) async { + final id = message.id; + if (id == null || id.isEmpty) { + return; + } + final text = await showDialog( + context: context, + builder: (_) => _EditMessageDialog(initial: message.message), + ); + // A plain message cannot become empty; a caption can be cleared. + final unchanged = text == null || text == message.message; + if (unchanged || (text.trim().isEmpty && !message.isMedia)) { + return; + } + try { + final peer = await CacheUtils.getUserById(conversationUserId); + if (peer == null) { + return; + } + // A reply keeps its quote and an attachment keeps its media reference, so + // only the body of the envelope changes. + final Uint8List plaintext; + if (message.isMedia) { + final references = await ChatSender.mediaReferencesFor(peer, message); + if (references == null || references.isEmpty) { + await Fluttertoast.showToast( + msg: 'attachmentCaptionUneditable'.tr(), + backgroundColor: Colors.red); + return; + } + plaintext = message.isAlbum + ? MediaUtils.buildAlbumEnvelope(references, text, + forwarded: message.forwarded) + : MediaUtils.buildMediaEnvelope(references.first, text, + forwarded: message.forwarded); + } else { + final reply = message.replyTo; + plaintext = + reply == null ? utf8.encode(text) : buildTextEnvelope(text, reply); + } + final data = await CryptoUtils.encryptMessageData( + plaintext, bu.CryptoUtils.rsaPublicKeyFromPem(peer.publicKey)); + final response = await Utils.callApi( + () => Singleton().messagesApi.editMessage( + id, + editMessageInput: EditMessageInput( + content: data['encryptedData']!, + key: data['encryptedKey']!, + nonce: data['nonce']!, + mac: data['mac']!, + ), + ), + rethrowErr: true); + await CacheUtils.markMessageEdited(conversationUserId, message.sentAt, + text, (response?.editedAt ?? DateTime.now()).toLocal()); + MessageNotifier().notify(); + } catch (_) { + // The old text stays in place. + } + } + + /// Whether the message can be handed to another app. + static bool canShare(PrivateMessage message) => + !message.viewOnce && + (message.message.isNotEmpty || message.localPath != null); + + /// Hand the text, or a decrypted copy of the attachment, to another app. + /// + /// The plaintext copy is written under the temporary-media prefix, so it is + /// swept on the next start even if the app is killed while sharing; here it + /// is deleted as soon as the share sheet returns. + static Future shareToApp(PrivateMessage message) async { + final path = message.localPath; + try { + if (path == null) { + await SharePlus.instance.share(ShareParams(text: message.message)); + return; + } + final bytes = await MediaUtils.decryptAtRest(path); + final dir = await getTemporaryDirectory(); + final file = File( + '${dir.path}/shept_send_share_${message.sentAt.microsecondsSinceEpoch}${MediaUtils.extensionForType(message.mediaType ?? MediaType.file)}'); + await file.writeAsBytes(bytes, flush: true); + await SharePlus.instance.share(ShareParams( + files: [XFile(file.path)], + text: message.message.isEmpty ? null : message.message, + )); + await MediaUtils.deleteLocalFile(file.path); + } catch (_) { + Fluttertoast.showToast( + msg: 'shareFailed'.tr(), backgroundColor: Colors.red); + } + } + + /// Save the decrypted attachment wherever the user picks. + static Future save(PrivateMessage message) async { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + return; + } + try { + final bytes = await MediaUtils.decryptAtRest(path); + final saved = await FilePicker.saveFile( + dialogTitle: 'saveAttachment'.tr(), + fileName: message.fileName ?? + 'shept_${message.sentAt.millisecondsSinceEpoch}${MediaUtils.extensionForType(type)}', + bytes: bytes, + ); + if (saved == null) { + return; + } + Fluttertoast.showToast(msg: 'attachmentSaved'.tr()); + } catch (_) { + Fluttertoast.showToast( + msg: 'attachmentSaveFailed'.tr(), backgroundColor: Colors.red); + } + } + + /// Pick a chat (or a user) and send the messages there. + static Future forward( + BuildContext context, List messages) async { + await Navigator.of(context).push(stepRoute(ForwardPage(messages))); + } + + /// Delete the message for this account on every device, after a + /// confirmation. The other side keeps its copy. + static void delete( + BuildContext context, PrivateMessage message, String conversationUserId, + {VoidCallback? onDeleted}) { + DialogUtils.yesNoDialog( + context, + 'deleteMessageConfirm'.tr(), + 'deleteMessageConfirmText'.tr(), + () => _delete(context, message, conversationUserId, + forEveryone: false, onDeleted: onDeleted)); + } + + /// Delete an own message for everyone, after a confirmation: the server + /// erases the ciphertext, so the other side loses it from the archive. + static void deleteForEveryone( + BuildContext context, PrivateMessage message, String conversationUserId, + {VoidCallback? onDeleted}) { + DialogUtils.yesNoDialog( + context, + 'deleteMessageForEveryoneConfirm'.tr(), + 'deleteMessageForEveryoneConfirmText'.tr(), + () => _delete(context, message, conversationUserId, + forEveryone: true, onDeleted: onDeleted)); + } + + /// Removes [message] on the server first, then locally. A failed server call + /// leaves the message alone: a local delete on its own would come back with + /// the next history page. + static Future _delete( + BuildContext context, PrivateMessage message, String conversationUserId, + {required bool forEveryone, VoidCallback? onDeleted}) async { + // A message that never reached the archive has nothing to delete on the + // server; only this device holds it. + final id = message.id; + if (id != null && id.isNotEmpty) { + try { + await Utils.callApi( + () => forEveryone + ? Singleton().messagesApi.deleteMessage(id) + : Singleton().messagesApi.hideMessage(id), + rethrowErr: true); + } catch (_) { + return; + } + } else if (forEveryone) { + await Fluttertoast.showToast( + msg: 'deleteMessageForEveryoneFailed'.tr(), + backgroundColor: Colors.red); + return; + } + if (forEveryone) { + // The row stays as a tombstone: the conversation keeps the place where + // the message was instead of closing the gap. + await CacheUtils.markMessageDeleted( + conversationUserId, message.sentAt, DateTime.now()); + } else { + await CacheUtils.deletePrivateMessage(conversationUserId, message); + } + MessageNotifier().notify(); + onDeleted?.call(); + } +} + +/// Edit dialog that owns its controller. +/// +/// Disposing a controller right after `showDialog` returns races the route's +/// exit animation: the `TextField` is still mounted and the dialog's inherited +/// elements deactivate with a live dependent, which trips +/// `InheritedElement.debugDeactivated` on a phone. +class _EditMessageDialog extends StatefulWidget { + const _EditMessageDialog({required this.initial}); + + final String initial; + + @override + State<_EditMessageDialog> createState() => _EditMessageDialogState(); +} + +class _EditMessageDialogState extends State<_EditMessageDialog> { + late final TextEditingController _controller = + TextEditingController(text: widget.initial); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text('editMessage'.tr()), + content: TextField( + controller: _controller, + autofocus: true, + maxLines: null, + minLines: 1, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('cancel'.tr()), + ), + TextButton( + onPressed: () => Navigator.pop(context, _controller.text), + child: Text('okText'.tr()), + ), + ], + ); + } +} diff --git a/lib/utils/message_format.dart b/lib/utils/message_format.dart new file mode 100644 index 0000000..99821ba --- /dev/null +++ b/lib/utils/message_format.dart @@ -0,0 +1,286 @@ +import 'link_utils.dart'; + +/// Inline formatting of a message body. +/// +/// The subset the app supports: `**bold**`, `*italic*`, `~~strike~~`, +/// `` `mono` ``, ```` ```block``` ```` and `||spoiler||`. Markers do not nest: +/// the first one that closes wins, which keeps the parser small and the result +/// predictable. +enum MessageStyle { + plain, + bold, + italic, + strike, + + /// Inline monospace (single backticks). + mono, + + /// Fenced code block (triple backticks) on its own lines. + code, + + /// Hidden until tapped. + spoiler, +} + +/// What a piece of a message is, for tap handling. +enum MessageKind { + text, + + /// Opens in the browser. + link, + + /// Opens the mail client. + email, + + /// Tapped to copy. + phone, +} + +/// One run of message text with one style and one tap action. +class MessagePiece { + const MessagePiece(this.text, this.style, this.kind); + + final String text; + final MessageStyle style; + final MessageKind kind; +} + +/// Splits [text] into styled, tappable pieces, in order. +List parseMessage(String text) { + if (text.isEmpty) { + return const []; + } + final pieces = []; + for (final segment in _splitCodeBlocks(text)) { + if (segment.block) { + pieces + .add(MessagePiece(segment.text, MessageStyle.code, MessageKind.text)); + } else { + _parseInline(segment.text, pieces); + } + } + return pieces; +} + +/// Whether [text] is only emoji, so it can be shown large and without a bubble. +/// +/// Keycaps (`1️⃣`) and skin-tone modifiers count as emoji. More than +/// [maxLargeEmoji] emoji are still emoji-only, the caller decides the size. +bool isEmojiOnly(String text) { + var emoji = 0; + var significant = 0; + for (final rune in text.runes) { + if (_isEmojiIgnorable(rune)) { + continue; + } + significant++; + if (_isEmojiRune(rune) || _isKeycapBase(rune)) { + if (_isEmojiRune(rune)) { + emoji++; + } + continue; + } + return false; + } + return emoji > 0 && significant > 0; +} + +/// Emoji in a message: used to cap the large rendering. +int emojiCount(String text) => text.runes.where(_isEmojiRune).length; + +// Whitespace, variation selectors, ZWJ and skin-tone modifiers carry no +// meaning on their own. +bool _isEmojiIgnorable(int rune) => + rune == 0x20 || + rune == 0x09 || + rune == 0x0A || + rune == 0x0D || + rune == 0xFE0F || + rune == 0xFE0E || + rune == 0x200D || + (rune >= 0x1F3FB && rune <= 0x1F3FF); + +bool _isEmojiRune(int rune) => + (rune >= 0x1F000 && rune <= 0x1FAFF) || + (rune >= 0x2600 && rune <= 0x27BF) || + (rune >= 0x2B00 && rune <= 0x2BFF) || + (rune >= 0x1F1E6 && rune <= 0x1F1FF) || + rune == 0x2764 || + rune == 0x203C || + rune == 0x2049; + +// Digits, `#` and `*` only appear in emoji when a keycap follows. +bool _isKeycapBase(int rune) => + rune == 0x23 || rune == 0x2A || (rune >= 0x30 && rune <= 0x39); + +class _Segment { + const _Segment(this.text, {required this.block}); + final String text; + final bool block; +} + +/// Splits fenced code blocks out of [text]. An unterminated fence runs to the +/// end of the message. +List<_Segment> _splitCodeBlocks(String text) { + const fence = '```'; + final segments = <_Segment>[]; + var index = 0; + while (true) { + final start = text.indexOf(fence, index); + if (start < 0) { + segments.add(_Segment(text.substring(index), block: false)); + break; + } + segments.add(_Segment(text.substring(index, start), block: false)); + final end = text.indexOf(fence, start + fence.length); + if (end < 0) { + segments.add(_Segment(_trimFence(text.substring(start + fence.length)), + block: true)); + break; + } + segments.add(_Segment(_trimFence(text.substring(start + fence.length, end)), + block: true)); + index = end + fence.length; + } + return segments.where((s) => s.block || s.text.isNotEmpty).toList(); +} + +// The newline that wraps a fence is part of the syntax, not the code. +String _trimFence(String text) { + var value = text; + while (value.startsWith('\n')) { + value = value.substring(1); + } + while (value.endsWith('\n')) { + value = value.substring(0, value.length - 1); + } + return value; +} + +class _Marker { + const _Marker(this.token, this.style); + final String token; + final MessageStyle style; +} + +// Longest first: `**` must win over `*` at the same position. +const List<_Marker> _markers = [ + _Marker('**', MessageStyle.bold), + _Marker('~~', MessageStyle.strike), + _Marker('||', MessageStyle.spoiler), + _Marker('`', MessageStyle.mono), + _Marker('*', MessageStyle.italic), +]; + +void _parseInline(String text, List out) { + final plain = StringBuffer(); + var index = 0; + while (index < text.length) { + _Marker? marker; + var at = -1; + for (final candidate in _markers) { + final found = text.indexOf(candidate.token, index); + if (found >= 0 && (at < 0 || found < at)) { + marker = candidate; + at = found; + } + } + if (marker == null) { + plain.write(text.substring(index)); + break; + } + final contentStart = at + marker.token.length; + final close = text.indexOf(marker.token, contentStart); + if (close <= contentStart) { + // No closing marker (or nothing between them): keep the text literal. + plain.write(text.substring(index, contentStart)); + index = contentStart; + continue; + } + plain.write(text.substring(index, at)); + _flushPlain(plain, out); + out.add(MessagePiece( + text.substring(contentStart, close), marker.style, MessageKind.text)); + index = close + marker.token.length; + } + _flushPlain(plain, out); +} + +void _flushPlain(StringBuffer buffer, List out) { + if (buffer.isEmpty) { + return; + } + out.addAll(_splitEntities(buffer.toString())); + buffer.clear(); +} + +/// Splits plain text into links, e-mail addresses, phone numbers and leftover +/// text. +List _splitEntities(String text) { + final pieces = []; + for (final link in splitLinks(text)) { + if (link.url != null) { + pieces.add(MessagePiece(link.text, MessageStyle.plain, MessageKind.link)); + continue; + } + pieces.addAll(_splitTappable(link.text)); + } + return pieces; +} + +/// Splits plain text into the things a tap can act on. When two patterns start +/// at the same character the one listed first wins. +List _splitTappable(String text) { + final patterns = <(RegExp, MessageKind)>[ + (_emailPattern, MessageKind.email), + (_phonePattern, MessageKind.phone), + ]; + final pieces = []; + var index = 0; + while (index < text.length) { + final rest = text.substring(index); + Match? best; + var kind = MessageKind.text; + for (final (pattern, candidateKind) in patterns) { + final match = pattern.firstMatch(rest); + if (match == null) { + continue; + } + if (candidateKind == MessageKind.phone && + !_isPhoneNumber(match.group(0)!)) { + continue; + } + if (best == null || match.start < best.start) { + best = match; + kind = candidateKind; + } + } + if (best == null) { + pieces.add(MessagePiece( + text.substring(index), MessageStyle.plain, MessageKind.text)); + break; + } + if (best.start > 0) { + pieces.add(MessagePiece(text.substring(index, index + best.start), + MessageStyle.plain, MessageKind.text)); + } + pieces.add(MessagePiece(best.group(0)!, MessageStyle.plain, kind)); + index += best.end; + } + return pieces; +} + +/// A single e-mail address, no display name and no surrounding punctuation. +final RegExp _emailPattern = RegExp( + r'(?= 7 && digits.length <= 15; +} diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index ca451a8..03c08b1 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -1,9 +1,16 @@ +import 'dart:convert'; + import 'package:flutter/material.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/media_download.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; import '../utils/notification_service.dart'; import '../models/private_message.dart'; import '../models/user.dart'; import 'cache_utils.dart'; +import 'media_utils.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -17,13 +24,199 @@ class MessageNotifier extends ChangeNotifier { MessageNotifier._internal(); + /// The media messages of a conversation that the viewer can open, newest + /// first: a local file, a known type, fully downloaded, not voice. Album + /// items are expanded into one entry per attachment. + static List viewableMedia(List messages) { + final media = []; + // A local file is what makes an attachment viewable, not its status: a + // stale failed/expired flag (an old redelivery) used to hide attachments + // that the bubbles and the viewer can still open. + bool viewable(PrivateMessage message) => + message.localPath != null && + message.mediaType != null && + message.mediaType != MediaType.voice; + for (final message in messages) { + if (message.isAlbum) { + for (final item in albumMedia(message)) { + if (viewable(item)) { + media.add(item); + } + } + continue; + } + if (viewable(message)) { + media.add(message); + } + } + media.sort((a, b) => b.sentAt.compareTo(a.sentAt)); + return media; + } + + /// One [PrivateMessage] per album attachment, in album order, so the viewer + /// and the gallery can treat them like single media messages. + static List albumMedia(PrivateMessage message) { + return [ + for (final item in message.album) + PrivateMessage( + message.senderId, + message.message, + message.sentAt, + message.receivedAt, + message.read, + mediaId: item.mediaId, + mediaTypeStr: item.type, + localPath: item.localPath, + mediaSize: item.size, + width: item.width, + height: item.height, + durationMs: item.durationMs, + fileName: item.fileName, + downloadStatus: item.status, + ) + ]; + } + + /// In-memory map of media references awaiting (or having failed) download, + /// keyed by media id. The transport key is intentionally never persisted to + /// disk, so tap-to-retry only works within the current session. + final Map _pendingMediaRefs = {}; + + /// Download, decrypt, store and confirm an incoming media attachment. + /// + /// The encrypted file is fetched over HTTP, decrypted with the transport key + /// from [reference], re-encrypted at rest with the app master key and the + /// owning message is updated. On success the server copy is confirmed (and + /// thus deleted); on failure the message is marked as failed for retry. + Future downloadMediaMessage( + String conversationUserId, MediaReference reference) async { + // A redelivery (history page, sync, reconnect) must not re-fetch an + // attachment we already hold: the server deleted its copy on confirm, so + // the attempt would 404 and mark a working attachment as failed. + if (await CacheUtils.hasMediaLocally( + conversationUserId, reference.mediaId)) { + return; + } + _pendingMediaRefs[reference.mediaId] = reference; + try { + final blob = await Utils.callApi( + () => Singleton().mediaApi.downloadMediaBytes(reference.mediaId), + rethrowErr: true, + ); + if (blob == null) { + throw Exception('empty media download'); + } + final plaintext = await MediaUtils.decryptTransport(blob, reference.key); + final localPath = await MediaUtils.encryptAtRest(plaintext); + await CacheUtils.updatePrivateMessageMedia( + conversationUserId, + reference.mediaId, + localPath: localPath, + downloadStatus: MediaDownloadStatus.ready, + // The reference carries the encrypted size; show the real one. + mediaSize: plaintext.length, + ); + _pendingMediaRefs.remove(reference.mediaId); + notifyListeners(); + // Confirm receipt so the server can delete its copy. + await Utils.callApi( + () => Singleton().mediaApi.confirmMediaDownload(reference.mediaId)); + } catch (e) { + // A 404 means the server no longer has the file (confirmed on another + // device, expired, or the account was cleaned up): retrying cannot work, + // so the message shows a terminal state instead of a retry button. + final expired = e is ApiException && e.code == 404; + if (expired) { + _pendingMediaRefs.remove(reference.mediaId); + } + await CacheUtils.updatePrivateMessageMedia( + conversationUserId, + reference.mediaId, + downloadStatus: + expired ? MediaDownloadStatus.expired : MediaDownloadStatus.failed, + ); + notifyListeners(); + } + } + + /// Retry a previously failed media download (current session only). + Future retryMediaDownload( + String conversationUserId, String mediaId) async { + final reference = _pendingMediaRefs[mediaId]; + if (reference == null) { + return; + } + await CacheUtils.updatePrivateMessageMedia( + conversationUserId, + mediaId, + downloadStatus: MediaDownloadStatus.pending, + ); + notifyListeners(); + await downloadMediaMessage(conversationUserId, reference); + } + + /// Whether a failed media download can be retried this session. + bool canRetryMedia(String mediaId) => _pendingMediaRefs.containsKey(mediaId); + + /// Fetches an attachment whose reference is no longer in memory (after a + /// restart) from what the stored row kept: a single message holds the media + /// envelope, an album item holds its own key. + Future downloadFromStored( + String conversationUserId, PrivateMessage message, String mediaId) async { + final reference = _storedReference(message, mediaId); + if (reference == null) { + return; + } + await CacheUtils.updatePrivateMessageMedia( + conversationUserId, + mediaId, + downloadStatus: MediaDownloadStatus.pending, + ); + notifyListeners(); + await downloadMediaMessage(conversationUserId, reference); + } + + /// Rebuilds one attachment reference from the stored message, null when the + /// row does not carry it (an old build, or a foreign media id). + MediaReference? _storedReference(PrivateMessage message, String mediaId) { + for (final item in message.album) { + if (item.mediaId != mediaId || item.keyB64 == null) { + continue; + } + return MediaReference( + item.mediaId, + base64Decode(item.keyB64!), + MediaType.values.byName(item.type), + item.size, + width: item.width, + height: item.height, + durationMs: item.durationMs, + fileName: item.fileName, + ); + } + final raw = message.mediaRefJson; + if (raw == null || raw.isEmpty) { + return null; + } + try { + final decoded = + MediaReference.fromJson(jsonDecode(raw) as Map); + if (decoded.mediaId == mediaId) { + return decoded; + } + } catch (_) { + // A reference this build cannot read: nothing to retry. + } + return null; + } + /// Add messages to cache - Future addMessages(int userId, List messages) async { + Future addMessages(String userId, List messages) async { // Check if users exist for (var msg in messages) { if (!await CacheUtils.userExists(msg.senderId)) { - var user = - await Utils.callApi(() => Singleton().userApi.getUserById(msg.senderId)); + var user = await Utils.callApi( + () => Singleton().userApi.getUserById(msg.senderId)); if (user != null) { // Save user to cache await CacheUtils.addUser(User.fromModel(user)); @@ -36,9 +229,15 @@ class MessageNotifier extends ChangeNotifier { } /// Get all messages by user ID - Future> getMessages(int userId) async { - var messages = await CacheUtils.getPrivateMessages(userId, markAsRead: true); - await NotificationService().removeNotificationsById(messages.map((x) => x.notificationId).toList()); + Future> getMessages(String userId) async { + var messages = + await CacheUtils.getPrivateMessages(userId, markAsRead: true); + await NotificationService().removeNotificationsById( + messages.map((x) => x.notificationId).toList()); + // The read flags just changed in the cache. Nothing else tells the Home + // list, so the unread row would stay bold after leaving the chat. The chat + // page's own listener is skipped: it is still inside `_loadMessages`. + notifyListeners(); return messages; } @@ -50,8 +249,8 @@ class MessageNotifier extends ChangeNotifier { for (var e in messages.entries) { // User does not exists in cache if (!e.key.isInBox) { - var user = - await Utils.callApi(() => Singleton().userApi.getUserById(e.key.id)); + var user = await Utils.callApi( + () => Singleton().userApi.getUserById(e.key.id)); if (user != null) { // Save user to cache await CacheUtils.addUser(User.fromModel(user)); @@ -64,10 +263,9 @@ class MessageNotifier extends ChangeNotifier { newMessages[e.key] = e.value; } } - // Sort conversations by last message date - var sortedEntries = newMessages.entries.toList() - ..sort((a, b) => b.value.receivedAt.compareTo(a.value.receivedAt)); - return Map.fromEntries(sortedEntries); + // The cache already ordered this map (pinned chats first, then by the + // newest message), so the entries are kept in the order they came in. + return newMessages; } /// Delete all chats @@ -77,9 +275,24 @@ class MessageNotifier extends ChangeNotifier { } /// Delete chat by user ID - Future deleteChat(int userId) async { + /// Deletes the conversation for this account on every device: the server + /// stops returning it, then this device drops what it holds. A failed call + /// leaves everything in place, because a local wipe alone would come back + /// with the next archive page. + /// + /// @return bool whether the server confirmed the delete + Future deleteChat(String userId) async { + final cleared = await Utils.callApi( + () => Singleton().messagesApi.clearConversation(userId), + showError: true); + final cut = cleared?.clearedAt; + if (cut == null) { + return false; + } await CacheUtils.deletePrivateMessagesWithUser(userId); + await CacheUtils.applyConversationClearedAt(userId, cut.toLocal()); notifyListeners(); + return true; } void notify() { diff --git a/lib/utils/message_search.dart b/lib/utils/message_search.dart new file mode 100644 index 0000000..3420843 --- /dev/null +++ b/lib/utils/message_search.dart @@ -0,0 +1,113 @@ +import '../models/private_message.dart'; + +/// One stored message that matched a search, with the conversation it belongs +/// to (the other side's user id, not the sender: an archived message we sent +/// lives in the peer's conversation). +class MessageHit { + const MessageHit(this.conversationId, this.message); + + final String conversationId; + final PrivateMessage message; +} + +/// What to look for in one conversation's local history. +/// +/// The store holds decrypted text, so a search is a local scan: nothing leaves +/// the device and no server round-trip happens. +class MessageSearchQuery { + const MessageSearchQuery({this.text = '', this.conversationId}); + + /// Case-insensitive substring of the message text (or of a file name). + final String text; + + /// Restricts the search to one conversation. + final String? conversationId; + + /// Whether this query filters anything out at all. + bool get isEmpty => text.trim().isEmpty; + + bool matches(MessageHit hit) { + if (conversationId != null && hit.conversationId != conversationId) { + return false; + } + final needle = text.trim().toLowerCase(); + if (needle.isEmpty) { + return true; + } + final message = hit.message; + // An attachment without a caption is still findable by its file name. + return message.message.toLowerCase().contains(needle) || + (message.fileName ?? '').toLowerCase().contains(needle); + } +} + +/// How many hits a search returns. A single letter must not walk the whole +/// history into a list. +const int searchResultLimit = 300; + +/// Applies [query] to [hits] and returns the newest first. +List filterMessages( + Iterable hits, MessageSearchQuery query) { + final matched = hits.where(query.matches).toList() + ..sort((a, b) => b.message.sentAt.compareTo(a.message.sentAt)); + return matched.length > searchResultLimit + ? matched.sublist(0, searchResultLimit) + : matched; +} + +/// A window of [text] around the first occurrence of [needle], for the result +/// list. Returns [text] when the needle is not in it. +String snippet(String text, String needle, {int radius = 40}) { + final trimmed = needle.trim(); + if (trimmed.isEmpty) { + return text.length <= radius * 2 + ? text + : '${text.substring(0, radius * 2)}…'; + } + final at = text.toLowerCase().indexOf(trimmed.toLowerCase()); + if (at < 0) { + return text.length <= radius * 2 + ? text + : '${text.substring(0, radius * 2)}…'; + } + var start = at - radius; + var end = at + trimmed.length + radius; + if (start < 0) { + start = 0; + } + if (end > text.length) { + end = text.length; + } + final prefix = start > 0 ? '…' : ''; + final suffix = end < text.length ? '…' : ''; + return '$prefix${text.substring(start, end)}$suffix'; +} + +/// Splits [text] into alternating plain and matched runs, so a result can show +/// what it found. Case-insensitive; every occurrence is marked. +List<({String text, bool match})> highlightParts(String text, String needle) { + final plain = [(text: text, match: false)]; + final trimmed = needle.trim(); + if (trimmed.isEmpty || text.isEmpty) { + return plain; + } + final lowered = text.toLowerCase(); + final target = trimmed.toLowerCase(); + final parts = <({String text, bool match})>[]; + var index = 0; + while (true) { + final at = lowered.indexOf(target, index); + if (at < 0) { + if (index < text.length) { + parts.add((text: text.substring(index), match: false)); + } + break; + } + if (at > index) { + parts.add((text: text.substring(index, at), match: false)); + } + parts.add((text: text.substring(at, at + target.length), match: true)); + index = at + target.length; + } + return parts.isEmpty ? plain : parts; +} diff --git a/lib/utils/nav_transitions.dart b/lib/utils/nav_transitions.dart new file mode 100644 index 0000000..cf1ecbc --- /dev/null +++ b/lib/utils/nav_transitions.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; +import 'package:page_transition/page_transition.dart'; + +/// Shared navigation timing: fast start, soft landing. +const Duration navDuration = Duration(milliseconds: 200); +const Curve navCurve = Curves.easeOutCubic; + +/// Opens a conversation: the new page rises from the bottom. +/// +/// Deliberately not `bottomToTopJoined` — the joined variants need the +/// previous page as a widget and mount it a second time, which restarts its +/// `initState` (cache scans, network calls) while the transition animates. +Route slideUpRoute(Widget child) { + return PageTransition( + type: PageTransitionType.bottomToTop, + child: child, + duration: navDuration, + reverseDuration: navDuration, + curve: navCurve, + ); +} + +/// Opens a secondary page: the content cross-fades, nothing large slides. +Route fadeRoute(Widget child) { + return PageTransition( + type: PageTransitionType.fade, + child: child, + duration: navDuration, + reverseDuration: navDuration, + curve: navCurve, + ); +} + +/// Opens the next step of a flow (forwarding, onboarding): it comes in from +/// the side, the way a form usually does. +Route stepRoute(Widget child) { + return PageTransition( + type: PageTransitionType.rightToLeft, + child: child, + duration: navDuration, + reverseDuration: navDuration, + curve: navCurve, + ); +} diff --git a/lib/utils/notification_service.dart b/lib/utils/notification_service.dart index 4f5556a..57a5e93 100644 --- a/lib/utils/notification_service.dart +++ b/lib/utils/notification_service.dart @@ -1,29 +1,91 @@ import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:sprintf/sprintf.dart'; import '../utils/cache_utils.dart'; import '../models/user.dart'; import '../models/private_message.dart'; +import 'singleton.dart'; // https://www.scaler.com/topics/flutter-local-notification/ class NotificationService { + /// Set by HomePage while it is alive, so a tap on a single message + /// notification can open the chat immediately instead of being queued. + static void Function(String userId)? onChatSelected; + final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); /// Init notification settings Future init() async { const AndroidInitializationSettings initializationSettingsAndroid = - AndroidInitializationSettings('app_icon'); + AndroidInitializationSettings('ic_stat_shept'); + final LinuxInitializationSettings initializationSettingsLinux = + LinuxInitializationSettings( + defaultActionName: 'shept_message', + defaultIcon: ThemeLinuxIcon('mail-unread'), + ); + // Asks for alert/badge/sound permission on iOS and macOS. + const DarwinInitializationSettings initializationSettingsDarwin = + DarwinInitializationSettings(); final InitializationSettings initializationSettings = - InitializationSettings(android: initializationSettingsAndroid); + InitializationSettings( + android: initializationSettingsAndroid, + iOS: initializationSettingsDarwin, + macOS: initializationSettingsDarwin, + linux: initializationSettingsLinux); + + await _flutterLocalNotificationsPlugin.initialize( + settings: initializationSettings, + onDidReceiveNotificationResponse: _onNotificationTap); + + // Tapping a notification while the app was closed launches it through here + // (Android only, the Linux implementation does not support it). + if (defaultTargetPlatform == TargetPlatform.android) { + final launchDetails = await _flutterLocalNotificationsPlugin + .getNotificationAppLaunchDetails(); + if (launchDetails?.didNotificationLaunchApp ?? false) { + _setPendingChat(launchDetails!.notificationResponse?.payload); + } + } - await _flutterLocalNotificationsPlugin.initialize(initializationSettings); + // FCM posts notifications into this channel, so it must exist before a push arrives + await _flutterLocalNotificationsPlugin + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin>() + ?.createNotificationChannel(AndroidNotificationChannel( + 'shept_firebase_messages', + 'Shept', + description: 'notificationChannelDesc'.tr(), + importance: Importance.max, + sound: const RawResourceAndroidNotificationSound('notification'), + )); + } + + /// Remember the chat a notification points at. The app may still be locked, + /// so HomePage opens it once it is on screen (i.e. after unlocking). + void _onNotificationTap(NotificationResponse response) => + _setPendingChat(response.payload); + + /// The payload of a single message notification is the sender id; grouped + /// notifications carry none and just open HomePage. + void _setPendingChat(String? payload) { + final userId = payload ?? ''; + if (userId.isEmpty) { + return; + } + final onChatSelected = NotificationService.onChatSelected; + if (onChatSelected != null) { + onChatSelected(userId); + return; + } + Singleton().pendingChatUserId = userId; } /// Show notifications. Future showMessagesNotification(List messages) async { - final Map> groupedMessagesById = {}; + final Map> groupedMessagesById = {}; for (var message in messages) { if (!groupedMessagesById.containsKey(message.senderId)) { groupedMessagesById[message.senderId] = []; @@ -44,14 +106,17 @@ class NotificationService { } // More messages if (messages.length > 1) { - final lines = getGroupedNotificationLines(groupedMessagesByUser); + final preview = await CacheUtils.getNotificationPreview(); + final lines = preview + ? getGroupedNotificationLines(groupedMessagesByUser) + : ['newMessageBody'.tr()]; final groupedPlatformChannelSpecifics = await groupedNotificationDetails( lines, groupedMessagesByUser.keys.length, messages.length); await _flutterLocalNotificationsPlugin.show( - messages.last.notificationId, - 'newMessagesTitle'.tr(), - 'newMessagesBody'.tr(), - groupedPlatformChannelSpecifics, + id: messages.last.notificationId, + title: 'newMessagesTitle'.tr(), + body: 'newMessagesBody'.tr(), + notificationDetails: groupedPlatformChannelSpecifics, ); } } @@ -66,7 +131,7 @@ class NotificationService { // Sort messages userMessages.sort((a, b) => b.receivedAt.compareTo(a.receivedAt)); return userMessages - .map((message) => '${user.username}: ${message.message}'); + .map((message) => '${user.username}: ${message.preview}'); }) .toList() .reversed @@ -81,8 +146,8 @@ class NotificationService { 'xMessagesFromYChats'.tr(), [totalMessageCount, chatCount])); AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( - 'whisperLocalNotificationMultipleMessages', - 'whisperLocalNotificationMultipleMessages'.tr(), + 'sheptLocalNotificationMultipleMessages', + 'sheptLocalNotificationMultipleMessages'.tr(), groupKey: 'cz.josefraz.flutter_push_notifications_multiple_messages', channelDescription: 'notificationChannelDesc'.tr(), setAsGroupSummary: true, @@ -105,11 +170,14 @@ class NotificationService { Future showMessageNotification(PrivateMessage message) async { var user = await CacheUtils.getUserById(message.senderId) ?? User(message.senderId, '', '', false); + // The text is decrypted; the user decides whether the lock screen shows it. + final preview = await CacheUtils.getNotificationPreview(); + final body = preview ? message.preview : 'newMessageBody'.tr(); AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( - 'whisperLocalNotificationSingleMessage', - 'whisperLocalNotificationSingleMessage'.tr(), + 'sheptLocalNotificationSingleMessage', + 'sheptLocalNotificationSingleMessage'.tr(), groupKey: 'cz.josefraz.flutter_push_notifications_single_message', channelDescription: 'notificationChannelDesc'.tr(), importance: Importance.max, @@ -118,14 +186,43 @@ class NotificationService { enableVibration: true, playSound: true, sound: RawResourceAndroidNotificationSound('notification'), + // Message previews are long, don't let Android truncate them + styleInformation: BigTextStyleInformation(body), ); NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics); await _flutterLocalNotificationsPlugin.show( - message.notificationId, - user.username, - message.message, - platformChannelSpecifics, + id: message.notificationId, + title: user.username, + body: body, + notificationDetails: platformChannelSpecifics, + payload: message.senderId.toString(), + ); + } + + /// Show a server-side security notice, e.g. a login from another device. + /// + /// It carries no message content and no payload: tapping it only opens the + /// app, the device list is where the action happens. + Future showSecurityNotification(String title, String body) async { + AndroidNotificationDetails androidPlatformChannelSpecifics = + AndroidNotificationDetails( + 'sheptLocalNotificationSecurity', + 'sheptLocalNotificationSecurity'.tr(), + channelDescription: 'notificationChannelDesc'.tr(), + importance: Importance.high, + priority: Priority.high, + ticker: 'tickerLocalNotification'.tr(), + enableVibration: true, + playSound: true, + sound: RawResourceAndroidNotificationSound('notification'), + ); + await _flutterLocalNotificationsPlugin.show( + id: title.hashCode & 0x7fffffff, + title: title, + body: body, + notificationDetails: + NotificationDetails(android: androidPlatformChannelSpecifics), ); } @@ -136,7 +233,7 @@ class NotificationService { for (var id in ids) { for (var notification in activeNotifications) { if (notification.id == id) { - await _flutterLocalNotificationsPlugin.cancel(id); + await _flutterLocalNotificationsPlugin.cancel(id: id); } } } diff --git a/lib/utils/playback_lock.dart b/lib/utils/playback_lock.dart new file mode 100644 index 0000000..2635e2d --- /dev/null +++ b/lib/utils/playback_lock.dart @@ -0,0 +1,19 @@ +import 'package:flutter/foundation.dart'; + +/// Only one source may play at a time (voice messages and the video viewer). +/// +/// Whoever starts playing claims the lock; every other player pauses itself +/// when the owner changes. +class PlaybackLock { + PlaybackLock._(); + + static final ValueNotifier owner = ValueNotifier(null); + + static void claim(Object source) => owner.value = source; + + static void release(Object source) { + if (identical(owner.value, source)) { + owner.value = null; + } + } +} diff --git a/lib/utils/playback_speed.dart b/lib/utils/playback_speed.dart new file mode 100644 index 0000000..703b0f7 --- /dev/null +++ b/lib/utils/playback_speed.dart @@ -0,0 +1,13 @@ +/// Playback speeds the voice player cycles through. +const List playbackSpeeds = [1.0, 1.5, 2.0]; + +/// Next speed in the cycle; an unknown value falls back to the first one. +double nextSpeed(double current) { + final index = playbackSpeeds.indexOf(current); + return playbackSpeeds[(index + 1) % playbackSpeeds.length]; +} + +/// Label of the cycle button: `1x`, `1.5x`, `2x`. +String speedLabel(double speed) { + return speed == speed.roundToDouble() ? '${speed.toInt()}x' : '${speed}x'; +} diff --git a/lib/utils/presence.dart b/lib/utils/presence.dart new file mode 100644 index 0000000..4860ca6 --- /dev/null +++ b/lib/utils/presence.dart @@ -0,0 +1,159 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; + +import 'live_location.dart'; + +/// Live, in-memory status of the other participants: who is online, when they +/// were last seen and whether they are typing. Nothing here is stored, and the +/// server keeps no presence either, so a restart or a disconnect empties it. +class PresenceNotifier extends ChangeNotifier { + PresenceNotifier._(); + + static final PresenceNotifier instance = PresenceNotifier._(); + + /// How long a typing hint stays visible after the last frame. The sender + /// repeats it while typing, so there is no "stopped typing" frame. + Duration typingTtl = const Duration(seconds: 5); + + /// How long an "online" stays believable without a new announcement. The + /// sender repeats it every minute, so an app that is killed instead of paused + /// drops off on its own. + Duration presenceTtl = const Duration(seconds: 95); + + final Map _lastSeen = {}; + final Map _presenceTimers = {}; + final Map _typingUntil = {}; + final Map _typingTimers = {}; + final Map _online = {}; + + /// Live positions shared with this device, dropped at their own deadline. + final Map _live = {}; + final Map _liveTimers = {}; + + /// When each session was first seen here, so its bubble sits at that instant + /// in the conversation instead of being pinned to the bottom. + final Map _liveStarted = {}; + + /// The position [peerId] is sharing right now, null when they are not. + LiveLocationPoint? liveLocation(String peerId) { + final point = _live[peerId]; + if (point == null || point.until.isBefore(DateTime.now())) { + return null; + } + return point; + } + + /// When the live session of [peerId] started here, null without one. + DateTime? liveStartedAt(String peerId) => _liveStarted[peerId]; + + /// Keeps one relayed position and forgets it at its deadline. A point that + /// is already expired is the sender saying "stopped": it clears the session + /// instead of showing a stale position. + void applyLiveLocation(String peerId, LiveLocationPoint point) { + if (!point.until.isAfter(DateTime.now())) { + _liveTimers.remove(peerId)?.cancel(); + _live.remove(peerId); + _liveStarted.remove(peerId); + notifyListeners(); + return; + } + _live[peerId] = point; + _liveStarted.putIfAbsent(peerId, () => DateTime.now()); + _liveTimers.remove(peerId)?.cancel(); + final left = point.until.difference(DateTime.now()); + _liveTimers[peerId] = Timer(left.isNegative ? Duration.zero : left, () { + _live.remove(peerId); + _liveStarted.remove(peerId); + _liveTimers.remove(peerId); + notifyListeners(); + }); + notifyListeners(); + } + + /// True when [peerId] is known to be online; null when nothing is known. + bool? isOnline(String peerId) => _online[peerId]; + + /// When [peerId] was last seen, null while unknown. + DateTime? lastSeen(String peerId) => _lastSeen[peerId]; + + /// Whether [peerId] is typing right now. + bool isTyping(String peerId) { + final until = _typingUntil[peerId]; + return until != null && until.isAfter(DateTime.now()); + } + + /// Applies one presence frame. Going offline carries the instant the server + /// saw it, which is the only last seen this client ever gets. + void applyPresence(String peerId, + {required bool online, DateTime? lastSeenAt}) { + _online[peerId] = online; + _presenceTimers.remove(peerId)?.cancel(); + if (online) { + _lastSeen.remove(peerId); + _presenceTimers[peerId] = Timer(presenceTtl, () { + // Silence means the peer lost the network or was killed: nobody will + // announce it, so the badge expires instead of lying. + _online[peerId] = false; + _lastSeen[peerId] = DateTime.now(); + _presenceTimers.remove(peerId); + notifyListeners(); + }); + } else if (lastSeenAt != null) { + _lastSeen[peerId] = lastSeenAt.toLocal(); + } + notifyListeners(); + } + + /// Applies one typing hint and clears it again on its own after + /// [typingTtl]. + void applyTyping(String peerId) { + _typingUntil[peerId] = DateTime.now().add(typingTtl); + _typingTimers.remove(peerId)?.cancel(); + _typingTimers[peerId] = Timer(typingTtl, () { + _typingUntil.remove(peerId); + _typingTimers.remove(peerId); + notifyListeners(); + }); + notifyListeners(); + } + + /// Drops everything: without a connection nothing here is known anymore. + void clear() { + for (final timer in _typingTimers.values) { + timer.cancel(); + } + for (final timer in _presenceTimers.values) { + timer.cancel(); + } + for (final timer in _liveTimers.values) { + timer.cancel(); + } + _typingTimers.clear(); + _presenceTimers.clear(); + _liveTimers.clear(); + _typingUntil.clear(); + _online.clear(); + _lastSeen.clear(); + _live.clear(); + _liveStarted.clear(); + notifyListeners(); + } + + /// One line under a name: typing wins over online, online over last seen. + /// Null when nothing is known, so the caller keeps the plain name. + String? statusText(String peerId) { + if (isTyping(peerId)) { + return 'typing'.tr(); + } + if (_online[peerId] == true) { + return 'online'.tr(); + } + final seen = _lastSeen[peerId]; + if (seen != null) { + return 'lastSeenAt'.tr(args: [DateFormat.Hm().format(seen)]); + } + return null; + } +} diff --git a/lib/utils/round_note_playback.dart b/lib/utils/round_note_playback.dart new file mode 100644 index 0000000..8e301c6 --- /dev/null +++ b/lib/utils/round_note_playback.dart @@ -0,0 +1,213 @@ +import 'package:flutter/widgets.dart'; +import 'package:video_player/video_player.dart'; + +import 'media_autoplay.dart'; +import 'playback_lock.dart'; + +/// Whether the note needs its floating copy: it is live (playing, or paused +/// from the copy itself) and mostly out of the chat's viewport. +bool shouldPin({required bool active, required double visibleFraction}) => + active && visibleFraction < 0.5; + +/// Share of [note] that is inside [viewport]: 0 when it is fully out of sight, +/// 1 when the whole circle is on screen. +double visibleFraction(Rect note, Rect viewport) { + if (note.height <= 0) { + return 0; + } + final inside = note.intersect(viewport); + if (inside.height <= 0) { + return 0; + } + return (inside.height / note.height).clamp(0.0, 1.0); +} + +/// The note's rect as it will sit once a rubber-band bounce settles: the list +/// follows the finger while stretched, so the stretch is taken out of the +/// measurement and the floating copy does not blink with the bounce. +Rect settledNoteRect( + Rect note, { + required double overscroll, + required bool reversed, +}) => + overscroll == 0 + ? note + : note.shift(Offset(0, reversed ? overscroll : -overscroll)); + +/// The one round note that is live in the open chat. +/// +/// The inline circle keeps owning its player - it is the only thing that can +/// give the note a first frame before it is played - and this holds a reference +/// to it: it says which note is live, how much of it is on screen, and hands +/// the player to the floating copy. The two views therefore never restart the +/// video, and two notes can never play at once. +class RoundNotePlayback extends ChangeNotifier { + String? _key; + String? _conversationId; + DateTime? _sentAt; + VideoPlayerController? _controller; + double _visibleFraction = 1; + bool _active = false; + bool _chained = false; + bool _lastPlaying = false; + bool _disposed = false; + + /// Key of the note that is live, null when nothing is playing any more. + String? get key => _key; + + /// The player of the live note; the floating copy renders this one. + VideoPlayerController? get controller => _controller; + + bool get playing => _controller?.value.isPlaying ?? false; + + /// Started and not finished or dismissed yet: the note is still "the one". + bool get active => _active; + + /// The note is (mostly) out of sight and needs the floating copy. + bool get pinned => + shouldPin(active: _active, visibleFraction: _visibleFraction); + + /// Makes [key] the live note and starts it, resuming a paused one. + Future start({ + required String key, + required String conversationId, + required DateTime sentAt, + required VideoPlayerController controller, + }) async { + if (_key != key || !identical(_controller, controller)) { + final previous = _controller; + if (previous != null && !identical(previous, controller)) { + previous.removeListener(_onValue); + await previous.pause(); + } + _key = key; + _conversationId = conversationId; + _sentAt = sentAt; + _controller = controller; + _visibleFraction = 1; + _chained = false; + controller.addListener(_onValue); + } + _active = true; + PlaybackLock.claim(this); + if (controller.value.position >= controller.value.duration) { + await controller.seekTo(Duration.zero); + } + await controller.play(); + _notify(); + } + + Future pause() async { + await _controller?.pause(); + _notify(); + } + + Future resume() async { + final controller = _controller; + if (controller == null) { + return; + } + _active = true; + PlaybackLock.claim(this); + await controller.play(); + _notify(); + } + + Future toggle() => playing ? pause() : resume(); + + /// The floating copy was swiped away: playback stops and the note is no + /// longer the live one until the user starts it again. + Future dismiss() async { + final controller = _controller; + if (controller == null) { + return; + } + await controller.pause(); + await controller.seekTo(Duration.zero); + PlaybackLock.release(this); + _active = false; + _notify(); + } + + /// How much of [key] is on screen. Only a change of the pin itself is worth a + /// rebuild: this is called on every scroll frame. + void updateVisibility(String key, double fraction) { + if (_key != key) { + return; + } + final wasPinned = pinned; + _visibleFraction = fraction; + if (pinned != wasPinned) { + _notify(); + } + } + + /// The inline circle is gone: forget the player and stop it. + void detach(String key) { + if (_key != key) { + return; + } + final controller = _controller; + controller?.removeListener(_onValue); + controller?.pause(); + _controller = null; + _key = null; + _active = false; + _notify(); + } + + void _onValue() { + final controller = _controller; + if (controller == null) { + return; + } + final value = controller.value; + if (value.position >= value.duration && value.duration > Duration.zero) { + controller.pause(); + controller.seekTo(Duration.zero); + PlaybackLock.release(this); + _active = false; + // One request per playback: a repeated end-of-video event must not restart + // the chain. + if (!_chained) { + _chained = true; + MediaAutoplay.nextRoundNote(_conversationId!, _sentAt!); + } + _notify(); + return; + } + if (value.isPlaying != _lastPlaying) { + _lastPlaying = value.isPlaying; + _notify(); + } + } + + void _notify() { + if (!_disposed) { + notifyListeners(); + } + } + + @override + void dispose() { + _disposed = true; + _controller?.removeListener(_onValue); + PlaybackLock.release(this); + super.dispose(); + } +} + +/// Gives the chat's [RoundNotePlayback] to the circles inside the list. +class RoundNoteScope extends InheritedNotifier { + const RoundNoteScope({ + required RoundNotePlayback playback, + required super.child, + super.key, + }) : super(notifier: playback); + + static RoundNotePlayback of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()!.notifier!; + + static RoundNotePlayback? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.notifier; +} diff --git a/lib/utils/round_video_recorder.dart b/lib/utils/round_video_recorder.dart new file mode 100644 index 0000000..bb0bfaf --- /dev/null +++ b/lib/utils/round_video_recorder.dart @@ -0,0 +1,93 @@ +import 'dart:io'; + +import 'package:camera/camera.dart'; + +/// Records the round video note started by holding down the composer's camera +/// button. +/// +/// The chat page owns the camera for the few seconds the finger is down, shows +/// the circle above the composer and hands the file over when it is released. +class RoundVideoRecorder { + /// Longest note. A note is a glance, not a video message. + static const Duration maxLength = Duration(seconds: 60); + + CameraController? _controller; + bool _recording = false; + + CameraController? get controller => _controller; + + bool get isReady => _controller?.value.isInitialized ?? false; + + /// Opens the front camera and starts recording. False when there is no camera + /// or it cannot be opened (permission, busy). + Future start() async { + try { + final cameras = await availableCameras(); + if (cameras.isEmpty) { + return false; + } + // A note is a message to a person, not a recording of the room. + final front = cameras.firstWhere( + (camera) => camera.lensDirection == CameraLensDirection.front, + orElse: () => cameras.first, + ); + final controller = + CameraController(front, ResolutionPreset.medium, enableAudio: true); + await controller.initialize(); + _controller = controller; + await controller.startVideoRecording(); + _recording = true; + return true; + } catch (_) { + await dispose(); + return false; + } + } + + /// Stops and returns the recorded file, or null when nothing was recorded. + Future stop() async { + final controller = _controller; + if (controller == null || !_recording) { + await dispose(); + return null; + } + _recording = false; + try { + final captured = await controller.stopVideoRecording(); + final file = File(captured.path); + await dispose(); + return file; + } catch (_) { + await dispose(); + return null; + } + } + + /// Stops and throws the recording away. + Future cancel() async { + final controller = _controller; + if (controller != null && _recording) { + _recording = false; + try { + final captured = await controller.stopVideoRecording(); + await File(captured.path) + .delete() + .catchError((_) => File(captured.path)); + } catch (_) { + // Nothing to keep. + } + } + await dispose(); + } + + Future dispose() async { + final controller = _controller; + _controller = null; + _recording = false; + try { + await controller?.dispose(); + } catch (_) { + // The platform side may already be gone. + } + } +} diff --git a/lib/utils/screen_guard.dart b/lib/utils/screen_guard.dart new file mode 100644 index 0000000..c461ee7 --- /dev/null +++ b/lib/utils/screen_guard.dart @@ -0,0 +1,46 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// The platform half of screenshot handling: blocking the screen of a view-once +/// attachment and reporting screenshots taken elsewhere. Android is the only +/// target where the block is enforceable, so on every other platform both calls +/// are a no-op. +class ScreenGuard { + static const MethodChannel _channel = MethodChannel('shept/secure_screen'); + + /// Called when the platform noticed a screenshot. + static VoidCallback? onScreenshot; + + /// Wires the native callback once, at startup. + static Future start() async { + _channel.setMethodCallHandler((call) async { + if (call.method == 'onScreenshot') { + onScreenshot?.call(); + } + return null; + }); + } + + /// Makes the current window invisible to screenshots and recordings. + static Future enableSecure() async { + await _invoke('enableSecure'); + } + + /// Gives the screen back once the secure view is gone. + static Future disableSecure() async { + await _invoke('disableSecure'); + } + + static Future _invoke(String method) async { + if (defaultTargetPlatform != TargetPlatform.android) { + return; + } + try { + await _channel.invokeMethod(method); + } on MissingPluginException { + // A build without the native side still runs; it just cannot block. + } on PlatformException { + // Nothing to do: the block is a best effort on the platform side. + } + } +} diff --git a/lib/utils/share_intent.dart b/lib/utils/share_intent.dart new file mode 100644 index 0000000..afb20c9 --- /dev/null +++ b/lib/utils/share_intent.dart @@ -0,0 +1,151 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:receive_sharing_intent/receive_sharing_intent.dart'; + +import '../models/user.dart'; +import '../pages/chat_page.dart'; +import 'app_navigator.dart'; +import 'cache_utils.dart'; +import 'chat_sender.dart'; +import 'media_utils.dart'; + +/// Receives pictures, videos and files shared from other apps. +/// +/// The picked chat decides where the files go; nothing is sent before the user +/// picks one, so a share into the app cannot become a message to the wrong +/// person. +class SharedInbox { + SharedInbox._(); + + /// How many shared files one message may carry. + static const int maxFiles = 10; + + static bool _started = false; + + /// Starts listening for inbound shares: once for a cold start, and then for + /// every share while the app runs. + /// + /// Called from Home, never from [main]: a share that arrives while the app is + /// still locked must not open a contact picker over the password screen. + static Future start() async { + if (_started) { + return; + } + _started = true; + try { + final initial = await ReceiveSharingIntent.instance.getInitialMedia(); + if (initial.isNotEmpty) { + ReceiveSharingIntent.instance.reset(); + await _offer(initial); + } + ReceiveSharingIntent.instance.getMediaStream().listen((shared) { + if (shared.isNotEmpty) { + _offer(shared); + } + }); + } catch (_) { + // A platform without share intents simply has no inbox. + } + } + + static Future _offer(List shared) async { + final navigator = appNavigatorKey.currentState; + if (navigator == null) { + return; + } + final users = await CacheUtils.getAllUsers(); + if (users.isEmpty) { + return; + } + final target = await showModalBottomSheet( + context: navigator.context, + showDragHandle: true, + builder: (ctx) => SafeArea( + child: ListView( + shrinkWrap: true, + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Text('shareToChat'.tr(), + style: Theme.of(ctx).textTheme.titleMedium), + ), + for (final user in users) + ListTile( + leading: CircleAvatar( + backgroundColor: user.avatarColor, + child: Text(user.username.isEmpty + ? '?' + : user.username[0].toUpperCase()), + ), + title: Text(user.username), + onTap: () => Navigator.pop(ctx, user), + ), + ], + ), + ), + ); + if (target == null) { + return; + } + await _send(target, shared.take(maxFiles).toList()); + } + + static Future _send(User target, List shared) async { + try { + // A shared link or a line of text arrives as its own item and is a plain + // message; only real files go through the media pipeline. + final texts = shared + .where((item) => + item.type == SharedMediaType.text || + item.type == SharedMediaType.url) + .map((item) => item.path.trim()) + .where((text) => text.isNotEmpty); + for (final text in texts) { + await ChatSender.sendText(target, text); + } + + final files = shared + .where((item) => + item.type != SharedMediaType.text && + item.type != SharedMediaType.url) + .take(maxFiles) + .toList(); + if (files.length == 1) { + final file = File(files.single.path); + final bytes = await file.readAsBytes(); + if (!MediaUtils.uploadFits(bytes.length)) { + throw Exception('fileTooLarge'.tr()); + } + await ChatSender.sendMedia( + target, MediaUtils.detectType(file.path), bytes, + fileName: MediaUtils.baseName(file.path)); + } else if (files.isNotEmpty) { + final attachments = []; + for (final item in files) { + final file = File(item.path); + final bytes = await file.readAsBytes(); + if (!MediaUtils.uploadFits(bytes.length)) { + continue; + } + attachments.add(OutgoingAttachment( + type: MediaUtils.detectType(file.path), + bytes: bytes, + fileName: MediaUtils.baseName(file.path), + )); + } + if (attachments.isEmpty) { + throw Exception('fileTooLarge'.tr()); + } + await ChatSender.sendAlbum(target, attachments); + } + appNavigatorKey.currentState + ?.push(MaterialPageRoute(builder: (_) => ChatPage(target))); + } catch (e) { + await Fluttertoast.showToast( + msg: e.toString(), backgroundColor: Colors.red); + } + } +} diff --git a/lib/utils/singleton.dart b/lib/utils/singleton.dart index 7e81fbf..e65f175 100644 --- a/lib/utils/singleton.dart +++ b/lib/utils/singleton.dart @@ -1,9 +1,13 @@ +import 'dart:io'; + import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:http/io_client.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; -import 'package:whisper_websocket_client_dart/ws_client.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import 'package:shept_websocket_client_dart/ws_client.dart'; import '../models/app_theme.dart'; +import 'version.dart'; import '../models/profile.dart'; import 'package:flutter/foundation.dart'; @@ -23,6 +27,8 @@ class Singleton { late WsClient wsClient; // Current route late Route currentRoute; + // Chat a notification tap asked for, opened by HomePage once it is shown + String? pendingChatUserId; // Offline mode bool _offlineMode = false; @@ -38,7 +44,22 @@ class Singleton { set apiToken(String token) { var auth = HttpBearerAuth(); auth.accessToken = Singleton().profile.accessToken; - _api = ApiClient(basePath: Singleton().profile.url, authentication: auth); + _api = createApiClient(Singleton().profile.url, authentication: auth); + } + + /// API client with connection and idle timeouts. + /// + /// The generated client has no timeout of its own, so a stalled server would + /// leave a future pending forever (a media bubble stuck on "downloading"). + static ApiClient createApiClient(String basePath, + {Authentication? authentication}) { + final httpClient = HttpClient() + ..connectionTimeout = const Duration(seconds: 15) + ..idleTimeout = const Duration(seconds: 30); + return ApiClient(basePath: basePath, authentication: authentication) + ..client = IOClient(httpClient) + // Every request names the app version; the login gate reads it. + ..addDefaultHeader('X-Client-Version', appVersion); } set offlineMode(bool offline) { @@ -66,5 +87,11 @@ class Singleton { FirebaseApi get firebaseApi => FirebaseApi(_api); + MediaApi get mediaApi => MediaApi(_api); + + MessagesApi get messagesApi => MessagesApi(_api); + + ChatsApi get chatsApi => ChatsApi(_api); + bool get offlineMode => _offlineMode; } diff --git a/lib/utils/sticker_store.dart b/lib/utils/sticker_store.dart new file mode 100644 index 0000000..0007bcf --- /dev/null +++ b/lib/utils/sticker_store.dart @@ -0,0 +1,69 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:uuid/uuid.dart'; + +import 'cache_utils.dart'; +import 'media_utils.dart'; + +/// One sticker of the local collection. +class Sticker { + const Sticker(this.id, this.path); + + /// Id of the entry in the sticker box. + final String id; + + /// Encrypted-at-rest file on this device. + final String path; +} + +/// Custom stickers: pictures imported from a file, kept on this device. +/// +/// There is no third-party sticker store: the bytes are the user's, encrypted +/// at rest like every other attachment, and the only metadata is the path. +class StickerStore { + StickerStore._(); + + static const Uuid _uuid = Uuid(); + + /// Extensions a sticker may have. The renderer plays animated GIFs natively, + /// so both still and animated stickers work without extra code. + static const List _extensions = ['.png', '.gif', '.webp', '.jpg']; + + static bool _supported(String? fileName) { + if (fileName == null) { + return false; + } + final lower = fileName.toLowerCase(); + return _extensions.any(lower.endsWith); + } + + /// Every sticker still present on disk, oldest first. + static Future> all() async { + final entries = await CacheUtils.getStickers(); + final stickers = []; + for (final entry in entries.entries) { + if (File(entry.value).existsSync()) { + stickers.add(Sticker(entry.key, entry.value)); + } + } + return stickers; + } + + /// Imports [bytes] as a new sticker. Null when the file is not a picture. + static Future add(Uint8List bytes, String? fileName) async { + if (!_supported(fileName)) { + return null; + } + final path = await MediaUtils.encryptAtRest(bytes); + final sticker = Sticker(_uuid.v4(), path); + await CacheUtils.putSticker(sticker.id, sticker.path); + return sticker; + } + + /// Removes a sticker and its file. + static Future remove(Sticker sticker) async { + await CacheUtils.deleteSticker(sticker.id); + await MediaUtils.deleteLocalFile(sticker.path); + } +} diff --git a/lib/utils/storage_utils.dart b/lib/utils/storage_utils.dart new file mode 100644 index 0000000..171bf97 --- /dev/null +++ b/lib/utils/storage_utils.dart @@ -0,0 +1,125 @@ +import '../models/private_message.dart'; +import 'cache_utils.dart'; +import 'media_utils.dart'; + +/// What the attachments of one conversation cost on this device. +class ConversationUsage { + const ConversationUsage(this.conversationId, this.bytes, this.attachments); + + final String conversationId; + final int bytes; + final int attachments; +} + +/// Local media accounting, and the two ways to get the space back. +/// +/// Attachments are the only thing here that grows without bound: the archive is +/// text, but every video leaves an encrypted copy on disk until something +/// removes it. +class StorageUtils { + StorageUtils._(); + + /// Bytes and attachment count per conversation, newest biggest first. + static Future> usageByConversation() async { + final messages = await CacheUtils.getAllConversationMessages(); + final usage = []; + for (final entry in messages.entries) { + var bytes = 0; + var count = 0; + for (final message in entry.value) { + bytes += _messageBytes(message); + count += message.localPaths.length; + } + if (count > 0) { + usage.add(ConversationUsage(entry.key, bytes, count)); + } + } + usage.sort((a, b) => b.bytes.compareTo(a.bytes)); + return usage; + } + + /// What one conversation keeps on this device. + static Future usageFor(String conversationId) async { + for (final usage in await usageByConversation()) { + if (usage.conversationId == conversationId) { + return usage; + } + } + return ConversationUsage(conversationId, 0, 0); + } + + /// Drops the local copy of every attachment older than [days] and marks it + /// expired, keeping the messages themselves. Returns the bytes freed. + /// + /// The media is single delivery: once dropped it cannot be downloaded again, + /// which is why the setting spells that out before it is applied. + static Future purgeOlderThanDays(int days) async { + if (days <= 0) { + return 0; + } + final cutoff = DateTime.now().subtract(Duration(days: days)); + final messages = await CacheUtils.getAllConversationMessages(); + var freed = 0; + for (final entry in messages.entries) { + for (final message in entry.value) { + if (message.sentAt.isAfter(cutoff)) { + continue; + } + final paths = message.localPaths; + if (paths.isEmpty) { + continue; + } + freed += _messageBytes(message); + for (final path in paths) { + await MediaUtils.deleteLocalFile(path); + } + await CacheUtils.updateStoredMessage(entry.key, message, (stored) { + stored.localPath = null; + stored.downloadStatus = MediaDownloadStatus.expired; + if (!stored.isAlbum) { + return; + } + final items = stored.album; + for (final item in items) { + if (item.localPath != null) { + item.localPath = null; + item.status = MediaDownloadStatus.expired; + } + } + stored.setAlbum(items); + }); + } + } + return freed; + } + + /// Empties the temporary plaintext files and the in-memory decrypt cache. + /// The stored attachments stay: only copies that were never meant to outlive + /// the session go. + static Future clearCache() async { + await MediaUtils.clearTempFiles(); + MediaUtils.clearDecryptedCache(); + } + + /// Applies the configured auto-delete once at start-up. + static Future purgeIfDue() async { + final days = await CacheUtils.getAutoDeleteMediaDays(); + if (days > 0) { + await purgeOlderThanDays(days); + } + } + + /// Bytes one stored message keeps on disk, including the encryption overhead. + static int _messageBytes(PrivateMessage message) { + var bytes = 0; + if (message.localPath != null) { + bytes += (message.mediaSize ?? 0) + MediaUtils.transportOverheadBytes; + } + for (final item in message.album) { + if (item.localPath != null) { + bytes += item.size + MediaUtils.transportOverheadBytes; + } + } + return bytes; + } +} diff --git a/lib/utils/text_envelope.dart b/lib/utils/text_envelope.dart new file mode 100644 index 0000000..691ba96 --- /dev/null +++ b/lib/utils/text_envelope.dart @@ -0,0 +1,212 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +/// The message a reply quotes. +/// +/// The preview is stored next to the pointer, so the quote still reads after +/// the original was deleted locally (deleting a message only removes it on +/// this device). +class ReplyRef { + const ReplyRef({ + required this.senderId, + required this.sentAt, + required this.preview, + }); + + final String senderId; + final DateTime sentAt; + + /// Truncated body of the quoted message. + final String preview; + + /// Longest preview kept in the envelope; the bubble shows two lines. + static const int maxPreviewLength = 160; + + Map toJson() => { + 'senderId': senderId, + 'sentAt': sentAt.microsecondsSinceEpoch, + 'preview': preview, + }; + + /// Null when [json] is not a usable reference. + static ReplyRef? fromJson(Object? json) { + if (json is! Map) { + return null; + } + final senderId = json['senderId']; + final sentAt = json['sentAt']; + if (senderId is! String || sentAt is! int) { + return null; + } + return ReplyRef( + senderId: senderId, + sentAt: DateTime.fromMicrosecondsSinceEpoch(sentAt), + preview: json['preview'] is String ? json['preview'] as String : '', + ); + } + + /// Shortens [text] for storage in the envelope. + static String previewOf(String text) => text.length <= maxPreviewLength + ? text + : '${text.substring(0, maxPreviewLength)}…'; +} + +/// Payload of a text message that quotes another one. +class ParsedTextEnvelope { + const ParsedTextEnvelope(this.body, this.reply, + {this.forwarded = false, this.location, this.viewOnce = false}); + + final String body; + final ReplyRef? reply; + + /// The sender passed on somebody else's text instead of writing it. + final bool forwarded; + + /// A static location, null for an ordinary text message. + final LocationRef? location; + + /// A single-view message: the body is revealed once and then burnt. Only a + /// location uses it; an attachment carries the flag in its media envelope. + final bool viewOnce; +} + +/// A static location inside a text envelope. It stays a `text` message with an +/// optional key, so an older client shows the body ("📍 50.08, 14.42") instead +/// of raw JSON. +class LocationRef { + final double lat; + final double lng; + final double? accuracy; + final String? label; + + const LocationRef(this.lat, this.lng, {this.accuracy, this.label}); + + /// What a client without location support still shows. + String get body => '📍 ${lat.toStringAsFixed(5)}, ${lng.toStringAsFixed(5)}'; + + Map toJson() => { + 'lat': lat, + 'lng': lng, + if (accuracy != null) 'accuracy': accuracy, + if (label != null && label!.isNotEmpty) 'label': label, + }; + + static LocationRef? fromJson(dynamic json) { + if (json is! Map) { + return null; + } + final lat = json['lat']; + final lng = json['lng']; + if (lat is! num || lng is! num) { + return null; + } + return LocationRef(lat.toDouble(), lng.toDouble(), + accuracy: (json['accuracy'] as num?)?.toDouble(), + label: json['label'] as String?); + } +} + +/// Envelope version of a text message carrying a quote. Versions 1 and 2 are +/// the media envelopes; plain text stays raw UTF-8, so a reader that never +/// quotes anything keeps writing what every older client can open. +const int textEnvelopeVersion = 3; + +/// Plaintext (pre-encryption) bytes of a reply or a forwarded message. +/// +/// The envelope stays version 3 and the flags are optional keys, so a reader +/// that predates them still shows the body instead of raw JSON. +Uint8List buildTextEnvelope(String body, ReplyRef? reply, + {bool forwarded = false, LocationRef? location, bool viewOnce = false}) { + final map = { + 'sheptMsg': textEnvelopeVersion, + 'kind': 'text', + 'body': body, + if (reply != null) 'replyTo': reply.toJson(), + if (forwarded) 'forwarded': true, + if (location != null) 'location': location.toJson(), + if (viewOnce) 'viewOnce': true, + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); +} + +/// Parses [plaintext] as a quoting text envelope. Null for anything else, which +/// includes every plain text message. +ParsedTextEnvelope? tryParseTextEnvelope(Uint8List plaintext) { + try { + final decoded = jsonDecode(utf8.decode(plaintext)); + if (decoded is Map && + decoded['kind'] == 'text' && + decoded['sheptMsg'] == textEnvelopeVersion) { + final body = decoded['body']; + if (body is! String) { + return null; + } + return ParsedTextEnvelope( + body, + ReplyRef.fromJson(decoded['replyTo']), + forwarded: decoded['forwarded'] == true, + location: LocationRef.fromJson(decoded['location']), + viewOnce: decoded['viewOnce'] == true, + ); + } + } catch (_) { + // Not JSON / not a text envelope -> plain text. + } + return null; +} + +/// Envelope version of a control message: a chat setting both participants have +/// to agree on. It has its own version and kind, so no reader mistakes it for +/// text; a client that predates it shows raw JSON, which is why a timer is only +/// proposed towards a peer already on the new build. +const int systemEnvelopeVersion = 4; + +/// The only control message so far: the disappearing-message timer. +const String systemActionDisappearing = 'disappearing'; + +class ParsedSystemEnvelope { + const ParsedSystemEnvelope(this.state, this.seconds); + + /// "propose", "accept" or "decline". + final String state; + + /// The timer in seconds; 0 turns disappearing messages off. + final int seconds; +} + +/// Plaintext (pre-encryption) bytes of a disappearing-message proposal, an +/// acceptance or a refusal. +Uint8List buildSystemEnvelope(String state, int seconds) { + final map = { + 'sheptMsg': systemEnvelopeVersion, + 'kind': 'system', + 'action': systemActionDisappearing, + 'state': state, + 'seconds': seconds, + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); +} + +/// Parses [plaintext] as a control envelope. Null for anything else. +ParsedSystemEnvelope? tryParseSystemEnvelope(Uint8List plaintext) { + try { + final decoded = jsonDecode(utf8.decode(plaintext)); + if (decoded is! Map || + decoded['kind'] != 'system' || + decoded['sheptMsg'] != systemEnvelopeVersion || + decoded['action'] != systemActionDisappearing) { + return null; + } + final state = decoded['state']; + final seconds = decoded['seconds']; + if (state is! String || seconds is! num) { + return null; + } + if (state != 'propose' && state != 'accept' && state != 'decline') { + return null; + } + return ParsedSystemEnvelope(state, seconds.toInt()); + } catch (_) { + return null; + } +} diff --git a/lib/utils/theme_notifier.dart b/lib/utils/theme_notifier.dart index e9d92be..6d715ce 100644 --- a/lib/utils/theme_notifier.dart +++ b/lib/utils/theme_notifier.dart @@ -3,7 +3,6 @@ import '../models/app_theme.dart'; // https://stackoverflow.com/a/65517149/19371130 class ThemeNotifier extends ChangeNotifier { - ThemeNotifier(this.appTheme); AppTheme appTheme; @@ -12,4 +11,4 @@ class ThemeNotifier extends ChangeNotifier { appTheme = theme; return notifyListeners(); } -} \ No newline at end of file +} diff --git a/lib/utils/theme_utils.dart b/lib/utils/theme_utils.dart new file mode 100644 index 0000000..6df5a22 --- /dev/null +++ b/lib/utils/theme_utils.dart @@ -0,0 +1,21 @@ +import 'package:flutter/material.dart'; + +class ThemeUtils { + /// Theme seeded with the per-chat color, or the inherited theme without an override. + /// + /// Brightness and Material 3 always follow the global theme. + static ThemeData chatTheme(BuildContext context, Color? seed) { + if (seed == null) { + return Theme.of(context); + } + final brightness = Theme.of(context).brightness; + // Recomputing the tonal palette on every rebuild lands mid-transition. + final key = Object.hash(seed, brightness); + return _chatThemes[key] ??= ThemeData.from( + colorScheme: + ColorScheme.fromSeed(seedColor: seed, brightness: brightness), + useMaterial3: true); + } + + static final Map _chatThemes = {}; +} diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index d4c304b..f7f5001 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; @@ -5,35 +6,74 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; -import 'package:jwt_decoder/jwt_decoder.dart'; import 'package:page_transition/page_transition.dart'; import 'package:path_provider/path_provider.dart'; import 'package:vibration/vibration.dart'; import '../utils/notification_service.dart'; import '../pages/chat_page.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:shept_openapi_client_dart/api.dart'; import 'package:basic_utils/basic_utils.dart' as bu; -import 'package:whisper_websocket_client_dart/models/private_message.dart'; -import 'package:whisper_websocket_client_dart/models/ws_response.dart'; -import 'package:whisper_websocket_client_dart/models/ws_response_type.dart'; +import 'package:shept_websocket_client_dart/models/delivery_ack.dart'; +import 'package:shept_websocket_client_dart/models/live_location.dart'; +import 'package:shept_websocket_client_dart/models/message_event.dart'; +import 'package:shept_websocket_client_dart/models/presence.dart'; +import 'package:shept_websocket_client_dart/models/read_receipt.dart'; +import 'package:shept_websocket_client_dart/models/synced.dart'; +import 'package:shept_websocket_client_dart/models/typing.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/private_message.dart'; +import 'package:shept_websocket_client_dart/models/ws_response.dart'; +import 'package:shept_websocket_client_dart/models/ws_response_type.dart'; +import 'auto_download.dart'; import 'cache_utils.dart'; +import 'chat_sender.dart'; import 'crypto_utils.dart'; +import 'media_utils.dart'; import 'message_notifier.dart'; +import 'live_location.dart'; +import 'presence.dart'; import 'singleton.dart'; +import 'text_envelope.dart'; import '../models/private_message.dart' as pm; +import '../models/user.dart'; class Utils { - /// Capitalize first letter of string. - static String capitalizeFirstLetter(String input) { - if (input.isEmpty) { - return input; + /// Localized text for a server error code (the server only sends camelCase + /// names). An unknown code falls back to a generic message, so the user never + /// sees a raw identifier. + static String serverErrorText(String code) { + if (code.isEmpty) { + return 'serverError'.tr(); } - return input[0].toUpperCase() + input.substring(1); + final text = code.tr(); + return text == code ? 'serverError'.tr() : text; + } + + /// Error code from a JSON error body ({"error": "someCode"}). Empty when the + /// body carries no code. + static String serverErrorCode(String? body) { + if (body == null || body.isEmpty) { + return ''; + } + try { + final decoded = jsonDecode(body); + if (decoded is Map && decoded['error'] is String) { + return decoded['error'] as String; + } + } catch (_) { + // Not JSON: nothing to translate. + } + return ''; } /// Call API, handle errors and return result. + /// + /// [showError] turns the red error toast off for internal calls (token + /// renewal) that have their own recovery path. static Future callApi(Future Function() call, - {bool useSecurity = true, bool rethrowErr = false}) async { + {bool useSecurity = true, + bool rethrowErr = false, + bool showError = true}) async { // Check tokens if (useSecurity) { await authCheck(); @@ -45,20 +85,18 @@ class Utils { return result; } catch (e) { // Handle error - if (e is ApiException) { + if (e is ApiException && !showError) { + if (e.innerException is SocketException) { + Singleton().offlineMode = true; + } + } else if (e is ApiException) { if (e.innerException == null) { - if (e.message != '') { - Map messageMap = - jsonDecode(e.message!) as Map; - await Fluttertoast.showToast( - msg: Utils.capitalizeFirstLetter(messageMap['error']), - backgroundColor: Colors.red); - } else { - await Fluttertoast.showToast( - msg: Utils.capitalizeFirstLetter( - 'HTTP error ${e.code.toString()}'), - backgroundColor: Colors.red); - } + final code = Utils.serverErrorCode(e.message); + await Fluttertoast.showToast( + msg: code.isEmpty + ? 'httpError'.tr(args: [e.code.toString()]) + : Utils.serverErrorText(code), + backgroundColor: Colors.red); } else { if (e.innerException is SocketException) { Singleton().offlineMode = true; @@ -79,57 +117,161 @@ class Utils { /// Gets cache directory path static Future getCacheDir() async { Directory dir = await getApplicationDocumentsDirectory(); - return '${dir.path}/whisper'; + return '${dir.path}/shept'; } + /// In-flight token renewal. Concurrent callers (a resume fires several API + /// calls at once) share one renewal: the refresh token is single use, so two + /// parallel refreshes would burn the session. + static Future? _authInFlight; + /// Checks access and refresh tokens and renews them if necessary. - static Future authCheck() async { - bool toAuth = false; - // Initial auth - if (Singleton().profile.refreshToken == '' && - Singleton().profile.accessToken == '') { - toAuth = true; - } else { - // Auth when refresh token is expired - toAuth = JwtDecoder.isExpired(Singleton().profile.refreshToken); + /// + /// A refresh can be refused (session revoked, or a token minted before + /// sessions were recorded). The RSA challenge always works with the stored + /// private key, so it is the fallback instead of leaving the app unauthorized. + static Future authCheck() { + final inFlight = _authInFlight; + if (inFlight != null) { + return inFlight; } + final renewal = _doAuthCheck(); + _authInFlight = renewal; + return renewal.whenComplete(() { + _authInFlight = null; + }); + } - // Auth if necessary - if (toAuth) { - // Auth - final token = await CryptoUtils.generateRsaJwt( - Singleton().profile.user.id, - bu.CryptoUtils.rsaPrivateKeyFromPem(Singleton().profile.privateKey)); - var authResponse = await Utils.callApi( - () => Singleton() - .authApi - .authUser(authUserInput: AuthUserInput(token: token)), - useSecurity: false); - if (authResponse != null) { - // Set tokens to singleton - Singleton().profile.accessToken = authResponse.accessToken; - Singleton().profile.refreshToken = authResponse.refreshToken; - // Save profile to cache - await CacheUtils.setProfile(Singleton().profile); + static Future _doAuthCheck() async { + final profile = Singleton().profile; + final hasTokens = profile.refreshToken != '' || profile.accessToken != ''; + bool toAuth = !hasTokens || !isTokenUsable(profile.refreshToken); + + if (!toAuth && !isTokenUsable(profile.accessToken)) { + var refreshed = false; + try { + final refreshResponse = await Utils.callApi( + () => Singleton().authApi.refreshUserAccessToken( + refreshUserAccessTokenInput: RefreshUserAccessTokenInput( + refreshToken: profile.refreshToken)), + useSecurity: false, + rethrowErr: true, + showError: false); + if (refreshResponse != null) { + profile.accessToken = refreshResponse.accessToken; + // The server rotates the refresh token: the old one is spent. + if (refreshResponse.refreshToken.isNotEmpty) { + profile.refreshToken = refreshResponse.refreshToken; + } + await CacheUtils.setProfile(profile); + refreshed = true; + } + } on ApiException catch (e) { + // 401: the server will not renew this session -> log in again. + if (e.code == 401) { + toAuth = true; + } + } catch (_) { + // Network problem: stay offline, the next call retries. } - } else if (JwtDecoder.isExpired(Singleton().profile.accessToken)) { - // Refresh access token if expired - var refreshResponse = await Utils.callApi( - () => Singleton().authApi.refreshUserAccessToken( - refreshUserAccessTokenInput: RefreshUserAccessTokenInput( - refreshToken: Singleton().profile.refreshToken)), - useSecurity: false); - - if (refreshResponse != null) { - // Set access token to singleton - Singleton().profile.accessToken = refreshResponse.accessToken; - // Save profile to cache - await CacheUtils.setProfile(Singleton().profile); + if (!refreshed && !toAuth) { + Singleton().apiToken = profile.accessToken; + return; + } + } + + if (toAuth) { + // The server only accepts a login JWT that carries a fresh challenge, so + // it can never be replayed and a revoked session stays revoked. + final challenge = await Utils.callApi( + () => Singleton().authApi.authChallenge(), + useSecurity: false, + showError: false); + if (challenge != null) { + // The device id is created once per installation, signed into the + // login JWT and registered by the server, so it can be revoked. + final deviceId = await CacheUtils.getOrCreateDeviceId(); + final token = await CryptoUtils.generateRsaJwt(profile.user.id, + bu.CryptoUtils.rsaPrivateKeyFromPem(profile.privateKey), + nonce: challenge.challenge, deviceId: deviceId); + final authResponse = await Utils.callApi( + () => Singleton().authApi.authUser( + authUserInput: AuthUserInput( + token: token, + deviceId: deviceId, + label: CacheUtils.deviceLabel, + platform: CacheUtils.devicePlatform, + )), + useSecurity: false, + showError: false); + if (authResponse != null) { + profile.accessToken = authResponse.accessToken; + profile.refreshToken = authResponse.refreshToken; + await CacheUtils.setProfile(profile); + } } } // Set API token - Singleton().apiToken = Singleton().profile.accessToken; + Singleton().apiToken = profile.accessToken; + } + + /// Claims of a JWT, or null when it cannot be read. Local use only: the + /// server remains the authority. + static Map? tokenClaims(String token) { + final parts = token.split('.'); + if (parts.length != 3) { + return null; + } + try { + return jsonDecode( + utf8.decode(base64Url.decode(base64Url.normalize(parts[1])))) + as Map; + } catch (_) { + return null; + } + } + + /// Whether a JWT is expired or unreadable. + static bool isTokenExpired(String token) { + final payload = tokenClaims(token); + if (payload == null) { + return true; + } + final exp = payload['exp']; + if (exp is! int) { + return false; + } + return DateTime.fromMillisecondsSinceEpoch(exp * 1000) + .isBefore(DateTime.now()); + } + + /// Whether a JWT is accepted by the current server: readable, unexpired and + /// carrying the token type the server requires. Tokens issued before types + /// existed are useless even while their expiry is still in the future, so + /// they must trigger a login instead of failing every request. + static bool isTokenUsable(String token) { + if (isTokenExpired(token)) { + return false; + } + final claims = tokenClaims(token); + return claims != null && claims['typ'] is String; + } + + /// Whether a server URL may be used. + /// + /// Release builds only talk to HTTPS: message bodies stay end-to-end + /// encrypted, but tokens, contacts and metadata would travel in clear text + /// over plain HTTP. Debug builds accept HTTP for local development. + static bool isAllowedServerUrl(String url) { + final uri = Uri.tryParse(url.trim()); + if (uri == null || !uri.hasAuthority || uri.host.isEmpty) { + return false; + } + if (uri.scheme == 'https') { + return true; + } + return !kReleaseMode && uri.scheme == 'http'; } /// Get WebSocket URL from APi URL @@ -140,89 +282,392 @@ class Utils { return '$wsUrl/ws'; } + /// Decrypt, store and optionally announce a batch of messages. + /// + /// Live frames are announced (a notification per conversation) and their + /// older echoes are dropped; history from a sync is stored silently. + static Future _storeMessages(List messages, + {required bool notify, bool advanceCursor = false}) async { + // A tombstone (deleted for everyone) has no ciphertext left. The caller + // drops the local copy; storing it here would only create an undecryptable + // placeholder. + messages = messages + .where((message) => + message.content != null && + message.key != null && + message.nonce != null && + message.mac != null) + .toList(); + if (messages.isEmpty) { + return; + } + messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); + List decryptedMessages = []; + // Media references of each conversation that still need a download. + final pendingMediaRefs = >{}; + + try { + // One isolate for the whole batch: a per-message decrypt used to + // cost an RSA key parse and an isolate spawn each. + List decryptedBatch; + try { + decryptedBatch = await CryptoUtils.decryptMessageBatch( + messages + .map((message) => { + 'data': message.content!, + 'key': message.key!, + 'nonce': message.nonce!, + 'mac': message.mac!, + }) + .toList(), + Singleton().profile.privateKey); + } catch (_) { + // A batch failure must not drop the messages: they become visible + // placeholders below instead of disappearing. + decryptedBatch = List.filled(messages.length, null); + } + + final decryptionTasks = messages.asMap().entries.map((entry) async { + final index = entry.key; + final message = entry.value; + try { + final decryptedMessage = decryptedBatch[index]; + if (decryptedMessage == null) { + throw const FormatException('message decryption failed'); + } + // Media message: decode the envelope and create a placeholder. + final envelope = MediaUtils.tryParseMediaEnvelope(decryptedMessage); + if (envelope != null) { + final expiresAt = await _expiryFor(message.peerId, message.sentAt); + if (envelope.references.length > 1) { + // Album: one bubble, one download per attachment. + final albumMsg = pm.PrivateMessage( + message.senderId, + envelope.caption, + message.sentAt, + DateTime.now(), + false, + downloadStatus: pm.MediaDownloadStatus.pending, + forwarded: envelope.forwarded, + viewOnce: envelope.viewOnce, + expiresAt: expiresAt, + ); + albumMsg.setAlbum(envelope.references + .map((ref) => pm.AlbumItem( + mediaId: ref.mediaId, + type: ref.type.name, + size: ref.size, + width: ref.width, + height: ref.height, + durationMs: ref.durationMs, + fileName: ref.fileName, + keyB64: base64Encode(ref.key), + status: pm.MediaDownloadStatus.pending, + )) + .toList()); + return (albumMsg, envelope.references, message.peerId); + } + final ref = envelope.references.single; + final mediaMsg = pm.PrivateMessage( + message.senderId, + envelope.caption, + message.sentAt, + DateTime.now(), + false, + mediaId: ref.mediaId, + mediaTypeStr: ref.type.name, + mediaSize: ref.size, + width: ref.width, + height: ref.height, + durationMs: ref.durationMs, + fileName: ref.fileName, + downloadStatus: pm.MediaDownloadStatus.pending, + forwarded: envelope.forwarded, + viewOnce: envelope.viewOnce, + expiresAt: expiresAt, + mediaRefJson: jsonEncode(ref.toJson()), + ); + return (mediaMsg, [ref], message.peerId); + } + // Control message: the disappearing-message agreement. It carries no + // text, so the chat renders it as a pill. + final systemEnvelope = tryParseSystemEnvelope(decryptedMessage); + if (systemEnvelope != null) { + final systemMsg = pm.PrivateMessage( + message.senderId, + '', + message.sentAt, + DateTime.now(), + // Chat state, already applied above: it must not raise an + // unread badge. + true, + systemState: systemEnvelope.state, + systemSeconds: systemEnvelope.seconds) + ..id = message.id; + return (systemMsg, const [], message.peerId); + } + // Plain text message (legacy/unchanged path), or a reply that carries + // its quote in a text envelope. + final textEnvelope = tryParseTextEnvelope(decryptedMessage); + final textMsg = pm.PrivateMessage( + message.senderId, + textEnvelope?.body ?? utf8.decode(decryptedMessage), + message.sentAt, + DateTime.now(), + false, + forwarded: textEnvelope?.forwarded ?? false, + viewOnce: textEnvelope?.viewOnce ?? false, + locationJson: textEnvelope?.location == null + ? null + : jsonEncode(textEnvelope!.location!.toJson()), + expiresAt: await _expiryFor(message.peerId, message.sentAt)) + ..setReplyTo(textEnvelope?.reply); + return (textMsg, const [], message.peerId); + } catch (e) { + // Log individual message decryption errors + if (kDebugMode) { + debugPrint( + 'Failed to decrypt message from ${message.senderId}: $e'); + } + // Keep a visible placeholder: dropping the message hides the loss + // from the user and from the server (which still has the entry). + return ( + pm.PrivateMessage( + message.senderId, + pm.PrivateMessage.undecryptableMarker, + message.sentAt, + DateTime.now(), + false, + ), + const [], + message.peerId + ); + } + }); + + final results = await Future.wait(decryptionTasks); + + // Filter out failed decryptions (null values) + final valid = results + .whereType<(pm.PrivateMessage, List, String)>() + .toList(); + decryptedMessages = valid.map((e) => e.$1).toList(); + for (final (message, refs, _) in valid) { + if (refs.isNotEmpty) { + pendingMediaRefs.putIfAbsent(message.senderId, () => []).addAll(refs); + } + } + // A control message changes the chat state before the bubble is stored, + // so the chat list already shows the new timer. + for (final (message, _, _) in valid) { + if (message.isSystem) { + await applySystemAgreement( + message.senderId, message.systemState!, message.systemSeconds); + } + } + + // Show toast only if all messages failed to decrypt + if (decryptedMessages.isEmpty && messages.isNotEmpty) { + await Fluttertoast.showToast( + msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); + } + } catch (_) { + await Fluttertoast.showToast( + msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); + } + // Self-sent messages are stored locally before sending; dropping the live + // server echo prevents a duplicate bubble in the debug self-chat. The + // archive copy is kept, because it is what a fresh device syncs. + if (notify) { + decryptedMessages.removeWhere( + (message) => message.senderId == Singleton().profile.user.id); + } + + if (decryptedMessages.isEmpty) { + return; + } + // A batch can hold messages from several peers: store each conversation + // under its own key. The peer id and not the sender is the conversation: + // an archived message we sent has our own id as the sender. + final byPeer = >{}; + final peerOfMessage = {}; + final idOfMessage = {}; + final editedOfMessage = {}; + final openedOfMessage = {}; + for (final message in messages) { + final key = + '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'; + peerOfMessage[key] = message.peerId; + idOfMessage[key] = message.id; + editedOfMessage[key] = message.editedAt; + openedOfMessage[key] = message.openedAt; + } + for (final message in decryptedMessages) { + final key = + '${message.senderId}|${message.sentAt.toUtc().toIso8601String()}'; + // The archive id is what a delete on the server needs. + message.id ??= idOfMessage[key]; + message.editedAt ??= editedOfMessage[key]; + message.openedAt ??= openedOfMessage[key]?.toLocal(); + final peer = peerOfMessage[key] ?? message.senderId; + byPeer.putIfAbsent(peer, () => []).add(message); + } + for (final entry in byPeer.entries) { + await MessageNotifier().addMessages(entry.key, entry.value); + // Kick off media downloads now that placeholders are persisted. The + // network setting decides which ones: what is skipped stays pending and + // the bubble offers a download button. + for (final ref in pendingMediaRefs[entry.key] ?? const []) { + if (!await AutoDownload.allows(ref)) { + continue; + } + // Fire-and-forget; updates the message + notifies on completion. + MessageNotifier().downloadMediaMessage(entry.key, ref); + } + } + // A live message would otherwise come back on the next sync and overwrite + // a downloaded attachment with its placeholder. Only live frames may move + // the cursor: a history page is one conversation and says nothing about + // the messages of the others. + if (advanceCursor) { + var highestSeq = 0; + for (final message in messages) { + if (message.seq > highestSeq) { + highestSeq = message.seq; + } + } + if (highestSeq > 0) { + await CacheUtils.setSyncSeq(highestSeq); + } + } + + if (!notify) { + return; + } + + // A control message is chat state, not correspondence: it never rings. + decryptedMessages.removeWhere((message) => message.isSystem); + + // Remove messages from notifications if user was not online when they were sent + decryptedMessages.removeWhere((x) => !messages + .where((y) => y.sentAt == x.sentAt && y.senderId == x.senderId) + .first + .recipientOnline); + + bool homePageOpened = false; + var currentRoute = Singleton().currentRoute; + if (currentRoute is PageTransition) { + if (currentRoute.child is ChatPage) { + var chatPage = currentRoute.child as ChatPage; + // Delete messages of current open user chat from notifications + decryptedMessages.removeWhere((x) => x.senderId == chatPage.user.id); + } + } else { + // Home page is opened + homePageOpened = true; + } + // Show notification if there are messages to announce and HomePage is not opened + if (decryptedMessages.isNotEmpty && !homePageOpened) { + if (Singleton().profile.enableNotifications) { + await NotificationService().showMessagesNotification(decryptedMessages); + } + } else { + // Vibrate if all messages were for currently opened user + Vibration.vibrate(pattern: [0, 150], intensities: [0, 255]); + } + } + /// Handle WebSocket message static Future onWsMessageReceived(WsResponse wsResponse) async { switch (wsResponse.type) { // More messages case WsResponseType.messages: - var messages = wsResponse.payload as List; - messages.sort((a, b) => a.sentAt.compareTo(b.sentAt)); - List decryptedMessages = []; + await _storeMessages(wsResponse.payload as List, + notify: true, advanceCursor: true); + break; - // Parallel decrypt all messages - try { - final decryptionTasks = messages.map((message) async { - try { - var decryptedMessage = await CryptoUtils.decryptMessageData( - message.content, - message.key, - message.nonce, - message.mac, - bu.CryptoUtils.rsaPrivateKeyFromPem( - Singleton().profile.privateKey)); - return pm.PrivateMessage( - message.senderId, - utf8.decode(decryptedMessage), - message.sentAt, - DateTime.now(), - false); - } catch (e) { - // Log individual message decryption errors - if (kDebugMode) { - debugPrint( - 'Failed to decrypt message from ${message.senderId}: $e'); - } - return null; // Return null for failed decryptions - } - }); + // Archive delta after a reconnect + case WsResponseType.synced: + final synced = wsResponse.payload as Synced; + for (final peer in synced.peers) { + // A fresh device learns the accounts it is talking to from the batch. + await CacheUtils.addUser( + User(peer.id, peer.username, peer.publicKey, false)); + } + // A tombstone carries no ciphertext: keep the row as the "deleted" + // placeholder instead of storing an undecryptable bubble. + for (final dead + in synced.messages.where((message) => message.deletedAt != null)) { + await CacheUtils.markMessageDeleted( + dead.peerId, dead.sentAt, dead.deletedAt!.toLocal()); + } + if (synced.messages.isNotEmpty) { + // History is silent: a week offline must not ring once per old + // message. + await _storeMessages(synced.messages, notify: false); + } + for (final cleared in synced.cleared) { + await CacheUtils.applyConversationClearedAt( + cleared.peerId, cleared.clearedAt.toLocal()); + } + // Events come after the messages they talk about, which is what the + // server's cursor ordering guarantees. + for (final event in synced.events) { + await applyEvent(event); + } + for (final receipt in synced.reads) { + await CacheUtils.setPeerReadAt( + receipt.peerId, receipt.readAt.toLocal()); + } + // After the cursors are stored: the reload kicked off earlier (when the + // messages were written) read the old value. + MessageNotifier().notify(); + // Only after the batch is stored: a cursor ahead of the local messages + // would drop them for good. + await CacheUtils.setSyncSeq(synced.syncedThrough); + await CacheUtils.setSyncEventSeq(synced.eventsThrough); + if (synced.hasMore && Singleton().wsClient.isConnected) { + Singleton().wsClient.sendSync(synced.syncedThrough, + sinceEventSeq: synced.eventsThrough); + } + break; - final results = await Future.wait(decryptionTasks); + // One live mutation of an archived message + case WsResponseType.edit: + case WsResponseType.delete: + case WsResponseType.reaction: + case WsResponseType.pin: + case WsResponseType.open: + await applyEvent(wsResponse.payload as MessageEvent); + break; - // Filter out failed decryptions (null values) - decryptedMessages = results.whereType().toList(); + // The other participant moved their read cursor + case WsResponseType.read: + final receipt = wsResponse.payload as ReadReceipt; + await CacheUtils.setPeerReadAt( + receipt.peerId, receipt.readAt.toLocal()); + MessageNotifier().notify(); + break; - // Show toast only if all messages failed to decrypt - if (decryptedMessages.isEmpty && messages.isNotEmpty) { - await Fluttertoast.showToast( - msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); - } - } catch (_) { - await Fluttertoast.showToast( - msg: 'decryptionFailed'.tr(), backgroundColor: Colors.red); - } - if (decryptedMessages.isNotEmpty) { - await MessageNotifier() - .addMessages(decryptedMessages.first.senderId, decryptedMessages); - - // Remove messages from notifications if user was not online when they were sent - decryptedMessages.removeWhere((x) => !messages - .where((y) => y.sentAt == x.sentAt && y.senderId == x.senderId) - .first - .recipientOnline); - - bool homePageOpened = false; - var currentRoute = Singleton().currentRoute; - if (currentRoute is PageTransition) { - if (currentRoute.child is ChatPage) { - var chatPage = currentRoute.child as ChatPage; - // Delete messages of current open user chat from notifications - decryptedMessages - .removeWhere((x) => x.senderId == chatPage.user.id); - } - } else { - // Home page is opened - homePageOpened = true; - } - // Show notification if there are messages to announce and HomePage is not opened - if (decryptedMessages.isNotEmpty && !homePageOpened) { - if (Singleton().profile.enableNotifications) { - await NotificationService() - .showMessagesNotification(decryptedMessages); - } - } else { - // Vibrate if all messages were for currently opened user - Vibration.vibrate(pattern: [0, 150], intensities: [0, 255]); - } + // The other participant is typing right now + case WsResponseType.typing: + PresenceNotifier.instance + .applyTyping((wsResponse.payload as TypingFrame).peerId); + break; + + // The other participant came online or went away + case WsResponseType.presence: + final presence = wsResponse.payload as PresenceFrame; + PresenceNotifier.instance.applyPresence(presence.peerId, + online: presence.online, lastSeenAt: presence.lastSeenAt); + break; + + // A live position: relayed encrypted, kept in memory until it expires. + case WsResponseType.liveLocation: + final frame = wsResponse.payload as LiveLocationFrame; + final point = await decryptLiveLocation(frame.payload); + if (point != null) { + PresenceNotifier.instance.applyLiveLocation(frame.peerId, point); } break; @@ -234,14 +679,205 @@ class Utils { SystemNavigator.pop(); break; + // Delivery acknowledgement of one of our outgoing messages + case WsResponseType.ack: + final ack = wsResponse.payload as DeliveryAck; + await ChatSender.confirmSent(ack.receiverId, ack.sentAt, id: ack.id); + break; + // Error case WsResponseType.error: var error = wsResponse.payload as String; - await Fluttertoast.showToast(msg: error, backgroundColor: Colors.red); + await Fluttertoast.showToast( + msg: Utils.serverErrorText(error), backgroundColor: Colors.red); + break; + + // A frame from a newer server. Ignoring it keeps this build usable. + case WsResponseType.unknown: + break; + } + } + + /// The local disappearing deadline of one incoming message, null when the + /// chat has no timer. + static Future _expiryFor(String peerId, DateTime sentAt) async { + final seconds = await CacheUtils.getDisappearingSeconds(peerId); + return seconds > 0 ? sentAt.add(Duration(seconds: seconds)) : null; + } + + /// Applies one step of the disappearing-message agreement carried by a + /// control message from [peerId]. + static Future applySystemAgreement( + String peerId, String state, int seconds) async { + switch (state) { + case 'propose': + await CacheUtils.setDisappearingProposal(peerId, seconds); + break; + case 'accept': + // The peer accepted what this device proposed. + await CacheUtils.setDisappearingSeconds(peerId, seconds); + await CacheUtils.setDisappearingProposal(peerId, null); + break; + case 'decline': + await CacheUtils.setDisappearingProposal(peerId, null); + break; + } + } + + /// Applies one entry of the mutation log: an edit, a deletion, a reaction or + /// a pin of a message this device already has. The same code serves a live + /// frame and a replayed sync page, so a reconnect converges on the same + /// state. + static Future applyEvent(MessageEvent event) async { + switch (event.kind) { + case MessageEventKind.delete: + await CacheUtils.markMessageDeleted( + event.peerId, event.sentAt, event.createdAt.toLocal()); + await CacheUtils.setMessagePinned(event.peerId, event.messageId, null); + break; + + case MessageEventKind.edit: + final content = event.content; + if (content == null) { + return; + } + final plain = await _decryptSmall(event); + if (plain == null) { + return; + } + final body = tryParseTextEnvelope(plain)?.body ?? utf8.decode(plain); + await CacheUtils.markMessageEdited( + event.peerId, event.sentAt, body, event.createdAt.toLocal()); + break; + + case MessageEventKind.reaction: + // My own reaction ciphertext is wrapped for the other side, so this + // device keeps the emoji it set locally. + if (event.actorId == Singleton().profile.user.id) { + return; + } + String? emoji; + if (event.content != null) { + final plain = await _decryptSmall(event); + if (plain == null) { + return; + } + emoji = utf8.decode(plain); + } + await CacheUtils.setMessageReaction( + event.peerId, event.sentAt, event.actorId, emoji); + break; + + case MessageEventKind.pin: + await CacheUtils.setMessagePinned(event.peerId, event.messageId, + event.pinned == true ? event.createdAt.toLocal() : null); break; + + case MessageEventKind.open: + await CacheUtils.markMessageOpened(event.peerId, event.sentAt, + (event.openedAt ?? event.createdAt).toLocal()); + break; + } + MessageNotifier().notify(); + } + + /// Decrypts the small payload of an edit or a reaction, null when it cannot + /// be opened. + static Future _decryptSmall(MessageEvent event) async { + final content = event.content; + final key = event.key; + final nonce = event.nonce; + final mac = event.mac; + if (content == null || key == null || nonce == null || mac == null) { + return null; + } + try { + final decrypted = await CryptoUtils.decryptMessageBatch([ + {'data': content, 'key': key, 'nonce': nonce, 'mac': mac} + ], Singleton().profile.privateKey); + return decrypted.single; + } catch (_) { + return null; + } + } + + /// Decrypt and store a page from the history endpoint. + /// + /// History is silent: no notifications and no vibration, the messages are + /// older than anything the device already has. + static Future storeHistoryPage( + List messages) async { + if (messages.isEmpty) { + return; + } + // A tombstone carries no ciphertext (the sender deleted it for everyone): + // keep the row as the "deleted" placeholder instead of an undecryptable + // bubble. The content is already gone, so only the marker is stored. + for (final dead in messages.where((message) => message.deletedAt != null)) { + await CacheUtils.markMessageDeleted( + dead.peerId, dead.sentAt, dead.deletedAt!.toLocal()); } + messages = messages.where((message) => message.deletedAt == null).toList(); + if (messages.isEmpty) { + return; + } + final wire = messages + .map((message) => PrivateMessage.fromJson({ + 'id': message.id, + 'seq': message.seq, + 'senderId': message.senderId, + 'peerId': message.peerId, + 'content': message.content, + 'key': message.key, + 'nonce': message.nonce, + 'mac': message.mac, + 'sentAt': message.sentAt.toIso8601String(), + 'editedAt': message.editedAt?.toIso8601String(), + 'openedAt': message.openedAt?.toIso8601String(), + 'recipientOnline': false, + })) + .toList(); + await _storeMessages(wire, notify: false); } + /// Ask the server for the archive delta and the mutation log above the + /// cursors stored on this device. Nothing is pushed on connect, so this is + /// what catches a client up. + static Future syncArchive() async { + if (!Singleton().wsClient.isConnected) { + return; + } + try { + Singleton().wsClient.sendSync(await CacheUtils.getSyncSeq(), + sinceEventSeq: await CacheUtils.getSyncEventSeq()); + } catch (e) { + if (kDebugMode) { + debugPrint('sync request failed: $e'); + } + } + } + + /// Publishes how far the account has read [peerId]'s chat. Returns false when + /// the server refused, so the caller can retry on the next message. + static Future sendReadCursor(String peerId, DateTime readAt) async { + try { + await callApi( + () => Singleton().chatsApi.setReadCursor( + peerId, + setReadCursorInput: SetReadCursorInput(readAt: readAt.toUtc()), + ), + rethrowErr: true, + showError: false); + return true; + } catch (_) { + return false; + } + } + + /// Invoked after a successful connect, e.g. to push a pending Firebase id + /// without polling. + static Future Function()? onConnected; + /// Connect to WebSocket with improved connection handling static Future wsConnect({bool firstConnect = false}) async { // Skip if already connected @@ -260,9 +896,12 @@ class Utils { try { // Attempt to get WebSocket access token + // A refused handshake is retried by the backoff loop; a toast per attempt + // would spam the user of a revoked device. var wsAuthResponse = await Utils.callApi( () => Singleton().wsAuthApi.webSocketAuth(), useSecurity: true, + showError: false, ).timeout( Duration(seconds: 10), // Add timeout for API calls onTimeout: () => null, @@ -295,9 +934,25 @@ class Utils { if (kDebugMode) { debugPrint('WebSocket connected successfully'); } + + // Messages that never got a delivery ack are retried now; the server + // deduplicates them by (receiver, sentAt). + await ChatSender.resendPending(); + // Nothing is pushed on connect: ask for the archive delta above the last + // seq stored here. A phone away for a week fetches only that week. + await syncArchive(); + // Then tell the peers we are here, if presence is switched on. + await announcePresence(); + final onConnected = Utils.onConnected; + if (onConnected != null) { + await onConnected(); + } } catch (e) { // WebSocket connection failed Singleton().offlineMode = true; + // Nothing about the peers is known without a connection. + PresenceNotifier.instance.clear(); + _stopPresenceHeartbeat(); if (kDebugMode) { debugPrint('WebSocket connection attempt failed: $e'); @@ -316,6 +971,73 @@ class Utils { static bool get isOnline => Singleton().wsClient.isConnected && !Singleton().offlineMode; + /// Tells every peer of the chat list that this device is online, and keeps + /// saying it once a minute so a killed app drops off by itself. Silent when + /// presence is off: an off client sends no frame at all. + static Future announcePresence() async { + final sent = await _sendPresence(online: true); + _presenceHeartbeat?.cancel(); + _presenceHeartbeat = sent + ? Timer.periodic(const Duration(seconds: 60), (_) { + _sendPresence(online: true); + }) + : null; + } + + /// Withdraws presence before the app goes to the background, so a peer does + /// not keep a stale "online" with no way to learn better. + static Future withdrawPresence() async { + _stopPresenceHeartbeat(); + // No setting check: it is being turned off, and the peers must hear it. + await _sendPresence(online: false, force: true); + } + + static Timer? _presenceHeartbeat; + + static void _stopPresenceHeartbeat() { + _presenceHeartbeat?.cancel(); + _presenceHeartbeat = null; + } + + /// Returns whether a frame was actually sent. + static Future _sendPresence( + {required bool online, bool force = false}) async { + if (!force && !await CacheUtils.isPresenceEnabled()) { + return false; + } + if (!isOnline) { + return false; + } + final chats = await CacheUtils.getLatestPrivateMessages(); + final peerIds = chats.keys.map((user) => user.id).toList(); + if (peerIds.isEmpty) { + return false; + } + Singleton().wsClient.sendPresence(peerIds, online: online); + return true; + } + + /// At most one typing hint per peer every three seconds; the receiver drops + /// the indicator on its own after five. + static DateTime? _lastTypingSent; + static String? _lastTypingPeer; + + /// Tells [peerId] that this device is typing, if the user opted in. + static Future sendTypingHint(String peerId) async { + if (!await CacheUtils.isTypingIndicatorEnabled() || !isOnline) { + return; + } + final now = DateTime.now(); + if (_lastTypingPeer == peerId && + _lastTypingSent != null && + now.difference(_lastTypingSent!) < const Duration(seconds: 3)) { + return; + } + _lastTypingPeer = peerId; + _lastTypingSent = now; + Singleton().wsClient.sendTyping(peerId); + } + /// Force disconnect and set offline mode static void forceOfflineMode() { try { @@ -323,6 +1045,8 @@ class Utils { } catch (_) { // Ignore disconnect errors } + PresenceNotifier.instance.clear(); + _stopPresenceHeartbeat(); Singleton().offlineMode = true; } } diff --git a/lib/utils/version.dart b/lib/utils/version.dart new file mode 100644 index 0000000..6bd8c79 --- /dev/null +++ b/lib/utils/version.dart @@ -0,0 +1,3 @@ +/// Version of this app build, sent as `X-Client-Version`. The server refuses a +/// login below its `minClientVersion` with a code we can translate. +const String appVersion = '0.3.0'; diff --git a/lib/utils/websocket_manager.dart b/lib/utils/websocket_manager.dart index 311cab5..63ae312 100644 --- a/lib/utils/websocket_manager.dart +++ b/lib/utils/websocket_manager.dart @@ -1,9 +1,21 @@ import 'dart:async'; +import 'dart:math'; + import '../utils/utils.dart'; +/// Keeps the WebSocket connected with exponential backoff. +/// +/// A fixed short interval cost a token request every few seconds, on battery and +/// on the server, even when the device was offline for hours. class WebSocketManager { static final WebSocketManager _instance = WebSocketManager._internal(); Timer? _timer; + bool _running = false; + int _attempt = 0; + + /// First retry delay; doubles up to [maxDelay]. + static const Duration _initialDelay = Duration(seconds: 2); + static const Duration maxDelay = Duration(seconds: 60); /// Private constructor for singleton pattern WebSocketManager._internal(); @@ -13,15 +25,39 @@ class WebSocketManager { return _instance; } - /// Start periodic connection check + /// Delay before the next connection attempt. Exposed for tests. + static Duration delayForAttempt(int attempt) { + // Clamp the exponent before shifting: 2^attempt overflows an int long + // before the delay is capped. + final exponent = attempt < 0 ? 0 : min(attempt, 16); + final seconds = _initialDelay.inSeconds * pow(2, exponent).toInt(); + return Duration(seconds: min(seconds, maxDelay.inSeconds)); + } + + /// Start the reconnect loop. void startConnectionCheck() { - _timer = Timer.periodic(Duration(seconds: 5), (timer) async { - await Utils.wsConnect(); - }); + _timer?.cancel(); + _running = true; + _attempt = 0; + _scheduleNext(); } - /// Stop the periodic connection check + /// Stop the reconnect loop. void stopConnectionCheck() { + _running = false; _timer?.cancel(); + _timer = null; + } + + void _scheduleNext() { + if (!_running) { + return; + } + _timer = Timer(delayForAttempt(_attempt), () async { + await Utils.wsConnect(); + // A successful connection restarts the schedule from the short delay. + _attempt = Utils.isOnline ? 0 : _attempt + 1; + _scheduleNext(); + }); } -} \ No newline at end of file +} diff --git a/lib/widgets/admin_user_list_item.dart b/lib/widgets/admin_user_list_item.dart new file mode 100644 index 0000000..1695db4 --- /dev/null +++ b/lib/widgets/admin_user_list_item.dart @@ -0,0 +1,73 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +import '../models/user.dart'; + +/// One row of the admin user list: avatar, name, admin badge and the +/// destructive action in an overflow menu. +class AdminUserListItem extends StatelessWidget { + const AdminUserListItem(this.user, {required this.onDelete, super.key}); + + final User user; + final VoidCallback onDelete; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return ListTile( + tileColor: Colors.transparent, + leading: CircleAvatar( + radius: 22, + backgroundColor: user.avatarColor, + child: Text( + user.username.isNotEmpty ? user.username[0].toUpperCase() : '?', + style: TextStyle(fontSize: 20, color: user.avatarTextColor), + ), + ), + title: Row( + children: [ + Flexible( + child: Text(user.username, overflow: TextOverflow.ellipsis), + ), + if (user.admin) + Padding( + padding: const EdgeInsets.only(left: 8), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: colors.primaryContainer, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + 'adminBadge'.tr(), + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + letterSpacing: 0.5, + color: colors.onPrimaryContainer, + ), + ), + ), + ), + ], + ), + trailing: PopupMenuButton( + icon: const Icon(Icons.more_vert), + onSelected: (_) => onDelete(), + itemBuilder: (context) => [ + PopupMenuItem( + value: 'delete', + child: Row( + children: [ + const Icon(Icons.delete_forever, color: Colors.red), + const SizedBox(width: 8), + Text('deleteUser'.tr(), + style: const TextStyle(color: Colors.red)), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/attachment_confirm_sheet.dart b/lib/widgets/attachment_confirm_sheet.dart new file mode 100644 index 0000000..aa9a2e4 --- /dev/null +++ b/lib/widgets/attachment_confirm_sheet.dart @@ -0,0 +1,160 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +/// What the sender chose in [AttachmentConfirmSheet]: the caption, whether the +/// attachment travels as a view-once one, and whether it should be edited first. +class AttachmentConfirmResult { + const AttachmentConfirmResult( + {required this.caption, this.viewOnce = false, this.edit = false}); + + final String caption; + final bool viewOnce; + + /// The sender wants the editor before sending: crop/draw for a photo, trim + /// for a video. + final bool edit; +} + +/// Sheet shown after picking an attachment: an optional caption, an optional +/// "view once" switch and a Send/Cancel decision. Owns its +/// [TextEditingController], because the sheet route keeps rebuilding while it +/// animates out. +class AttachmentConfirmSheet extends StatefulWidget { + /// Number of picked attachments; more than one means an album. + final int count; + final String initialCaption; + + /// Whether the picked attachment may be sent as a single view (one visual + /// attachment, never an album or a file). + final bool allowViewOnce; + + /// Whether the picker offers the editor (one photo or one video). + final bool allowEdit; + + const AttachmentConfirmSheet({ + required this.count, + this.initialCaption = '', + this.allowViewOnce = false, + this.allowEdit = false, + super.key, + }); + + /// Shows the sheet and returns the chosen caption and flags, or null when + /// cancelled. + /// + /// [theme] and [backgroundColor] come from the caller: a modal route renders + /// above the chat's own Theme, so without them the sheet uses the app theme. + static Future show(BuildContext context, + {required int count, + String initialCaption = '', + bool allowViewOnce = false, + bool allowEdit = false, + ThemeData? theme, + Color? backgroundColor}) { + return showModalBottomSheet( + context: context, + showDragHandle: true, + isScrollControlled: true, + backgroundColor: backgroundColor, + builder: (ctx) { + final sheet = AttachmentConfirmSheet( + count: count, + initialCaption: initialCaption, + allowViewOnce: allowViewOnce, + allowEdit: allowEdit, + ); + return theme == null ? sheet : Theme(data: theme, child: sheet); + }, + ); + } + + @override + State createState() => _AttachmentConfirmSheetState(); +} + +class _AttachmentConfirmSheetState extends State { + late final TextEditingController _controller = + TextEditingController(text: widget.initialCaption); + bool _viewOnce = false; + + void _send({bool edit = false}) { + Navigator.pop( + context, + AttachmentConfirmResult( + caption: _controller.text.trim(), + viewOnce: _viewOnce, + edit: edit, + )); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: EdgeInsets.only( + left: 16, + right: 16, + bottom: MediaQuery.of(context).viewInsets.bottom + 16, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + widget.count > 1 + ? '${'sendAlbum'.tr()} (${widget.count})' + : 'sendAttachment'.tr(), + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 12), + TextField( + controller: _controller, + minLines: 1, + maxLines: 4, + autofocus: true, + decoration: InputDecoration(hintText: 'addCaption'.tr()), + ), + // One visual attachment can be turned into a single view right here, + // instead of being a separate entry in the attach sheet. + if (widget.allowViewOnce) + CheckboxListTile( + value: _viewOnce, + onChanged: (value) => setState(() => _viewOnce = value ?? false), + controlAffinity: ListTileControlAffinity.leading, + contentPadding: EdgeInsets.zero, + secondary: const Icon(Icons.visibility_off), + title: Text('attachViewOnce'.tr()), + subtitle: Text('viewOnceHint'.tr()), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('cancel'.tr()), + ), + const Spacer(), + if (widget.allowEdit) + TextButton.icon( + onPressed: () => _send(edit: true), + icon: const Icon(Icons.tune), + label: Text('editAttachment'.tr()), + ), + const SizedBox(width: 8), + FilledButton( + onPressed: _send, + child: Text('send'.tr()), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/widgets/change_password_dialog.dart b/lib/widgets/change_password_dialog.dart new file mode 100644 index 0000000..8a6c9c9 --- /dev/null +++ b/lib/widgets/change_password_dialog.dart @@ -0,0 +1,146 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/biometric_auth.dart'; +import '../utils/cache_utils.dart'; +import '../utils/singleton.dart'; + +/// Changes the local password: verifies the current one, re-encrypts the +/// profile and media under the key derived from the new one, and keeps +/// biometric unlock in sync. +class ChangePasswordDialog extends StatefulWidget { + const ChangePasswordDialog({super.key}); + + @override + State createState() => _ChangePasswordDialogState(); +} + +class _ChangePasswordDialogState extends State { + final TextEditingController _current = TextEditingController(); + final TextEditingController _next = TextEditingController(); + final TextEditingController _confirmation = TextEditingController(); + bool _busy = false; + String? _error; + + @override + void dispose() { + _current.dispose(); + _next.dispose(); + _confirmation.dispose(); + super.dispose(); + } + + Future _submit() async { + final next = _next.text; + if (next.length < 8 || next.length > 64) { + setState(() { + _error = 'invalidPassword'.tr(); + }); + return; + } + if (next != _confirmation.text) { + setState(() { + _error = 'passwordMismatch'.tr(); + }); + return; + } + + setState(() { + _busy = true; + _error = null; + }); + try { + final changed = await CacheUtils.changePassword(_current.text, next); + if (!mounted) { + return; + } + if (!changed) { + setState(() { + _busy = false; + _error = 'wrongCurrentPassword'.tr(); + }); + return; + } + // Biometrics store a copy of the derived key; it must follow the change, + // otherwise fingerprint unlock would open the boxes with a stale key. + if (await CacheUtils.isBiometryEnabled()) { + if (!mounted) { + return; + } + final stored = await BiometricAuth.storeEncryptionKey( + Singleton().boxCollectionKey, context); + if (!stored) { + await BiometricAuth.clearEncryptionKey(); + await CacheUtils.setBiometryEnabled(false); + } + if (!mounted) { + return; + } + } + if (!mounted) { + return; + } + Navigator.of(context).pop(true); + } catch (e) { + debugPrint('change password failed: $e'); + if (!mounted) { + return; + } + setState(() { + _busy = false; + }); + await Fluttertoast.showToast( + msg: 'passwordChangeFailed'.tr(), backgroundColor: Colors.red); + } + } + + Widget _field(TextEditingController controller, String label) { + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: TextField( + controller: controller, + obscureText: true, + enabled: !_busy, + decoration: InputDecoration(labelText: label), + ), + ); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text('changePassword'.tr()), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _field(_current, 'currentPassword'.tr()), + _field(_next, 'newPassword'.tr()), + _field(_confirmation, 'confirmPassword'.tr()), + if (_error != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(_error!, + style: + TextStyle(color: Theme.of(context).colorScheme.error)), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: _busy ? null : () => Navigator.of(context).pop(false), + child: Text('noText'.tr()), + ), + TextButton( + onPressed: _busy ? null : _submit, + child: _busy + ? const SizedBox( + width: 18, height: 18, child: CircularProgressIndicator()) + : Text('okText'.tr()), + ), + ], + ); + } +} diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 6776d04..51d5567 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -2,17 +2,81 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/user.dart'; import '../models/private_message.dart'; +import '../utils/disappearing.dart'; +import '../utils/message_actions.dart'; +import '../utils/message_format.dart'; +import '../utils/text_envelope.dart'; +import '../utils/message_notifier.dart'; +import '../utils/singleton.dart'; +import 'formatted_text.dart'; +import 'media_bubble.dart'; +import 'view_once_frame.dart'; -// TODO show options on bottom on holding the widget (like in Messenger - copy etc) +/// One message bubble. +/// +/// Long-press enters selection mode; double-tap (or a horizontal swipe) replies. +/// Everything the single-message sheet used to offer lives in the selection +/// app bar, which keeps one gesture per intent. class ChatBubble extends StatefulWidget { final PrivateMessage? previousMessage; final PrivateMessage message; final PrivateMessage? nextMessage; final User user; + // Fixed for both light and dark mode (see ThemeUtils.bubbleAccent). + final Color accentColor; + + /// Whether the chat is in multi-select mode. + final bool selectionMode; + + /// Whether this bubble is part of the current selection. + final bool selected; + + /// Flashes the bubble after a jump, so the user can see which message the + /// jump landed on. + final bool highlight; + + /// Instant up to which the peer read the chat; null when they never + /// published one (receipts off or nothing read yet). + final DateTime? readAt; + + /// Toggles this bubble in the selection (tap and long-press). + final VoidCallback? onSelect; + + /// Opens the action sheet (long-press). Falls back to [onSelect] when unset. + final VoidCallback? onActions; + + /// Opens the "who reacted" list when the reaction badge is tapped. + final VoidCallback? onReactions; + + /// Quotes this message in the composer (swipe, and double-tap when no quick + /// reaction is wired). + final VoidCallback? onReply; + + /// Double-tap: adds the quick reaction to this message. + final VoidCallback? onQuickReact; + + /// Jumps to the quoted message. + final VoidCallback? onTapQuote; + + /// Overrides the avatar rule. The live-location bubble is not a message, so + /// its neighbours cannot see it; the caller says who closes a run. + final bool? showAvatar; const ChatBubble( this.previousMessage, this.message, this.nextMessage, this.user, - {super.key}); + {required this.accentColor, + this.selectionMode = false, + this.selected = false, + this.highlight = false, + this.readAt, + this.onSelect, + this.onActions, + this.onReactions, + this.onReply, + this.onQuickReact, + this.onTapQuote, + this.showAvatar, + super.key}); @override State createState() => _ChatBubbleState(); @@ -21,20 +85,191 @@ class ChatBubble extends StatefulWidget { class _ChatBubbleState extends State { bool _showTooltip = false; - @override - void initState() { - super.initState(); - /* - if (!widget.message.read) { - widget.message.read = true; - widget.message.save(); + /// Long messages start folded; this is set once the user unfolds one. + bool _expanded = false; + + /// Text longer than this is folded (about eight lines on a phone). + static const int _foldLength = 600; + + bool get _foldable => + !widget.message.isMedia && + !widget.message.isUndecryptable && + widget.message.message.length > _foldLength; + + bool get _isLargeEmoji => + !widget.message.isMedia && + !widget.message.isUndecryptable && + isEmojiOnly(widget.message.message) && + emojiCount(widget.message.message) <= 3; + + /// Tapping the badge shows who reacted; a bubble without that callback keeps + /// offering its actions, which is what the badge used to do. + VoidCallback? get _onBadgeTap => + widget.onReactions ?? widget.onActions ?? widget.onSelect; + + /// One badge for all reactions of the bubble: the emoji sit in a single pill + /// with no gap between them, and a count only when the same emoji came from + /// more than one participant. + Widget _reactionBadge() { + final emojis = widget.message.reactionEmojis; + final counts = {}; + for (final emoji in widget.message.reactions?.values ?? const []) { + counts[emoji] = (counts[emoji] ?? 0) + 1; } - */ + return Container( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(10), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (var i = 0; i < emojis.length; i++) ...[ + if (i > 0) const SizedBox(width: 1), + Text( + (counts[emojis[i]] ?? 1) > 1 + ? '${emojis[i]}${counts[emojis[i]]}' + : emojis[i], + style: const TextStyle(fontSize: 12), + ), + ], + ], + ), + ); + } + + /// A control message rendered as one centred line: the disappearing-message + /// agreement, which belongs to the chat state rather than to a speaker. + Widget _systemPill(BuildContext context) { + final message = widget.message; + final label = disappearingLabel(message.systemSeconds); + final text = switch (message.systemState) { + 'propose' => 'disappearingProposalPill'.tr(args: [label]), + 'accept' => 'disappearingEnabledPill'.tr(args: [label]), + 'decline' => 'disappearingDeclinedPill'.tr(), + _ => 'disappearingChanged'.tr(), + }; + final scheme = Theme.of(context).colorScheme; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16), + child: Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + text, + textAlign: TextAlign.center, + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(color: scheme.onSurfaceVariant), + ), + ), + ), + ); + } + + /// Filled colour of this bubble: the chat accent on our side, a neutral tone + /// on theirs. + Color bubbleBackground() { + if (widget.message.isMe) { + return widget.accentColor; + } + // The other side stays neutral, only the tone follows the brightness. + if (Theme.of(context).brightness == Brightness.dark) { + return Theme.of(context).colorScheme.surfaceContainerHigh; + } + return Theme.of(context).colorScheme.surfaceDim; + } + + Color bubbleTextColor() { + return bubbleBackground().computeLuminance() > 0.5 + ? Colors.black + : Colors.white; + } + + /// A view-once location: one reveal, then a tombstone. The reveal is the + /// platform map app, and it spends the single view on the way out. + Widget _viewOnceMessage(BuildContext context, LocationRef? location) { + final opened = widget.message.openedAt != null; + final mine = + widget.message.isMe && widget.user.id != Singleton().profile.user.id; + // Same owner colour as a text bubble (accent for mine, neutral for theirs), + // so an opened tombstone never reads as the other side's message. + final bubbleColor = bubbleBackground(); + final textColor = bubbleTextColor(); + return ViewOnceFrame( + label: mine + ? (opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr()) + : (opened ? 'viewOnceOpened'.tr() : 'viewOnceOpen'.tr()), + bubbleColor: bubbleColor, + textColor: textColor, + dimmed: opened, + onTap: mine || opened || location == null + ? null + : () async { + await MessageActions.openLocation(location); + await MessageActions.consumeViewOnce( + widget.user.id, widget.message); + }, + ); + } + + /// A static location: a pin, the coordinates and a way into the platform map + /// app. No tiles are fetched, so nothing leaves the device until the tap. + Widget _locationBubble( + BuildContext context, LocationRef location, Color color) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Icon(Icons.place, size: 20, color: color), + const SizedBox(width: 6), + Flexible( + child: Text( + (location.label?.isNotEmpty ?? false) + ? location.label! + : 'locationMessage'.tr(), + style: TextStyle(color: color, fontWeight: FontWeight.w600), + ), + ), + ], + ), + Padding( + padding: const EdgeInsets.only(top: 2, left: 26), + child: Text(location.body, + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(color: color.withValues(alpha: 0.8))), + ), + Align( + alignment: Alignment.centerRight, + child: TextButton.icon( + onPressed: () => MessageActions.openLocation(location), + icon: const Icon(Icons.map, size: 18), + label: Text('openInMaps'.tr()), + ), + ), + ], + ); } @override Widget build(BuildContext context) { + // A control message has no bubble of its own: it is one centred line. + if (widget.message.isSystem) { + return _systemPill(context); + } + bool showAvatar() { + if (widget.showAvatar != null) return widget.showAvatar!; if (widget.message.isMe) return false; // Show avatar if next message is null (last message) if (widget.nextMessage == null) return true; @@ -54,7 +289,9 @@ class _ChatBubbleState extends State { ? widget.previousMessage!.sentAt : widget.previousMessage!.receivedAt; - final currentTime = widget.message.isMe ? widget.message.sentAt : widget.message.receivedAt; + final currentTime = widget.message.isMe + ? widget.message.sentAt + : widget.message.receivedAt; final difference = currentTime.difference(previousTime).inMinutes; return difference >= 10; @@ -89,157 +326,501 @@ class _ChatBubbleState extends State { } } - Color bubbleBackground() { - var brightness = Theme.of(context).brightness; - if (widget.message.isMe) { - if (brightness == Brightness.dark) { - return Theme.of(context).colorScheme.secondary; - } - return Theme.of(context).colorScheme.primary; - } else { - if (brightness == Brightness.dark) { - return Theme.of(context).colorScheme.onSecondary; - } - return Theme.of(context).colorScheme.surfaceDim; + /// Gesture handling: select in selection mode, otherwise tooltip + reply. + void onTap() { + if (widget.selectionMode) { + widget.onSelect?.call(); + return; + } + setState(() { + _showTooltip = !_showTooltip; + }); + } + + void onLongPress() { + // A long press in selection mode does nothing: tapping already toggles. + if (widget.selectionMode) { + return; } + (widget.onActions ?? widget.onSelect)?.call(); } - Color bubbleTextColor() { - final backgroundColor = bubbleBackground(); - double luminance = backgroundColor.computeLuminance(); - return luminance > 0.5 ? Colors.black : Colors.white; + Widget content() { + // A view-once location is the single-view frame, not text; a plain one + // is a card with a pin and a way into the map app. + if (widget.message.viewOnce && !widget.message.isMedia) { + return _viewOnceMessage(context, widget.message.location); + } + if (widget.message.location case final location?) { + return _locationBubble(context, location, bubbleTextColor()); + } + // A tombstone is text even when it used to be an attachment. + if (widget.message.isMedia && !widget.message.isDeleted) { + return MediaBubble( + message: widget.message, + badge: widget.message.reactionEmojis.isEmpty + ? null + : GestureDetector( + onTap: _onBadgeTap, + child: _reactionBadge(), + ), + conversationUserId: widget.user.id, + bubbleColor: bubbleBackground(), + textColor: bubbleTextColor(), + // An album keeps its copies per item, so the retry has to walk them + // rather than look at the message's own media id. + canRetry: widget.message.isAlbum + ? widget.message.album.any((item) => + item.mediaId.isNotEmpty && + item.localPath == null && + (MessageNotifier().canRetryMedia(item.mediaId) || + item.keyB64 != null)) + : widget.message.mediaId != null && + (MessageNotifier().canRetryMedia(widget.message.mediaId!) || + widget.message.mediaRefJson != null), + onRetry: () { + if (widget.message.isAlbum) { + for (final item in widget.message.album) { + if (item.mediaId.isEmpty || item.localPath != null) { + continue; + } + if (MessageNotifier().canRetryMedia(item.mediaId)) { + MessageNotifier() + .retryMediaDownload(widget.user.id, item.mediaId); + } else { + MessageNotifier().downloadFromStored( + widget.user.id, widget.message, item.mediaId); + } + } + return; + } + final mediaId = widget.message.mediaId; + if (mediaId == null) { + return; + } + if (MessageNotifier().canRetryMedia(mediaId)) { + MessageNotifier().retryMediaDownload(widget.user.id, mediaId); + } else { + MessageNotifier() + .downloadFromStored(widget.user.id, widget.message, mediaId); + } + }, + ); + } + + final color = bubbleTextColor(); + if (widget.message.isDeleted) { + return Text( + 'messageDeleted'.tr(), + style: TextStyle(color: color, fontStyle: FontStyle.italic), + ); + } + if (widget.message.isUndecryptable) { + return Text( + 'messageUndecryptable'.tr(), + style: TextStyle(color: color, fontStyle: FontStyle.italic), + ); + } + + final text = FormattedText( + widget.message.message, + style: TextStyle( + color: color, + fontSize: _isLargeEmoji ? 40 : null, + ), + maxLines: _foldable && !_expanded ? 8 : null, + ); + if (!_foldable) { + return text; + } + return Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + text, + GestureDetector( + onTap: () => setState(() => _expanded = !_expanded), + child: Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + _expanded ? 'showLess'.tr() : 'showFull'.tr(), + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ); } + /// The quoted message above the body, tappable to jump to the original. + Widget quoteBlock() { + final reply = widget.message.replyTo; + if (reply == null) { + return const SizedBox.shrink(); + } + final color = bubbleTextColor(); + final fromMe = reply.senderId == Singleton().profile.user.id; + final author = fromMe + ? 'meText'.tr() + : (widget.user.username.isNotEmpty ? widget.user.username : '?'); + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: GestureDetector( + onTap: widget.onTapQuote, + child: Container( + constraints: const BoxConstraints(minWidth: 120), + padding: const EdgeInsets.only(left: 8, top: 4, bottom: 4), + decoration: BoxDecoration( + border: Border( + left: BorderSide(color: color.withValues(alpha: 0.8), width: 3), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + author, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + Text( + reply.preview.isEmpty ? 'mediaPhoto'.tr() : reply.preview, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: color.withValues(alpha: 0.8), + fontSize: 12, + ), + ), + ], + ), + ), + ), + ); + } + + final bubble = Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.message.forwarded) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + 'forwardedMessage'.tr(), + style: TextStyle( + color: bubbleTextColor().withValues(alpha: 0.8), + fontSize: 11, + fontStyle: FontStyle.italic, + ), + ), + ), + if (widget.message.isReply) quoteBlock(), + content(), + if (widget.message.isEdited) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + 'messageEdited'.tr(), + style: TextStyle( + color: bubbleTextColor().withValues(alpha: 0.7), + fontSize: 11, + fontStyle: FontStyle.italic, + ), + ), + ), + ], + ); + + // Emoji-only messages drop the bubble chrome and read large; an attachment + // is the bubble, so it is clipped to the corners instead of sitting inside + // a coloured frame. + final isMedia = widget.message.isMedia; + // A view-once location draws its own frame, so it needs no bubble chrome + // behind it either. + final ownChrome = isMedia || widget.message.viewOnce; + // Animated so a jump flashes in and fades out instead of popping. + final bubbleBox = AnimatedContainer( + duration: const Duration(milliseconds: 250), + curve: Curves.easeOut, + decoration: BoxDecoration( + // A reply needs a surface for its quote; the attachment below fills the + // rest of the bubble. + color: ownChrome + ? (widget.message.isReply ? bubbleBackground() : null) + : (_isLargeEmoji ? null : bubbleBackground()), + borderRadius: BorderRadius.circular(20), + ), + // Above the child: a border in the decoration would sit under an + // attachment that fills the bubble. + foregroundDecoration: (widget.selected || widget.highlight) + ? BoxDecoration( + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: Theme.of(context).colorScheme.primary, + width: 2, + ), + ) + : null, + padding: ownChrome + ? (widget.message.isReply + ? const EdgeInsets.fromLTRB(8, 8, 8, 0) + : EdgeInsets.zero) + : (_isLargeEmoji + ? EdgeInsets.zero + : const EdgeInsets.symmetric(horizontal: 16, vertical: 10)), + child: bubble, + ); + + // An attachment clips its own media; the bubble must stay unclipped when a + // reaction badge hangs over its bottom edge. The wrapper is always there and + // only stops clipping: toggling Container.clipBehavior adds or drops its + // clip widget, which re-mounts the attachment and throws the decoded image + // away - the white flash when a reaction was added. + // + // A round note is never clipped either: it is a circle that grows while it + // plays and clips itself, so the rounded rectangle would only cut it at the + // box edges. + final clippedBox = ownChrome + ? ClipRRect( + borderRadius: BorderRadius.circular(20), + clipBehavior: widget.message.reactionEmojis.isEmpty || + widget.message.isVideoNote + ? Clip.none + : Clip.antiAlias, + child: bubbleBox, + ) + : bubbleBox; + + // The reactions hang on the bubble's bottom edge as one badge, on the side + // opposite the bubble's own side, the way a messenger pins them there. + final bubbleWithBadge = + widget.message.reactionEmojis.isEmpty || widget.message.isMedia + ? clippedBox + : Stack( + clipBehavior: Clip.none, + children: [ + // The room for the badge is part of the stack: a child that + // hangs past its parent's edge still paints, but it never + // receives the tap that opens the reaction list. + Padding( + // Same 12 px the badge used to hang by, now reserved + // inside the stack so the badge stays tappable. + padding: const EdgeInsets.only(bottom: 12), + child: clippedBox, + ), + Positioned( + bottom: 0, + left: widget.message.isMe ? 8 : null, + right: widget.message.isMe ? null : 8, + child: GestureDetector( + onTap: _onBadgeTap, + child: _reactionBadge(), + ), + ), + ], + ); + return Padding( padding: EdgeInsets.only( left: widget.message.isMe ? 96 : 16, right: widget.message.isMe ? 16 : 96, top: isFromSameUser() ? 4 : 16, ), - child: Column( - crossAxisAlignment: - widget.message.isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start, + child: Row( + mainAxisAlignment: widget.message.isMe + ? MainAxisAlignment.end + : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, children: [ - AnimatedSize( - duration: const Duration(milliseconds: 200), - curve: Curves.easeInOut, - child: SizedBox( - width: double.infinity, - child: Column( - children: [ - if (_showTooltip && !shouldShowTime()) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Center( - child: Text( - formatDate( - widget.message.isMe ? widget.message.sentAt : widget.message.receivedAt), - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - ), - if (shouldShowTime()) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Center( - child: Text( - formatDate( - widget.message.isMe ? widget.message.sentAt : widget.message.receivedAt), - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - ), - ], + if (widget.selectionMode) + Padding( + padding: const EdgeInsets.only(right: 6), + child: Icon( + widget.selected + ? Icons.check_circle + : Icons.radio_button_unchecked, + size: 20, + color: Theme.of(context).colorScheme.primary, ), ), - ), - GestureDetector( - onTap: () { - setState(() { - _showTooltip = !_showTooltip; - }); - }, - child: Align( - alignment: - widget.message.isMe ? Alignment.centerRight : Alignment.centerLeft, - child: Row( - mainAxisAlignment: widget.message.isMe - ? MainAxisAlignment.end - : MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - if (!widget.message.isMe) - SizedBox( - width: 40, // 32 (avatar) + 8 (padding) - child: showAvatar() - ? Padding( - padding: const EdgeInsets.only(right: 8), - child: CircleAvatar( - radius: 16, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 14, - color: widget.user.avatarTextColor, - ), - ), - ), - ) - : null, - ), - Flexible( - child: Column( - crossAxisAlignment: widget.message.isMe - ? CrossAxisAlignment.end - : CrossAxisAlignment.start, + Flexible( + child: Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + children: [ + if (_showTooltip && !shouldShowTime()) _tooltip(formatDate), + if (shouldShowTime()) _tooltip(formatDate), + GestureDetector( + onTap: onTap, + onLongPress: onLongPress, + onDoubleTap: widget.selectionMode + ? null + : (widget.onQuickReact ?? widget.onReply), + child: Align( + alignment: widget.message.isMe + ? Alignment.centerRight + : Alignment.centerLeft, + child: Row( + mainAxisAlignment: widget.message.isMe + ? MainAxisAlignment.end + : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, children: [ - /* - // Show nick if (!widget.message.isMe) - Padding( - padding: const EdgeInsets.only(left: 12, bottom: 4), - child: Text( - widget.user.username, - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - */ - Container( - decoration: BoxDecoration( - color: bubbleBackground(), - borderRadius: BorderRadius.circular(20), + SizedBox( + width: 40, // 32 (avatar) + 8 (padding) + child: showAvatar() + ? Padding( + padding: const EdgeInsets.only(right: 8), + child: CircleAvatar( + radius: 16, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0] + .toUpperCase() + : '?', + style: TextStyle( + fontSize: 14, + color: widget.user.avatarTextColor, + ), + ), + ), + ) + : null, ), - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 10), - child: Text( - widget.message.message, - style: TextStyle( - color: bubbleTextColor(), - ), - softWrap: true, + Flexible( + child: Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + children: [ + Padding( + // The badge's room is inside the bubble's own + // stack, so this one only carries the swipe. + padding: EdgeInsets.zero, + child: widget.onReply != null && + !widget.selectionMode + ? Dismissible( + key: ValueKey( + 'reply|${widget.message.senderId}' + '|${widget.message.sentAt.microsecondsSinceEpoch}'), + direction: DismissDirection.horizontal, + // The swipe is an action, not a + // delete: the bubble springs back. + confirmDismiss: (_) async { + widget.onReply?.call(); + return false; + }, + background: _swipeBackground( + Alignment.centerLeft, + bubbleTextColor()), + secondaryBackground: _swipeBackground( + Alignment.centerRight, + bubbleTextColor()), + child: bubbleWithBadge, + ) + : bubbleWithBadge, + ), + // Outgoing messages show a clock while they are + // being sent and an error when the send failed. + if (widget.message.isMe && + widget.message.sendStatus != SendStatus.sent) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Tooltip( + message: widget.message.sendStatus == + SendStatus.failed + ? 'messageSendFailed'.tr() + : 'messageSending'.tr(), + child: Icon( + widget.message.sendStatus == + SendStatus.failed + ? Icons.error_outline + : Icons.schedule, + size: 13, + color: widget.message.sendStatus == + SendStatus.failed + ? Colors.red + : Colors.grey, + ), + ), + ), + // Only the newest own message carries a tick, and + // only when the peer's cursor covers it: a single + // "delivered" tick would be a claim this build + // cannot back, because the peer's receipt switch + // is their business. + if (widget.message.isMe && _readByPeer) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Tooltip( + message: 'messageRead'.tr(), + child: Icon( + Icons.done_all, + size: 13, + color: + Theme.of(context).colorScheme.primary, + ), + ), + ), + ], ), ), ], ), ), - ], - ), + ), + ], ), ), ], ), ); } + + /// Whether the peer's read cursor already covers this message. + bool get _readByPeer { + final readAt = widget.readAt; + return readAt != null && !widget.message.sentAt.isAfter(readAt); + } + + Widget _swipeBackground(Alignment alignment, Color color) { + return Container( + alignment: alignment, + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Icon(Icons.reply, color: color.withValues(alpha: 0.7)), + ); + } + + Widget _tooltip(String Function(DateTime) formatDate) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Center( + child: Text( + formatDate(widget.message.isMe + ? widget.message.sentAt + : widget.message.receivedAt), + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + ), + ), + ), + ); + } } diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index 3ef7b93..46964f8 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -2,59 +2,89 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/private_message.dart'; import '../models/user.dart'; +import '../utils/chat_date.dart'; +import '../utils/presence.dart'; class ChatListItem extends StatefulWidget { - const ChatListItem(this.user, this.lastMessage, this.onPressed, {super.key}); + const ChatListItem(this.user, this.lastMessage, this.onPressed, + {this.unreadCount = 0, this.pinned = false, this.peerReadAt, super.key}); final User user; final PrivateMessage lastMessage; final Function() onPressed; + /// Unread incoming messages of this conversation, for the badge. + final int unreadCount; + + /// Whether the conversation is pinned to the top of the list. + final bool pinned; + + /// Instant up to which the peer read this chat; null when the chat does not + /// publish receipts or they never read it. + final DateTime? peerReadAt; + @override State createState() => _ChatListItemState(); } class _ChatListItemState extends State { - String formatDate() { - final DateTime now = DateTime.now().toLocal(); - final DateTime messageDate = widget.lastMessage.receivedAt.toLocal(); - final int daysDifference = messageDate.difference(now).inDays; + @override + void initState() { + super.initState(); + PresenceNotifier.instance.addListener(_onPresenceChanged); + } - // Today - if (messageDate.day == now.day && - messageDate.month == now.month && - messageDate.year == now.year) { - return '${'todayText'.tr()} ${DateFormat.Hm().format(messageDate)}'; - } - // Yesterday - else if (daysDifference == -1) { - return '${'yesterdayText'.tr()} ${DateFormat.Hm().format(messageDate)}'; - } - // Last week - else if (daysDifference >= -7) { - return '${DateFormat.EEEE().format(messageDate)} ${DateFormat.Hm().format(messageDate)}'; - } - // This year - else if (messageDate.year == now.year) { - return DateFormat.MMMMd().format(messageDate); - } - // Different year - else { - return DateFormat.yMMMMd().format(messageDate); + @override + void dispose() { + PresenceNotifier.instance.removeListener(_onPresenceChanged); + super.dispose(); + } + + /// Presence and typing are ephemeral, so the row redraws on every change. + void _onPresenceChanged() { + if (mounted) { + setState(() {}); } } + /// Rounded counter, capped the way every messenger does it. + Widget _unreadBadge() { + final scheme = Theme.of(context).colorScheme; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: scheme.primary, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + widget.unreadCount > 99 ? '99+' : '${widget.unreadCount}', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: scheme.onPrimary, + ), + ), + ); + } + @override Widget build(BuildContext context) { /// Return message with or without "me: " prefix String getTitle() { String meText = widget.lastMessage.isMe ? '${'meText'.tr()}: ' : ''; - String msg = widget.lastMessage.message.length <= 12 - ? widget.lastMessage.message - : '${widget.lastMessage.message.substring(0, 12)}...'; + // Use preview text (caption, or a localized label for media). + String preview = widget.lastMessage.preview; + String msg = + preview.length <= 14 ? preview : '${preview.substring(0, 14)}...'; return meText + msg; } + final bool unread = widget.unreadCount > 0 || !widget.lastMessage.read; + // Same rule as the bubble's tick, so the row and the chat cannot disagree. + final bool seenByPeer = widget.lastMessage.isMe && + widget.peerReadAt != null && + !widget.lastMessage.sentAt.isAfter(widget.peerReadAt!); + return ListTile( onTap: widget.onPressed, tileColor: Colors.transparent, @@ -62,36 +92,111 @@ class _ChatListItemState extends State { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), - leading: CircleAvatar( - radius: 22, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 20, - color: widget.user.avatarTextColor, + leading: Stack( + clipBehavior: Clip.none, + children: [ + CircleAvatar( + radius: 22, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 20, + color: widget.user.avatarTextColor, + ), + ), ), - ), + // The dot is the whole status badge: presence is opt-in, so an + // absent dot means "not sharing", not "offline". + if (PresenceNotifier.instance.isOnline(widget.user.id) == true) + Positioned( + right: 0, + bottom: 0, + child: Container( + width: 12, + height: 12, + decoration: BoxDecoration( + color: const Color(0xFF2E7D32), + shape: BoxShape.circle, + border: Border.all( + color: Theme.of(context).scaffoldBackgroundColor, + width: 2, + ), + ), + ), + ), + ], ), - title: Text( - widget.user.username.isNotEmpty ? widget.user.username : '?', - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + title: Row( + children: [ + if (widget.pinned) + Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon(Icons.push_pin, + size: 14, color: Theme.of(context).colorScheme.primary), + ), + Expanded( + child: Text( + widget.user.username.isNotEmpty ? widget.user.username : '?', + overflow: TextOverflow.ellipsis, + style: + unread ? const TextStyle(fontWeight: FontWeight.bold) : null, + ), + ), + ], ), - subtitle: Text( - getTitle(), - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + subtitle: Row( + children: [ + // The last own message carries the peer's tick, the way the bubble + // does; a row that hides it makes "delivered" and "read" look alike. + if (seenByPeer) + Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon( + Icons.done_all, + size: 14, + color: Theme.of(context).colorScheme.primary, + ), + ), + Expanded( + child: Text( + // A typing peer outranks the last message; it clears itself. + PresenceNotifier.instance.isTyping(widget.user.id) + ? 'typing'.tr() + : getTitle(), + overflow: TextOverflow.ellipsis, + style: + unread ? const TextStyle(fontWeight: FontWeight.bold) : null, + ), + ), + ], ), - trailing: Text( - formatDate(), - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + trailing: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + chatDateLabel( + widget.lastMessage.receivedAt, + todayLabel: 'todayText'.tr(), + yesterdayLabel: 'yesterdayText'.tr(), + ), + style: unread + ? TextStyle( + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.primary, + ) + : null, + ), + if (widget.unreadCount > 0) + Padding( + padding: const EdgeInsets.only(top: 4), + child: _unreadBadge(), + ), + ], ), ); } diff --git a/lib/widgets/formatted_text.dart b/lib/widgets/formatted_text.dart new file mode 100644 index 0000000..e763b4e --- /dev/null +++ b/lib/widgets/formatted_text.dart @@ -0,0 +1,199 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/link_utils.dart'; +import '../utils/message_format.dart'; + +/// Message text with inline formatting, tappable links, phone numbers, +/// e-mail addresses and spoilers that stay covered until tapped. +class FormattedText extends StatefulWidget { + const FormattedText( + this.text, { + this.style, + this.maxLines, + this.textAlign, + super.key, + }); + + final String text; + final TextStyle? style; + final int? maxLines; + final TextAlign? textAlign; + + @override + State createState() => _FormattedTextState(); +} + +class _FormattedTextState extends State { + final Map _recognizers = {}; + + /// Indices of the spoiler pieces the user has opened this session. + final Set _revealed = {}; + + @override + void dispose() { + for (final recognizer in _recognizers.values) { + recognizer.dispose(); + } + super.dispose(); + } + + TapGestureRecognizer _recognizer(String key, VoidCallback onTap) { + return _recognizers.putIfAbsent( + key, () => TapGestureRecognizer()..onTap = onTap); + } + + Color get _color => + widget.style?.color ?? + DefaultTextStyle.of(context).style.color ?? + Colors.black; + + TextSpan _span(MessagePiece piece, int index) { + switch (piece.style) { + case MessageStyle.bold: + return TextSpan( + text: piece.text, + style: const TextStyle(fontWeight: FontWeight.bold)); + case MessageStyle.italic: + return TextSpan( + text: piece.text, + style: const TextStyle(fontStyle: FontStyle.italic)); + case MessageStyle.strike: + return TextSpan( + text: piece.text, + style: const TextStyle(decoration: TextDecoration.lineThrough)); + case MessageStyle.mono: + return TextSpan( + text: piece.text, + style: TextStyle( + fontFamily: 'monospace', + backgroundColor: _color.withValues(alpha: 0.12), + ), + ); + case MessageStyle.spoiler: + if (_revealed.contains(index)) { + return TextSpan( + text: piece.text, + style: + TextStyle(backgroundColor: _color.withValues(alpha: 0.15))); + } + return TextSpan( + text: List.filled(piece.text.length, '█').join(), + recognizer: _recognizer('spoiler:$index', () { + setState(() => _revealed.add(index)); + }), + ); + case MessageStyle.code: + case MessageStyle.plain: + break; + } + switch (piece.kind) { + case MessageKind.link: + return TextSpan( + text: piece.text, + recognizer: + _recognizer('link:${piece.text}', () => openLink(piece.text)), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.email: + return TextSpan( + text: piece.text, + recognizer: _recognizer( + 'mail:${piece.text}', () => openLink('mailto:${piece.text}')), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.phone: + // Underlined like a link: it is something the user taps, not just text. + return TextSpan( + text: piece.text, + recognizer: _recognizer( + 'copy:${piece.kind.name}:${piece.text}', () => _copy(piece.text)), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.text: + return TextSpan(text: piece.text); + } + } + + /// Underline for everything tappable: links, e-mails and phone numbers read + /// as a link. + TextStyle _inlineLink(TextDecorationStyle style) => TextStyle( + decoration: TextDecoration.underline, + decorationStyle: style, + decorationColor: _color, + ); + Future _copy(String value) async { + await Clipboard.setData(ClipboardData(text: value)); + Fluttertoast.showToast(msg: 'copiedText'.tr()); + } + + @override + Widget build(BuildContext context) { + final pieces = parseMessage(widget.text); + if (pieces.isEmpty) { + return Text('', style: widget.style); + } + // Code blocks read as their own block, so they get a container instead of + // an inline span. Whole-message maxLines cannot clip through a block. + // shortcut: a folded message with a code block still shows the block in + // full, upgrade with a real measurement pass when that shows up in practice. + final hasBlock = pieces.any((piece) => piece.style == MessageStyle.code); + if (!hasBlock) { + return Text.rich( + TextSpan(children: [ + for (var i = 0; i < pieces.length; i++) _span(pieces[i], i), + ]), + style: widget.style, + maxLines: widget.maxLines, + overflow: widget.maxLines == null ? null : TextOverflow.ellipsis, + textAlign: widget.textAlign, + ); + } + + final runs = []; + var inline = []; + void flushInline() { + if (inline.isEmpty) { + return; + } + runs.add(Text.rich(TextSpan(children: inline), style: widget.style)); + inline = []; + } + + for (var i = 0; i < pieces.length; i++) { + final piece = pieces[i]; + if (piece.style != MessageStyle.code) { + inline.add(_span(piece, i)); + continue; + } + flushInline(); + runs.add( + Container( + width: double.infinity, + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + decoration: BoxDecoration( + color: _color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + piece.text, + style: widget.style?.copyWith( + fontFamily: 'monospace', + fontSize: (widget.style?.fontSize ?? 14) * 0.9, + ), + ), + ), + ); + } + flushInline(); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: runs, + ); + } +} diff --git a/lib/widgets/invite_list_item.dart b/lib/widgets/invite_list_item.dart index 8b8acc0..d9de47b 100644 --- a/lib/widgets/invite_list_item.dart +++ b/lib/widgets/invite_list_item.dart @@ -2,28 +2,31 @@ import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:whisper_openapi_client_dart/api.dart'; +import 'package:sprintf/sprintf.dart'; +import 'package:shept_openapi_client_dart/api.dart'; +import '../utils/admin_format.dart'; + +/// One row of the admin invite list: the invited address and how long the +/// invitation is still valid. Mostly static, so it only rebuilds per minute. class InviteListItem extends StatefulWidget { const InviteListItem(this.invite, {super.key}); final ModelsInvite invite; @override - State createState() => _UserListItemState(); + State createState() => _InviteListItemState(); } -class _UserListItemState extends State { - late Timer _timer; +class _InviteListItemState extends State { + Timer? _timer; late Duration _remainingTime; @override void initState() { super.initState(); _remainingTime = widget.invite.validUntil.difference(DateTime.now()); - - // Start the timer to update every second - _timer = Timer.periodic(const Duration(seconds: 1), (timer) { + _timer = Timer.periodic(const Duration(minutes: 1), (_) { if (mounted) { setState(() { _remainingTime = widget.invite.validUntil.difference(DateTime.now()); @@ -33,36 +36,27 @@ class _UserListItemState extends State { } @override - Widget build(BuildContext context) { - // Stop when remaining time is negative - if (_remainingTime.isNegative) { - _timer.cancel(); - } - // Calculate absolute remaining time - Duration displayDuration = _remainingTime; - // Format display time - String displayTime = - displayDuration.toString().split('.').first.padLeft(8, '0'); + void dispose() { + _timer?.cancel(); + super.dispose(); + } + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final remaining = inviteRemaining(_remainingTime); return ListTile( - onTap: () {}, // Empty method so that the visual effect works tileColor: Colors.transparent, - selectedTileColor: Theme.of(context).colorScheme.primaryContainer, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - title: Text(widget.invite.mail), - trailing: Transform.scale( - scale: 1.3, - child: Text( - _remainingTime.isNegative ? 'inviteExpired'.tr() : displayTime, - style: TextStyle( - color: _remainingTime.isNegative - ? Colors.red - : Theme.of(context).colorScheme.secondary, - fontWeight: - _remainingTime.isNegative ? FontWeight.bold : FontWeight.normal, - ), + title: Text(widget.invite.mail, overflow: TextOverflow.ellipsis), + trailing: Text( + remaining == null + ? 'inviteExpired'.tr() + : sprintf( + 'inviteExpiresIn'.tr(), ['${remaining.value}', remaining.unit]), + style: TextStyle( + fontSize: 12, + color: remaining == null ? Colors.red : colors.secondary, + fontWeight: remaining == null ? FontWeight.bold : FontWeight.normal, ), ), ); diff --git a/lib/widgets/live_location_bubble.dart b/lib/widgets/live_location_bubble.dart new file mode 100644 index 0000000..1f32c2a --- /dev/null +++ b/lib/widgets/live_location_bubble.dart @@ -0,0 +1,144 @@ +import 'dart:async'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +import '../models/user.dart'; +import '../pages/live_location_page.dart'; +import '../utils/live_location.dart'; +import '../utils/presence.dart'; + +/// The live location as one bubble in the conversation: this device's or the +/// peer's, ticking with the time left. Tapping it opens the live view; nothing +/// is archived, so the bubble exists only while a session does. +class LiveLocationBubble extends StatefulWidget { + const LiveLocationBubble(this.peer, {this.showAvatar = true, super.key}); + + final User peer; + + /// Whether this bubble closes the peer's run of messages: the avatar is + /// drawn only there, like on every other bubble. + final bool showAvatar; + + @override + State createState() => _LiveLocationBubbleState(); +} + +class _LiveLocationBubbleState extends State { + Timer? _tick; + + @override + void initState() { + super.initState(); + // The remaining time is a clock, not an event: one rebuild a second. + _tick = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) { + setState(() {}); + } + }); + PresenceNotifier.instance.addListener(_onChanged); + } + + @override + void dispose() { + _tick?.cancel(); + PresenceNotifier.instance.removeListener(_onChanged); + super.dispose(); + } + + void _onChanged() { + if (mounted) { + setState(() {}); + } + } + + String _left(DateTime until) { + final left = until.difference(DateTime.now()); + if (left.isNegative) { + return '0:00'; + } + return '${left.inMinutes}:' + '${left.inSeconds.remainder(60).toString().padLeft(2, '0')}'; + } + + @override + Widget build(BuildContext context) { + final mine = LiveLocationSharer.instance.isSharing(widget.peer.id); + final theirs = PresenceNotifier.instance.liveLocation(widget.peer.id); + if (!mine && theirs == null) { + return const SizedBox.shrink(); + } + final scheme = Theme.of(context).colorScheme; + final until = mine ? LiveLocationSharer.instance.until : theirs?.until; + final label = mine ? 'liveLocationMine'.tr() : 'liveLocationTheirs'.tr(); + final color = mine ? scheme.primaryContainer : scheme.surfaceContainerHigh; + final textColor = + mine ? scheme.onPrimaryContainer : scheme.onSurfaceVariant; + + // Laid out like a message bubble of this chat: the same side, the same + // width limits and, incoming, the same avatar. + final bubble = Container( + constraints: const BoxConstraints(maxWidth: 260), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.my_location, size: 20, color: textColor), + const SizedBox(width: 8), + Flexible( + child: Text( + until == null ? label : '$label · ${_left(until)}', + style: TextStyle(color: textColor), + ), + ), + const SizedBox(width: 6), + Icon(Icons.chevron_right, size: 18, color: textColor), + ], + ), + ); + + return Padding( + padding: EdgeInsets.only( + left: mine ? 96 : 16, + right: mine ? 16 : 96, + top: 16, + ), + child: Row( + mainAxisAlignment: + mine ? MainAxisAlignment.end : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + if (!mine && widget.showAvatar) + Padding( + padding: const EdgeInsets.only(right: 8), + child: CircleAvatar( + radius: 16, + backgroundColor: widget.peer.avatarColor, + child: Text( + widget.peer.username.isNotEmpty + ? widget.peer.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 14, + color: widget.peer.avatarTextColor, + ), + ), + ), + ), + Flexible( + child: InkWell( + borderRadius: BorderRadius.circular(20), + onTap: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => LiveLocationPage(widget.peer))), + child: bubble, + ), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/media_bubble.dart b/lib/widgets/media_bubble.dart new file mode 100644 index 0000000..92223d4 --- /dev/null +++ b/lib/widgets/media_bubble.dart @@ -0,0 +1,907 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import '../utils/nav_transitions.dart'; +import 'package:video_player/video_player.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +import '../models/private_message.dart'; +import '../pages/media_viewer_page.dart'; +import '../utils/cache_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/message_actions.dart'; +import '../utils/singleton.dart'; +import 'view_once_frame.dart'; +import 'round_video_note.dart'; +import 'voice_player.dart'; + +/// Renders a media attachment inside a chat bubble: image/gif thumbnail, video +/// preview with a play overlay, an inline voice player, or an album grid. +/// Handles the download/loading/failed states for incoming media. +class MediaBubble extends StatefulWidget { + final PrivateMessage message; + final Color bubbleColor; + final Color textColor; + final VoidCallback onRetry; + final bool canRetry; + final String conversationUserId; + + /// Reaction badge drawn on the attachment's bottom corner. + final Widget? badge; + + const MediaBubble({ + required this.message, + required this.bubbleColor, + required this.textColor, + required this.onRetry, + required this.canRetry, + required this.conversationUserId, + this.badge, + super.key, + }); + + @override + State createState() => _MediaBubbleState(); +} + +class _MediaBubbleState extends State { + Future? _imageFuture; + + /// Path the current [_imageFuture] belongs to. The cache mutates the same + /// message instance in place, so comparing widget objects cannot detect a + /// finished download; the path can. + String? _imagePath; + + @override + void initState() { + super.initState(); + _prepareImage(); + } + + @override + void didUpdateWidget(covariant MediaBubble oldWidget) { + super.didUpdateWidget(oldWidget); + _prepareImage(); + } + + void _prepareImage() { + final path = widget.message.localPath; + if (path == _imagePath) { + return; + } + _imagePath = path; + final type = widget.message.mediaType; + final isImage = type == MediaType.image || type == MediaType.gif; + _imageFuture = path != null && isImage ? _decryptAfterFrame(path) : null; + } + + /// Lets the first frame land before paying for the decryption, so a chat + /// full of images does not stall the push animation. + Future _decryptAfterFrame(String path) async { + final firstFrame = Completer(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!firstFrame.isCompleted) { + firstFrame.complete(); + } + }); + await firstFrame.future; + return MediaUtils.decryptAtRest(path); + } + + /// Constrained display size derived from the original media dimensions. + /// Size the video player reported for this bubble, used when the stored + /// dimensions of an older message are the unrotated frame. + Size? _videoFrame; + + /// Fits [w]x[h] into the bubble's box. + Size _fitToBox(int w, int h) { + const maxW = 240.0; + const maxH = 320.0; + if (w <= 0 || h <= 0) { + return const Size(220, 220); + } + double dw = w.toDouble(); + double dh = h.toDouble(); + final scale = (maxW / dw).clamp(0.0, 1.0); + dw *= scale; + dh *= scale; + if (dh > maxH) { + final s = maxH / dh; + dh *= s; + dw *= s; + } + return Size(dw, dh); + } + + Size _displaySize() { + final frame = _videoFrame; + if (frame != null) { + return _fitToBox(frame.width.round(), frame.height.round()); + } + return _fitToBox(widget.message.width ?? 0, widget.message.height ?? 0); + } + + /// Takes the size the player sees (rotation included) and stores it, so an + /// older message stops showing a portrait video in a landscape bubble. + void _onVideoFrame(Size frame) { + if (_videoFrame == frame) { + return; + } + setState(() => _videoFrame = frame); + final width = frame.width.round(); + final height = frame.height.round(); + if (widget.message.width == width && widget.message.height == height) { + return; + } + CacheUtils.updateStoredMessage(widget.conversationUserId, widget.message, + (stored) { + stored.width = width; + stored.height = height; + }); + } + + /// A single-view attachment never shows a thumbnail: nobody sees it before + /// opening it, and the open happens exactly once. Its caption stays hidden + /// too, since it already shows inside the viewer once opened. An opened + /// attachment, and the sender's own copy, are read-only tombstones. + Widget _viewOnceWidget() { + final opened = widget.message.openedAt != null; + final mine = widget.message.isMe && + widget.conversationUserId != Singleton().profile.user.id; + // An album carries its copies per item; the message itself never has one. + final ready = widget.message.isAlbum + ? widget.message.album.isNotEmpty && + widget.message.album.every((item) => item.localPath != null) + : widget.message.localPath != null; + + if (mine) { + // The sender keeps no copy: one open is the recipient's, never theirs. + return ViewOnceFrame( + label: opened ? 'viewOnceOpenedByPeer'.tr() : 'viewOnceSent'.tr(), + bubbleColor: widget.bubbleColor, + textColor: widget.textColor, + ); + } + if (opened) { + return ViewOnceFrame( + label: 'viewOnceOpened'.tr(), + bubbleColor: widget.bubbleColor, + textColor: widget.textColor, + dimmed: true, + ); + } + return ViewOnceFrame( + label: ready ? 'viewOnceOpen'.tr() : 'viewOnceLoad'.tr(), + bubbleColor: widget.bubbleColor, + textColor: widget.textColor, + onTap: () { + if (!ready) { + if (widget.canRetry) { + widget.onRetry(); + } + return; + } + _openViewOnce(); + }, + ); + } + + /// Opens the one allowed view, then burns the attachment. + Future _openViewOnce() async { + final message = widget.message; + await Navigator.of(context).push( + fadeRoute( + Theme( + data: Theme.of(context), + child: MediaViewerPage( + message: message, + conversationUserId: widget.conversationUserId, + viewOnce: true, + ), + ), + ), + ); + if (!mounted) { + return; + } + await MessageActions.consumeViewOnce(widget.conversationUserId, message); + } + + void _openViewer({int albumIndex = 0}) { + final path = widget.message.localPath; + final type = widget.message.mediaType; + if (!widget.message.isAlbum && (path == null || type == null)) { + return; + } + Navigator.of(context).push( + fadeRoute( + // The viewer is a separate route; carry the chat theme over to it + Theme( + data: Theme.of(context), + child: MediaViewerPage( + message: widget.message, + conversationUserId: widget.conversationUserId, + albumIndex: albumIndex, + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final type = widget.message.mediaType; + final hasCaption = widget.message.message.isNotEmpty; + + if (widget.message.viewOnce) { + return _viewOnceWidget(); + } + + if (widget.message.isAlbum) { + return _albumWidget(hasCaption); + } + + final insideBubble = type == MediaType.voice || type == MediaType.file; + + Widget media; + if (widget.message.localPath != null) { + // The file on disk is the truth. A failed/expired status can be stale: a + // redelivered message used to re-try a download the server had already + // confirmed, which flipped a working attachment to expired. + switch (type) { + case MediaType.image: + case MediaType.gif: + case MediaType.sticker: + media = _imageWidget(); + break; + case MediaType.video: + media = _videoWidget(); + break; + case MediaType.voice: + media = _voiceWidget(); + break; + case MediaType.file: + media = _fileWidget(); + break; + case null: + media = _placeholder(child: const Icon(Icons.broken_image)); + } + } else if (insideBubble && + widget.message.downloadStatus == MediaDownloadStatus.pending) { + media = type == MediaType.voice + ? SizedBox( + width: 220, + height: 48, + child: Center( + child: CircularProgressIndicator(color: widget.textColor), + ), + ) + : _fileWidget(); + } else if (widget.message.downloadStatus == MediaDownloadStatus.pending) { + media = _pendingMedia(); + } else if (widget.message.downloadStatus == MediaDownloadStatus.failed || + widget.message.downloadStatus == MediaDownloadStatus.expired) { + media = _failed(); + } else { + media = _placeholder(child: const CircularProgressIndicator()); + } + + // Voice and file messages live inside the coloured bubble. + if (insideBubble) { + final box = Container( + decoration: BoxDecoration( + color: widget.bubbleColor, + borderRadius: BorderRadius.circular(20), + ), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: media, + ); + if (widget.badge == null) { + return box; + } + // The reaction hangs over the bubble's bottom edge, the way it does on a + // visual attachment. Dropping it here made a reaction on a voice message + // look like it never happened. + return Stack( + clipBehavior: Clip.none, + children: [ + // The room the badge hangs into is part of the stack: a child past + // the edge still paints, but it never receives the tap that opens the + // reaction list. + Padding( + padding: const EdgeInsets.only(bottom: 10), + child: box, + ), + Positioned( + bottom: 0, + left: widget.message.isMe ? 16 : null, + right: widget.message.isMe ? null : 16, + child: widget.badge!, + ), + ], + ); + } + + // A round note plays right here: opening a circle in the full-screen + // viewer loses the shape and the ring it was recorded with. + if (type == MediaType.video && widget.message.isVideoNote) { + final path = widget.message.localPath; + if (path != null) { + return _withCaption( + RoundVideoNote( + message: widget.message, + conversationId: widget.conversationUserId, + ), + hasCaption, + ); + } + // Still downloading, or gone: the circle keeps its shape either way. + return _withCaption( + ClipOval( + child: SizedBox(width: 200, height: 200, child: media), + ), + hasCaption, + ); + } + + // A sticker is drawn bare: no bubble, no rounded frame, its own size. + if (type == MediaType.sticker) { + return _withCaption( + SizedBox(width: 160, height: 160, child: Center(child: media)), + hasCaption, + ); + } + + // Visual media: rounded thumbnail with optional caption underneath. + return _withCaption(media, hasCaption); + } + + /// Album: two-column grid of thumbnails (four tiles max, the last one shows + /// how many are hidden) plus the shared caption. + Widget _albumWidget(bool hasCaption) { + final items = widget.message.album; + const tile = 110.0; + const gap = 4.0; + final shown = items.length > 4 ? 4 : items.length; + return _withCaption( + SizedBox( + width: tile * 2 + gap, + child: GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + mainAxisSpacing: gap, + crossAxisSpacing: gap, + ), + itemCount: shown, + itemBuilder: (context, index) { + final hidden = + items.length > 4 && index == 3 ? items.length - 3 : null; + return AlbumTile( + item: items[index], + hiddenCount: hidden, + onTap: () => _openViewer(albumIndex: index), + ); + }, + ), + ), + hasCaption, + ); + } + + Widget _withCaption(Widget media, bool hasCaption) { + return Column( + // Own messages sit on the right, so the caption does too. + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + // The badge hangs over the media's bottom edge, so its room sits inside + // the stack: outside it the badge would paint but never take a tap. The + // caption below starts under that room instead of over the badge. + Stack( + // The badge hangs over the bottom edge, so the stack must not clip. + clipBehavior: Clip.none, + children: [ + Padding( + padding: EdgeInsets.only(bottom: widget.badge == null ? 0 : 10), + child: ClipRRect( + borderRadius: BorderRadius.circular(16), + child: media, + ), + ), + // On the attachment itself: the corner of the media, not the level + // of the caption below it. Far enough from the corner that the + // rounded side does not cut it. + if (widget.badge != null) + Positioned( + bottom: 0, + left: widget.message.isMe ? 16 : null, + right: widget.message.isMe ? null : 16, + child: widget.badge!, + ), + ], + ), + if (hasCaption) + Container( + margin: const EdgeInsets.only(top: 4), + decoration: BoxDecoration( + color: widget.bubbleColor, + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + child: Text( + widget.message.message, + style: TextStyle(color: widget.textColor), + ), + ), + ], + ); + } + + /// A pending attachment waits for the network setting; the icon is also the + /// way to fetch it now. + Widget _pendingMedia() { + final retryable = widget.canRetry; + return InkWell( + onTap: retryable ? widget.onRetry : null, + child: Padding( + padding: const EdgeInsets.all(12), + child: retryable + ? Tooltip( + message: 'downloadMedia'.tr(), + child: Icon(Icons.download_for_offline_outlined, + size: 28, color: widget.textColor), + ) + : const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ); + } + + Widget _placeholder({required Widget child}) { + final size = _displaySize(); + return Container( + width: size.width, + height: size.height, + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(16), + ), + alignment: Alignment.center, + child: child, + ); + } + + Widget _failed() { + final size = _displaySize(); + return Container( + width: size.width, + height: size.height, + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(16), + ), + alignment: Alignment.center, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.error_outline, size: 32), + const SizedBox(height: 8), + Text('mediaDownloadFailed'.tr(), textAlign: TextAlign.center), + if (widget.canRetry) + TextButton.icon( + onPressed: widget.onRetry, + icon: const Icon(Icons.refresh), + label: Text('retry'.tr()), + ), + ], + ), + ); + } + + Widget _imageWidget() { + final size = _displaySize(); + return GestureDetector( + onTap: _openViewer, + child: FutureBuilder( + future: _imageFuture, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return _placeholder(child: const CircularProgressIndicator()); + } + if (!snapshot.hasData) { + return _placeholder(child: const Icon(Icons.broken_image)); + } + return Image.memory( + snapshot.data!, + width: size.width, + height: size.height, + fit: BoxFit.cover, + cacheWidth: MediaUtils.decodeWidth(context, size.width), + ); + }, + ), + ); + } + + Widget _videoWidget() { + final size = _displaySize(); + return GestureDetector( + onTap: _openViewer, + child: SizedBox( + width: size.width, + height: size.height, + child: Stack( + alignment: Alignment.center, + fit: StackFit.expand, + children: [ + VideoThumbnail( + path: widget.message.localPath, + onFrame: _onVideoFrame, + ), + Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.25), + borderRadius: BorderRadius.circular(16), + ), + ), + // Center gives the badge its intrinsic size; without it the + // StackFit.expand stack stretches the circle over the whole bubble. + Center( + child: Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.35), + shape: BoxShape.circle, + ), + padding: const EdgeInsets.all(4), + child: + const Icon(Icons.play_arrow, color: Colors.white, size: 24), + ), + ), + if (widget.message.durationMs != null) + Positioned( + right: 8, + bottom: 8, + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + _formatDuration(widget.message.durationMs!), + style: const TextStyle(color: Colors.white, fontSize: 11), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _voiceWidget() { + return VoicePlayer( + localPath: widget.message.localPath!, + durationMs: widget.message.durationMs, + color: widget.textColor, + conversationId: widget.conversationUserId, + sentAt: widget.message.sentAt, + waveform: widget.message.mediaReferences?.first.waveform, + ); + } + + /// Document bubble: icon, file name and size; opens the viewer's file page. + Widget _fileWidget() { + final name = widget.message.fileName ?? 'mediaFile'.tr(); + return GestureDetector( + onTap: _openViewer, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.message.downloadStatus == MediaDownloadStatus.pending) + SizedBox( + width: 32, + height: 32, + child: CircularProgressIndicator( + strokeWidth: 2, + color: widget.textColor, + ), + ) + else + Icon(MediaUtils.iconForFileName(widget.message.fileName), + color: widget.textColor, size: 32), + const SizedBox(width: 8), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 180), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: widget.textColor), + ), + if (widget.message.mediaSize != null) + Text( + MediaUtils.formatBytes(widget.message.mediaSize!), + style: TextStyle( + color: widget.textColor.withValues(alpha: 0.7), + fontSize: 11, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + + String _formatDuration(int ms) { + final d = Duration(milliseconds: ms); + final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = d.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } +} + +/// One tile of an album bubble: image/gif thumbnail, first video frame, or a +/// type icon, with its own download state. +class AlbumTile extends StatefulWidget { + final AlbumItem item; + + /// When set, this tile stands in for all remaining attachments. + final int? hiddenCount; + final VoidCallback onTap; + + const AlbumTile({ + required this.item, + required this.onTap, + this.hiddenCount, + super.key, + }); + + @override + State createState() => _AlbumTileState(); +} + +class _AlbumTileState extends State { + Future? _imageFuture; + String? _imagePath; + + @override + void initState() { + super.initState(); + _prepare(); + } + + @override + void didUpdateWidget(covariant AlbumTile oldWidget) { + super.didUpdateWidget(oldWidget); + _prepare(); + } + + void _prepare() { + final path = widget.item.localPath; + if (path == _imagePath) { + return; + } + _imagePath = path; + final type = widget.item.mediaType; + final isImage = type == MediaType.image || type == MediaType.gif; + _imageFuture = + path != null && isImage ? MediaUtils.decryptAtRest(path) : null; + } + + @override + Widget build(BuildContext context) { + final item = widget.item; + final type = item.mediaType; + Widget content; + if (widget.hiddenCount != null && widget.hiddenCount! > 0 && item.isReady) { + content = Stack( + fit: StackFit.expand, + children: [ + _thumbnail(type), + Container( + color: Colors.black.withValues(alpha: 0.5), + alignment: Alignment.center, + child: Text( + '+${widget.hiddenCount}', + style: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold), + ), + ), + ], + ); + } else if (item.status == MediaDownloadStatus.failed || + item.status == MediaDownloadStatus.expired) { + content = const Center(child: Icon(Icons.error_outline)); + } else if (!item.isReady) { + content = const Center(child: CircularProgressIndicator(strokeWidth: 2)); + } else { + content = _thumbnail(type); + } + + return GestureDetector( + onTap: widget.onTap, + child: ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Container( + color: Colors.black.withValues(alpha: 0.1), + child: content, + ), + ), + ); + } + + Widget _thumbnail(MediaType? type) { + switch (type) { + case MediaType.image: + case MediaType.gif: + case MediaType.sticker: + return FutureBuilder( + future: _imageFuture, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Center( + child: CircularProgressIndicator(strokeWidth: 2)); + } + if (!snapshot.hasData) { + return const Center(child: Icon(Icons.broken_image)); + } + // Album tiles are 110 wide (see _albumWidget); decoding the full + // photo for one of them is what made a grid of attachments crawl. + return Image.memory(snapshot.data!, + fit: BoxFit.cover, + cacheWidth: MediaUtils.decodeWidth(context, 110)); + }, + ); + case MediaType.video: + return Stack( + fit: StackFit.expand, + children: [ + VideoThumbnail(path: widget.item.localPath), + const Center( + child: Icon(Icons.play_circle_outline, + color: Colors.white, size: 20)), + ], + ); + case MediaType.voice: + return const Center(child: Icon(Icons.mic)); + case MediaType.file: + return Center( + child: Icon(MediaUtils.iconForFileName(widget.item.fileName))); + case null: + return const Center(child: Icon(Icons.broken_image)); + } + } +} + +/// First frame of an encrypted-at-rest video, used as a bubble thumbnail. +/// Materializes a temporary plaintext file for the platform player and +/// releases both when the bubble is disposed. +class VideoThumbnail extends StatefulWidget { + final String? path; + + /// Called once the frame is known, with the rotation already applied. + final ValueChanged? onFrame; + + const VideoThumbnail({this.path, this.onFrame, super.key}); + + @override + State createState() => _VideoThumbnailState(); +} + +class _VideoThumbnailState extends State { + VideoPlayerController? _controller; + File? _tempFile; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void didUpdateWidget(covariant VideoThumbnail oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.path != widget.path) { + _disposeController(); + _load(); + } + } + + Future _load() async { + final path = widget.path; + if (path == null) { + return; + } + try { + final temp = await MediaUtils.materializeTempFile( + path, MediaUtils.extensionForType(MediaType.video)); + final controller = VideoPlayerController.file(temp); + await controller.initialize(); + await controller.setVolume(0); + // The player already applies the recorded rotation, so this is the size + // the frame really has. It also repairs a message stored with the + // unrotated dimensions. + final size = controller.value.size; + if (size.width > 0 && size.height > 0) { + widget.onFrame?.call(size); + } + if (!mounted) { + await controller.dispose(); + MediaUtils.deleteLocalFile(temp.path); + return; + } + setState(() { + _tempFile = temp; + _controller = controller; + }); + } catch (_) { + // The gradient fallback stays visible. + } + } + + void _disposeController() { + _controller?.dispose(); + _controller = null; + final temp = _tempFile; + _tempFile = null; + if (temp != null) { + MediaUtils.deleteLocalFile(temp.path); + } + } + + @override + void dispose() { + _disposeController(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + if (controller == null || !controller.value.isInitialized) { + return DecoratedBox( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [Color(0xFF2B2B2B), Color(0xFF000000)], + ), + ), + ); + } + return FittedBox( + fit: BoxFit.cover, + clipBehavior: Clip.hardEdge, + child: SizedBox( + width: controller.value.size.width, + height: controller.value.size.height, + child: VideoPlayer(controller), + ), + ); + } +} diff --git a/lib/widgets/pinned_round_note.dart b/lib/widgets/pinned_round_note.dart new file mode 100644 index 0000000..7e9f8d3 --- /dev/null +++ b/lib/widgets/pinned_round_note.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +import '../utils/round_note_playback.dart'; +import 'round_note_circle.dart'; + +/// The playing note as it looks once its circle leaves the chat's viewport: +/// the same player, 48 dp, hanging under the pinned-message strip. +/// +/// Tap pauses (and resumes) the note; a horizontal swipe throws the copy away +/// and stops playback. The circle it renders is the same widget the inline note +/// uses, so moving between the two never restarts the video. +class PinnedRoundNote extends StatelessWidget { + const PinnedRoundNote({required this.playback, this.size = 144, super.key}); + + final RoundNotePlayback playback; + final double size; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: playback, + builder: (context, _) { + final controller = playback.controller; + if (!playback.pinned || + controller == null || + !controller.value.isInitialized) { + return const SizedBox.shrink(); + } + return GestureDetector( + onTap: playback.toggle, + onHorizontalDragEnd: (_) => playback.dismiss(), + child: Material( + elevation: 6, + shape: const CircleBorder(), + clipBehavior: Clip.antiAlias, + color: Colors.black, + child: RoundNoteCircle( + controller: controller, + size: size, + showTime: false, + ), + ), + ); + }, + ); + } +} diff --git a/lib/widgets/round_note_circle.dart b/lib/widgets/round_note_circle.dart new file mode 100644 index 0000000..49137c7 --- /dev/null +++ b/lib/widgets/round_note_circle.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; + +/// The circle of a round note: the video, the ring that fills as it plays, the +/// play badge when it is not playing and, inline only, the running time. +/// +/// Shared by the inline note and the floating copy so both keep one geometry: +/// the indicator draws its stroke inside its box by default, so the video is +/// inset by the same 2 dp and the ring's path is inset by its 4 dp stroke - +/// that lands the ring's outer edge exactly on the video's circle instead of on +/// the bubble's clip, which used to shave it flat at all four sides. +class RoundNoteCircle extends StatelessWidget { + const RoundNoteCircle({ + required this.controller, + required this.size, + this.showTime = true, + super.key, + }); + + final VideoPlayerController controller; + final double size; + + /// The inline note shows how far it got; the 48 dp copy has no room for it. + final bool showTime; + + static const double _strokeWidth = 4; + + String _format(Duration duration) { + final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + @override + Widget build(BuildContext context) { + final ring = Theme.of(context).colorScheme.primary; + return ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) { + final total = value.duration.inMilliseconds; + final played = value.position.inMilliseconds.clamp(0, total); + final progress = total == 0 ? 0.0 : played / total; + return SizedBox( + width: size, + height: size, + child: Stack( + alignment: Alignment.center, + children: [ + Padding( + padding: const EdgeInsets.all(2), + child: ClipOval( + child: SizedBox.expand( + child: FittedBox( + fit: BoxFit.cover, + child: SizedBox( + width: controller.value.size.width, + height: controller.value.size.height, + child: VideoPlayer(controller), + ), + ), + ), + ), + ), + // How much of the note is left, as a ring that fills as it plays. + Padding( + padding: const EdgeInsets.all(_strokeWidth), + child: SizedBox.expand( + child: CircularProgressIndicator( + value: progress, + strokeWidth: _strokeWidth, + strokeAlign: BorderSide.strokeAlignCenter, + strokeCap: StrokeCap.round, + backgroundColor: Colors.black.withValues(alpha: 0.25), + valueColor: AlwaysStoppedAnimation(ring), + ), + ), + ), + if (!value.isPlaying) + Container( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.35), + shape: BoxShape.circle, + ), + padding: EdgeInsets.all(size * 0.04), + child: Icon( + Icons.play_arrow, + color: Colors.white, + size: size * 0.15, + ), + ), + if (showTime) + Positioned( + // Just above the video's rim, low enough to read as part of + // the note rather than as a caption. + bottom: 6, + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.45), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + _format(Duration(milliseconds: played)), + style: const TextStyle(color: Colors.white, fontSize: 11), + ), + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/widgets/round_video_note.dart b/lib/widgets/round_video_note.dart new file mode 100644 index 0000000..5a0c454 --- /dev/null +++ b/lib/widgets/round_video_note.dart @@ -0,0 +1,301 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; + +import '../models/private_message.dart'; +import '../utils/cache_utils.dart'; +import '../utils/media_autoplay.dart'; +import '../utils/media_utils.dart'; +import '../utils/round_note_playback.dart'; +import 'round_note_circle.dart'; + +/// A round video note, played in the chat instead of opening the viewer. +/// +/// The circle is the note itself: a filling ring runs around it as it plays and +/// the time sits under the picture, the way it looked while recording. The +/// circle keeps the player; while it is the live note it stays alive after it +/// scrolls out of sight, so the floating copy (`PinnedRoundNote`) can keep +/// rendering the same player. +class RoundVideoNote extends StatefulWidget { + const RoundVideoNote({ + required this.message, + required this.conversationId, + this.size = 200, + super.key, + }); + + final PrivateMessage message; + + /// The chat this note lives in: with the send time it is the key the chain + /// and the floating copy look for. + final String conversationId; + + final double size; + + @override + State createState() => _RoundVideoNoteState(); +} + +class _RoundVideoNoteState extends State + with WidgetsBindingObserver, AutomaticKeepAliveClientMixin { + VideoPlayerController? _controller; + File? _tempFile; + bool _failed = false; + + ScrollableState? _scrollable; + RoundNotePlayback? _playback; + bool _reportScheduled = false; + + late final String _key = + CacheUtils.messageKey(widget.conversationId, widget.message.sentAt); + + bool get _live => _playback?.key == _key; + + bool get playing => _controller?.value.isPlaying ?? false; + + /// How much bigger a playing note is than a resting one. The bubble reserves + /// the grown size, and 15 % is all the bubble's 16 dp screen inset allows. + static const double _growth = 1.15; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + MediaAutoplay.request.addListener(_onAutoplayRequest); + _prepare(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _playback = RoundNoteScope.maybeOf(context); + final scrollable = Scrollable.maybeOf(context); + if (!identical(scrollable, _scrollable)) { + _scrollable?.position.removeListener(_scheduleReport); + _scrollable = scrollable; + _scrollable?.position.addListener(_scheduleReport); + } + } + + /// The circle stays mounted while it is the live note: without that its + /// player (and the floating copy) would die the moment it leaves the viewport. + @override + bool get wantKeepAlive => _live && (_playback?.active ?? false); + + Future _prepare() async { + try { + final temp = await MediaUtils.materializeTempFile( + widget.message.localPath!, '.mp4'); + final controller = VideoPlayerController.file(temp); + await controller.initialize(); + await controller.setLooping(false); + await controller.setVolume(1); + if (!mounted) { + await controller.dispose(); + MediaUtils.deleteLocalFile(temp.path); + return; + } + setState(() { + _tempFile = temp; + _controller = controller; + }); + _reportVisibility(); + } catch (_) { + if (mounted) { + setState(() => _failed = true); + } + } + } + + /// Starts this note when the previous one finished and asked for it. + void _onAutoplayRequest() { + if (MediaAutoplay.request.value != _key) { + return; + } + MediaAutoplay.request.value = null; + _start(); + } + + Future _start() async { + final controller = _controller; + final playback = _playback; + if (controller == null || playback == null) { + return; + } + await playback.start( + key: _key, + conversationId: widget.conversationId, + sentAt: widget.message.sentAt, + controller: controller, + ); + updateKeepAlive(); + } + + Future _toggle() async { + final playback = _playback; + final controller = _controller; + if (playback == null || controller == null) { + return; + } + if (_live && controller.value.isPlaying) { + await playback.pause(); + return; + } + await _start(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + return; + } + final playback = _playback; + if (_live && playback != null) { + playback.pause(); + } else { + _controller?.pause(); + } + } + + /// A scroll notification arrives before the frame that moves this note, so + /// measuring right away reads the old (or detached) box and the floating copy + /// would stay up after the note came back into sight. Measure after the + /// frame instead. + void _scheduleReport() { + if (_reportScheduled) { + return; + } + _reportScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _reportScheduled = false; + if (mounted) { + _reportVisibility(); + } + }); + } + + /// Reports how much of the circle is on screen; the floating copy appears + /// once less than half of it is. + void _reportVisibility() { + final playback = _playback; + if (playback == null || playback.key != _key) { + return; + } + final position = _scrollable?.position; + final box = context.findRenderObject() as RenderBox?; + final viewport = _scrollable?.context.findRenderObject() as RenderBox?; + if (box == null || + !box.attached || + viewport == null || + !viewport.attached) { + playback.updateVisibility(_key, 0); + return; + } + var rect = box.localToGlobal(Offset.zero) & box.size; + final area = viewport.localToGlobal(Offset.zero) & viewport.size; + if (position != null) { + // A rubber band drags the whole list with the finger, so a bounce over the + // note made the floating copy vanish and come back on release. Measure + // where the note will sit once the list settles instead. + final overscroll = position.pixels - + position.pixels + .clamp(position.minScrollExtent, position.maxScrollExtent); + if (overscroll != 0) { + final settled = position.axisDirection == AxisDirection.up + ? overscroll + : -overscroll; + rect = rect.shift(Offset(0, -settled)); + } + } + playback.updateVisibility(_key, visibleFraction(rect, area)); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + MediaAutoplay.request.removeListener(_onAutoplayRequest); + _scrollable?.position.removeListener(_scheduleReport); + _playback?.detach(_key); + _controller?.dispose(); + final temp = _tempFile; + if (temp != null) { + MediaUtils.deleteLocalFile(temp.path); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + super.build(context); + final controller = _controller; + if (_failed) { + return SizedBox( + width: widget.size, + height: widget.size, + child: Center( + child: Text( + 'mediaError'.tr(), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, fontSize: 12), + ), + ), + ); + } + if (controller == null || !controller.value.isInitialized) { + return SizedBox( + width: widget.size, + height: widget.size, + child: const Center(child: CircularProgressIndicator()), + ); + } + final playback = _playback; + // One VideoPlayer per player: while the floating copy shows the video the + // circle (which is out of sight anyway) keeps only its dark disc. + final pinned = playback != null && _live && playback.pinned; + // Reported after every layout: new messages shift the viewport without a + // scroll event. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _reportVisibility(); + } + }); + return GestureDetector( + onTap: _toggle, + child: SizedBox( + // The bubble always reserves the grown size: a circle that changes the + // item's height would re-lay the list out under the user's thumb every + // time a note starts or ends. + width: widget.size * _growth, + height: widget.size * _growth, + child: Center( + child: TweenAnimationBuilder( + // The video is a texture: it paints only inside its own layout box, + // so the growth has to be a real size (a Transform or OverflowBox + // leaves the picture at 200 dp while the ring moves out). + tween: Tween(end: _live && playing ? 1 : 1 / _growth), + duration: const Duration(milliseconds: 180), + curve: Curves.easeOut, + builder: (context, factor, _) { + final side = widget.size * _growth * factor; + return pinned + ? ClipOval( + child: Container( + width: side, + height: side, + color: Colors.black, + ), + ) + : RoundNoteCircle( + controller: controller, + size: side, + showTime: side >= 100, + ); + }, + ), + ), + ), + ); + } +} diff --git a/lib/widgets/select_user_list_item.dart b/lib/widgets/select_user_list_item.dart deleted file mode 100644 index 17e5291..0000000 --- a/lib/widgets/select_user_list_item.dart +++ /dev/null @@ -1,51 +0,0 @@ -import 'package:flutter/material.dart'; -import '../models/user.dart'; - -class SelectUserListItem extends StatefulWidget { - const SelectUserListItem(this.user, this.valueChanged, {super.key}); - - final User user; - final Function(bool) valueChanged; - - @override - State createState() => _SelectUserListItemState(); -} - -class _SelectUserListItemState extends State { - bool _isSelected = false; - - @override - Widget build(BuildContext context) { - return ListTile( - onTap: () {}, // Empty method so that the visual effect works - tileColor: Colors.transparent, - selectedTileColor: Theme.of(context).colorScheme.primaryContainer, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - ), - leading: CircleAvatar( - radius: 22, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 20, - color: widget.user.avatarTextColor, - ), - ), - ), - title: Text(widget.user.username), - trailing: Checkbox( - value: _isSelected, - onChanged: (_) { - setState(() { - _isSelected = !_isSelected; - widget.valueChanged(_isSelected); - }); - }, - ), - ); - } -} diff --git a/lib/widgets/settings_tile.dart b/lib/widgets/settings_tile.dart new file mode 100644 index 0000000..4e817d8 --- /dev/null +++ b/lib/widgets/settings_tile.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +/// One settings-style row with a fixed height, so rows look the same whether +/// they end in a switch, a badge or nothing. +class SettingsTile extends StatelessWidget { + const SettingsTile({ + super.key, + required this.icon, + required this.label, + this.onPressed, + this.trailing, + this.extra, + this.color, + }); + + final IconData icon; + final String label; + final VoidCallback? onPressed; + + /// Widget at the right edge, e.g. a switch. + final Widget? trailing; + + /// Widget right after the label, e.g. a colour dot. + final Widget? extra; + + /// Tint for icon and label; inherited from the button theme when null. + final Color? color; + + @override + Widget build(BuildContext context) { + return TextButton( + onPressed: onPressed, + style: TextButton.styleFrom( + alignment: Alignment.centerLeft, + minimumSize: const Size.fromHeight(48), + padding: const EdgeInsets.symmetric(horizontal: 16), + ), + child: Row( + children: [ + Icon(icon, size: 24, color: color), + Padding( + padding: const EdgeInsets.only(left: 5), + child: Text(label, style: TextStyle(color: color)), + ), + if (extra != null) extra!, + if (trailing != null) const Spacer(), + if (trailing != null) trailing!, + ], + ), + ); + } +} diff --git a/lib/widgets/sticker_sheet.dart b/lib/widgets/sticker_sheet.dart new file mode 100644 index 0000000..aabad6d --- /dev/null +++ b/lib/widgets/sticker_sheet.dart @@ -0,0 +1,125 @@ +import 'dart:typed_data'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/dialog_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/sticker_store.dart'; + +/// The local sticker collection: tap one to send it, long-press to delete, +/// "+" to import a picture from a file. +class StickerSheet extends StatefulWidget { + const StickerSheet({super.key}); + + /// Shows the collection and returns the sticker the user picked, or null. + static Future show(BuildContext context) { + return showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (_) => const StickerSheet(), + ); + } + + @override + State createState() => _StickerSheetState(); +} + +class _StickerSheetState extends State { + List _stickers = const []; + bool _loading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + final stickers = await StickerStore.all(); + if (!mounted) { + return; + } + setState(() { + _stickers = stickers; + _loading = false; + }); + } + + Future _import() async { + final picked = await MediaUtils.pickMultipleMediaFromGallery(); + var added = 0; + for (final file in picked) { + final sticker = await StickerStore.add( + await file.readAsBytes(), MediaUtils.baseName(file.path)); + if (sticker != null) { + added++; + } + } + if (picked.isNotEmpty && added == 0) { + await Fluttertoast.showToast( + msg: 'stickerUnsupported'.tr(), backgroundColor: Colors.orange); + } + await _load(); + } + + Future _delete(Sticker sticker) async { + await DialogUtils.yesNoDialog( + context, 'deleteSticker'.tr(), 'deleteStickerConfirm'.tr(), () async { + await StickerStore.remove(sticker); + await _load(); + }); + } + + @override + Widget build(BuildContext context) { + return SafeArea( + child: SizedBox( + height: 320, + child: _loading + ? const Center(child: CircularProgressIndicator()) + : GridView.builder( + padding: const EdgeInsets.all(12), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 4, + mainAxisSpacing: 8, + crossAxisSpacing: 8, + ), + itemCount: _stickers.length + 1, + itemBuilder: (context, index) { + if (index == _stickers.length) { + return InkWell( + onTap: _import, + child: DecoratedBox( + decoration: BoxDecoration( + border: + Border.all(color: Theme.of(context).dividerColor), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.add), + ), + ); + } + final sticker = _stickers[index]; + return GestureDetector( + onTap: () => Navigator.pop(context, sticker), + onLongPress: () => _delete(sticker), + child: FutureBuilder( + future: MediaUtils.decryptAtRest(sticker.path), + builder: (context, snapshot) { + if (!snapshot.hasData) { + return const Center( + child: CircularProgressIndicator(strokeWidth: 2)); + } + return Image.memory(snapshot.data!, + fit: BoxFit.contain); + }, + ), + ); + }, + ), + ), + ); + } +} diff --git a/lib/widgets/theme_palette.dart b/lib/widgets/theme_palette.dart new file mode 100644 index 0000000..3d53f19 --- /dev/null +++ b/lib/widgets/theme_palette.dart @@ -0,0 +1,202 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +/// Seed colors offered as swatches: the app theme and the per-chat theme draw +/// from the same list, so a color picked in one place exists in the other. +const List themeSeeds = [ + Colors.blue, + Colors.indigo, + Colors.deepPurple, + Colors.pink, + Colors.red, + Colors.orange, + Colors.amber, + Colors.green, + Colors.teal, + Colors.cyan, + Colors.brown, + Colors.blueGrey, +]; + +/// Whether [color] is one of [themeSeeds]. Compared by value: a stored theme +/// rebuilds its MaterialColor, so identity never matches. +bool isSeedColor(Color? color) { + if (color == null) { + return false; + } + return themeSeeds.any((seed) => seed.toARGB32() == color.toARGB32()); +} + +/// Live sample of a theme: a bubble of each side and a filled button. +/// +/// [seed] is the color the sample is tinted with, the global app color when +/// null. +class ThemePreview extends StatelessWidget { + const ThemePreview({super.key, required this.seed}); + + final Color? seed; + + @override + Widget build(BuildContext context) { + final scheme = ColorScheme.fromSeed( + seedColor: seed ?? Theme.of(context).colorScheme.primary, + brightness: Theme.of(context).brightness, + ); + + Widget bubble(String text, {required bool mine}) { + return Align( + alignment: mine ? Alignment.centerRight : Alignment.centerLeft, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: mine ? scheme.primary : scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(16), + ), + child: Text( + text, + style: TextStyle( + fontSize: 13, + color: mine ? scheme.onPrimary : scheme.onSurface, + ), + ), + ), + ); + } + + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: scheme.surfaceContainerLow, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: scheme.outlineVariant), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + bubble('themePreviewPeer'.tr(), mine: false), + const SizedBox(height: 6), + bubble('themePreviewOwn'.tr(), mine: true), + const SizedBox(height: 10), + FilledButton( + onPressed: () {}, + child: Text('themePreviewButton'.tr()), + ), + ], + ), + ); + } +} + +/// Round seed swatches with the controls that sit next to them in a theme +/// dialog: a custom color and, when a chat may inherit, the global one. +class ThemePalette extends StatelessWidget { + const ThemePalette({ + super.key, + required this.selected, + this.onPicked, + this.onCustom, + this.onInherit, + this.inheritSelected = false, + }); + + /// The seed in use, null when the theme inherits the global color. + final Color? selected; + + final ValueChanged? onPicked; + final VoidCallback? onCustom; + + /// Present when "use the global theme" is a choice of its own. + final VoidCallback? onInherit; + final bool inheritSelected; + + @override + Widget build(BuildContext context) { + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + if (onInherit != null) + _Swatch( + key: const ValueKey('themeSwatch-global'), + color: null, + selected: inheritSelected, + icon: Icons.public, + tooltip: 'useGlobalTheme'.tr(), + onTap: onInherit, + ), + for (var i = 0; i < themeSeeds.length; i++) + _Swatch( + key: ValueKey('themeSwatch-$i'), + color: themeSeeds[i], + selected: selected?.toARGB32() == themeSeeds[i].toARGB32(), + onTap: onPicked == null ? null : () => onPicked!(themeSeeds[i]), + ), + // A hand picked color is not in the palette, and it still has to show + // as the current choice. + _Swatch( + key: const ValueKey('themeSwatch-custom'), + color: isSeedColor(selected) ? null : selected, + selected: selected != null && !isSeedColor(selected), + icon: + isSeedColor(selected) || selected == null ? Icons.colorize : null, + onTap: onCustom, + ), + ], + ); + } +} + +/// One round swatch, with a check when it is the one in use. +class _Swatch extends StatelessWidget { + const _Swatch({ + super.key, + required this.color, + required this.selected, + this.icon, + this.tooltip, + this.onTap, + }); + + final Color? color; + final bool selected; + final IconData? icon; + final String? tooltip; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final mark = selected ? Icons.check : icon; + final widget = InkWell( + onTap: onTap, + customBorder: const CircleBorder(), + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + border: Border.all( + color: color == null ? scheme.outline : scheme.outlineVariant, + ), + ), + child: mark == null + ? null + : Icon( + mark, + size: 20, + color: color == null + ? scheme.onSurfaceVariant + : ThemeData.estimateBrightnessForColor(color!) == + Brightness.dark + ? Colors.white + : Colors.black, + ), + ), + ); + if (tooltip == null) { + return widget; + } + return Tooltip(message: tooltip!, child: widget); + } +} diff --git a/lib/widgets/typing_dots.dart b/lib/widgets/typing_dots.dart new file mode 100644 index 0000000..d897030 --- /dev/null +++ b/lib/widgets/typing_dots.dart @@ -0,0 +1,80 @@ +import 'dart:math' as math; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; + +/// Three dots that pulse in sequence, the messenger-style "typing" hint. Only +/// in the tree while the peer is typing, so the animation runs only then; a +/// platform that asks for reduced motion gets a static ellipsis instead. +class TypingDots extends StatefulWidget { + const TypingDots({this.color, this.dotSize = 6, super.key}); + + final Color? color; + final double dotSize; + + @override + State createState() => _TypingDotsState(); +} + +class _TypingDotsState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1200), + )..repeat(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final color = + widget.color ?? Theme.of(context).colorScheme.onSurfaceVariant; + final static = MediaQuery.disableAnimationsOf(context); + + return Semantics( + label: 'typing'.tr(), + child: static + ? Text('…', + style: TextStyle( + color: color, + fontSize: widget.dotSize * 2, + height: 1, + )) + : AnimatedBuilder( + animation: _controller, + builder: (context, _) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (var i = 0; i < 3; i++) + Padding( + padding: EdgeInsets.only(right: i == 2 ? 0 : 3), + child: _dot(color, i), + ), + ], + ), + ), + ); + } + + /// One dot: a sine bump of opacity and lift, each starting a little later + /// than the previous one. + Widget _dot(Color color, int index) { + final phase = (_controller.value - index * 0.12) % 1.0; + final bump = math.sin(phase * math.pi); + return Transform.translate( + offset: Offset(0, -2 * bump), + child: Container( + width: widget.dotSize, + height: widget.dotSize, + decoration: BoxDecoration( + color: color.withValues(alpha: 0.35 + 0.65 * bump), + shape: BoxShape.circle, + ), + ), + ); + } +} diff --git a/lib/widgets/user_list_item.dart b/lib/widgets/user_list_item.dart index a201bf4..7271686 100644 --- a/lib/widgets/user_list_item.dart +++ b/lib/widgets/user_list_item.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import '../models/user.dart'; +import '../utils/presence.dart'; class UserListItem extends StatefulWidget { const UserListItem(this.user, this.onPressed, {super.key}); @@ -12,6 +13,25 @@ class UserListItem extends StatefulWidget { } class _UserListItemState extends State { + @override + void initState() { + super.initState(); + PresenceNotifier.instance.addListener(_onPresenceChanged); + } + + @override + void dispose() { + PresenceNotifier.instance.removeListener(_onPresenceChanged); + super.dispose(); + } + + /// Presence is ephemeral, so the row redraws on every change. + void _onPresenceChanged() { + if (mounted) { + setState(() {}); + } + } + @override Widget build(BuildContext context) { return ListTile( @@ -21,18 +41,41 @@ class _UserListItemState extends State { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), - leading: CircleAvatar( - radius: 22, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 20, - color: widget.user.avatarTextColor, + leading: Stack( + clipBehavior: Clip.none, + children: [ + CircleAvatar( + radius: 22, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 20, + color: widget.user.avatarTextColor, + ), + ), ), - ), + // Same badge as the chat list: an absent dot means "not sharing". + if (PresenceNotifier.instance.isOnline(widget.user.id) == true) + Positioned( + right: 0, + bottom: 0, + child: Container( + width: 12, + height: 12, + decoration: BoxDecoration( + color: const Color(0xFF2E7D32), + shape: BoxShape.circle, + border: Border.all( + color: Theme.of(context).scaffoldBackgroundColor, + width: 2, + ), + ), + ), + ), + ], ), title: Text(widget.user.username), ); diff --git a/lib/widgets/view_once_frame.dart b/lib/widgets/view_once_frame.dart new file mode 100644 index 0000000..c83675e --- /dev/null +++ b/lib/widgets/view_once_frame.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; + +/// The box a view-once message shows before (and instead of) its content: one +/// icon, one line of state. Tapping it spends the single view; without an +/// [onTap] it is the read-only tombstone. +class ViewOnceFrame extends StatelessWidget { + const ViewOnceFrame({ + required this.label, + required this.bubbleColor, + required this.textColor, + this.onTap, + this.dimmed = false, + super.key, + }); + + final String label; + final Color bubbleColor; + final Color textColor; + final VoidCallback? onTap; + + /// Already opened: the box is drawn fainter, the hue still marks the owner. + final bool dimmed; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + // An opened frame is a little duller, never translucent: the peer's colour + // is already close to the chat background and alpha made it look invisible. + final fill = dimmed + ? Color.alphaBlend(scheme.surface.withValues(alpha: 0.35), bubbleColor) + : bubbleColor; + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10), + child: Container( + width: 200, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: fill, + borderRadius: BorderRadius.circular(10), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.visibility_off, color: textColor), + const SizedBox(height: 8), + Text( + label, + textAlign: TextAlign.center, + style: TextStyle(color: textColor), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/voice_player.dart b/lib/widgets/voice_player.dart new file mode 100644 index 0000000..fcba116 --- /dev/null +++ b/lib/widgets/voice_player.dart @@ -0,0 +1,401 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:just_audio/just_audio.dart'; + +import '../utils/cache_utils.dart'; +import '../utils/media_utils.dart'; +import '../utils/playback_lock.dart'; +import '../utils/playback_speed.dart'; +import '../utils/media_autoplay.dart'; + +/// Inline player for a voice message stored encrypted-at-rest. +/// +/// The encrypted file is decrypted into a temporary plaintext file for +/// playback and deleted again on dispose. +class VoicePlayer extends StatefulWidget { + final String localPath; + final int? durationMs; + final Color color; + + /// The chat this message lives in, and when it was sent: together they are + /// the key the next-message chain looks for. + final String conversationId; + final DateTime sentAt; + + /// Loudness samples recorded with the message, empty for older ones. + final List? waveform; + + const VoicePlayer({ + required this.localPath, + required this.color, + required this.conversationId, + required this.sentAt, + this.durationMs, + this.waveform, + super.key, + }); + + @override + State createState() => _VoicePlayerState(); +} + +class _VoicePlayerState extends State with WidgetsBindingObserver { + final AudioPlayer _player = AudioPlayer(); + File? _tempFile; + bool _loading = true; + bool _error = false; + double _speed = playbackSpeeds.first; + + /// Set once the finished message has asked for the next one, so a repeated + /// `completed` event does not restart the chain. + bool _chained = false; + + late final String _key = + CacheUtils.messageKey(widget.conversationId, widget.sentAt); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _player.playerStateStream.listen((state) { + if (state.processingState == ProcessingState.completed) { + PlaybackLock.release(this); + if (!_chained) { + _chained = true; + MediaAutoplay.next(widget.conversationId, widget.sentAt); + } + return; + } + if (!state.playing) { + PlaybackLock.release(this); + } + }); + PlaybackLock.owner.addListener(_onLockChanged); + MediaAutoplay.request.addListener(_onAutoplayRequest); + _prepare(); + } + + /// Starts this message when the previous one finished and asked for it. + void _onAutoplayRequest() { + if (MediaAutoplay.request.value != _key) { + return; + } + MediaAutoplay.request.value = null; + if (_loading || _error) { + return; + } + PlaybackLock.claim(this); + _player.play(); + } + + /// Pauses when another voice message or a video starts playing. + void _onLockChanged() { + if (!identical(PlaybackLock.owner.value, this) && _player.playing) { + _player.pause(); + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) { + _player.pause(); + } + } + + Future _prepare() async { + try { + _tempFile = + await MediaUtils.materializeTempFile(widget.localPath, '.m4a'); + await _player.setFilePath(_tempFile!.path); + _speed = await CacheUtils.getPlaybackSpeed(); + await _player.setSpeed(_speed); + if (mounted) { + setState(() { + _loading = false; + }); + } + } catch (_) { + if (mounted) { + setState(() { + _loading = false; + _error = true; + }); + } + } + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + PlaybackLock.owner.removeListener(_onLockChanged); + MediaAutoplay.request.removeListener(_onAutoplayRequest); + PlaybackLock.release(this); + _player.dispose(); + MediaUtils.deleteLocalFile(_tempFile?.path); + super.dispose(); + } + + /// Steps to the next speed and stores it for every other message. + Future _cycleSpeed() async { + final speed = nextSpeed(_speed); + setState(() { + _speed = speed; + }); + await _player.setSpeed(speed); + await CacheUtils.setPlaybackSpeed(speed); + } + + String _format(Duration d) { + final minutes = d.inMinutes.remainder(60).toString().padLeft(2, '0'); + final seconds = d.inSeconds.remainder(60).toString().padLeft(2, '0'); + return '$minutes:$seconds'; + } + + /// Waveform of the message, or a plain track for a message recorded before + /// the shape was stored. Tap or drag seeks, like the slider it replaces. + Widget _waveformBar(BuildContext context, Duration total, Duration position) { + final progress = total.inMilliseconds == 0 + ? 0.0 + : (position.inMilliseconds / total.inMilliseconds).clamp(0.0, 1.0); + return LayoutBuilder( + builder: (context, constraints) { + void seek(Offset local) { + if (_loading || total.inMilliseconds == 0) { + return; + } + final fraction = (local.dx / constraints.maxWidth).clamp(0.0, 1.0); + _player.seek(Duration( + milliseconds: (total.inMilliseconds * fraction).round())); + } + + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTapDown: (details) => seek(details.localPosition), + onHorizontalDragUpdate: (details) => seek(details.localPosition), + child: SizedBox( + height: 26, + child: CustomPaint( + painter: _WaveformPainter( + samples: widget.waveform ?? const [], + progress: progress, + color: widget.color, + ), + ), + ), + ); + }, + ); + } + + @override + Widget build(BuildContext context) { + if (_error) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.error_outline, color: widget.color), + const SizedBox(width: 8), + Text('mediaError'.tr(), style: TextStyle(color: widget.color)), + ], + ); + } + + final total = _player.duration ?? + (widget.durationMs != null + ? Duration(milliseconds: widget.durationMs!) + : Duration.zero); + + return SizedBox( + width: 220, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _loading + ? SizedBox( + width: 36, + height: 36, + child: Padding( + padding: const EdgeInsets.all(6), + child: CircularProgressIndicator( + strokeWidth: 2, + color: widget.color, + ), + ), + ) + : StreamBuilder( + stream: _player.playerStateStream, + builder: (context, snapshot) { + final playing = snapshot.data?.playing ?? false; + final completed = snapshot.data?.processingState == + ProcessingState.completed; + return IconButton( + color: widget.color, + icon: Icon((playing && !completed) + ? Icons.pause + : Icons.play_arrow), + onPressed: () async { + if (playing && !completed) { + await _player.pause(); + } else { + PlaybackLock.claim(this); + if (completed) { + _chained = false; + await _player.seek(Duration.zero); + } + _chained = false; + await _player.play(); + } + }, + ); + }, + ), + Expanded( + child: StreamBuilder( + stream: _player.positionStream, + builder: (context, snapshot) { + final position = snapshot.data ?? Duration.zero; + // The waveform and the time label sit on one line, so the bars + // are vertically centred in the row instead of being pushed up + // by a stacked label. + return StreamBuilder( + stream: _player.playerStateStream, + builder: (context, stateSnapshot) { + final completed = stateSnapshot.data?.processingState == + ProcessingState.completed; + // The speed control appears with playback and is gone + // again once the message finished. It sits under the time, + // so the track gets an equal spacer above it to stay + // centred on the play button instead of drifting up. + final started = position > Duration.zero && !completed; + const double speedLine = 16; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (started) const SizedBox(height: speedLine), + Row( + children: [ + Expanded( + child: _waveformBar(context, total, position), + ), + const SizedBox(width: 4), + Text( + _format(position.inMilliseconds > 0 + ? position + : total), + style: + TextStyle(fontSize: 11, color: widget.color), + ), + ], + ), + if (started) + SizedBox( + height: speedLine, + child: Align( + alignment: Alignment.centerRight, + child: Semantics( + button: true, + child: InkWell( + onTap: _cycleSpeed, + child: Padding( + padding: const EdgeInsets.only(right: 4), + child: Text( + speedLabel(_speed), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: widget.color, + ), + ), + ), + ), + ), + ), + ), + ], + ); + }, + ); + }, + ), + ), + ], + ), + ); + } +} + +/// Draws the loudness bars of a voice message, the played part in full colour. +class _WaveformPainter extends CustomPainter { + _WaveformPainter({ + required this.samples, + required this.progress, + required this.color, + }); + + final List samples; + final double progress; + final Color color; + + /// Bars drawn at most. A long recording has one sample per 100 ms, which + /// would be sub-pixel wide: the samples are folded into this many peaks. + static const int maxBars = 32; + + /// Folds [samples] into at most [maxBars] peaks, so a bar is always visible. + List _bars() { + if (samples.length <= maxBars) { + return samples; + } + final bucket = samples.length / maxBars; + return List.generate(maxBars, (index) { + final start = (index * bucket).floor(); + final end = + ((index + 1) * bucket).ceil().clamp(start + 1, samples.length); + var peak = 0; + for (var i = start; i < end; i++) { + if (samples[i] > peak) { + peak = samples[i]; + } + } + return peak; + }); + } + + @override + void paint(Canvas canvas, Size size) { + final bars = _bars(); + if (bars.isEmpty) { + final paint = Paint() + ..color = color.withValues(alpha: 0.3) + ..strokeWidth = 2 + ..strokeCap = StrokeCap.round; + canvas.drawLine(Offset(0, size.height / 2), + Offset(size.width, size.height / 2), paint); + return; + } + final step = size.width / bars.length; + final barWidth = (step * 0.6).clamp(1.0, 4.0); + final played = Paint()..color = color; + final rest = Paint()..color = color.withValues(alpha: 0.3); + for (var i = 0; i < bars.length; i++) { + final height = (bars[i] / 100 * size.height).clamp(2.0, size.height); + final rect = RRect.fromRectAndRadius( + Rect.fromCenter( + center: Offset(i * step + step / 2, size.height / 2), + width: barWidth, + height: height, + ), + const Radius.circular(1), + ); + canvas.drawRRect(rect, i / bars.length <= progress ? played : rest); + } + } + + @override + bool shouldRepaint(covariant _WaveformPainter oldDelegate) => + oldDelegate.progress != progress || + oldDelegate.color != color || + oldDelegate.samples != samples; +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..2584b5c --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "shept") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "cz.josefraz.shept") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8ac2ca5 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,27 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); + file_selector_plugin_register_with_registrar(file_selector_linux_registrar); + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); + g_autoptr(FlPluginRegistrar) record_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "RecordLinuxPlugin"); + record_linux_plugin_register_with_registrar(record_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..6b9c45f --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,28 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + file_selector_linux + flutter_secure_storage_linux + record_linux + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..7a69f32 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "shept"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "shept"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/pubspec.lock b/pubspec.lock index 20f99ac..4ce704f 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -9,22 +9,6 @@ packages: url: "https://pub.dev" source: hosted version: "67.0.0" - _flutterfire_internals: - dependency: transitive - description: - name: _flutterfire_internals - sha256: "23d16f00a2da8ffa997c782453c73867b0609bd90435195671a54de38a3566df" - url: "https://pub.dev" - source: hosted - version: "1.3.62" - adaptive_number: - dependency: transitive - description: - name: adaptive_number - sha256: "3a567544e9b5c9c803006f51140ad544aedc79604fd4f3f2c1380003f97c1d77" - url: "https://pub.dev" - source: hosted - version: "1.0.0" analyzer: dependency: transitive description: @@ -33,14 +17,22 @@ packages: url: "https://pub.dev" source: hosted version: "6.4.1" + android_file_picker: + dependency: transitive + description: + name: android_file_picker + sha256: e7e02f9bab7e014e5b47e4cef135a8f5c66f5c14fd90986e415e758f6a1762e1 + url: "https://pub.dev" + source: hosted + version: "2.1.6" archive: dependency: transitive description: name: archive - sha256: "2fde1607386ab523f7a36bb3e7edb43bd58e6edaf2ffb29d8a6d578b297fdbbd" + sha256: de5ac590b8155e4e676088d714bd41ea620449a6adc0f7950c5073874b287ddb url: "https://pub.dev" source: hosted - version: "4.0.7" + version: "4.6.0" args: dependency: transitive description: @@ -53,10 +45,18 @@ packages: dependency: transitive description: name: async - sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + audio_session: + dependency: transitive + description: + name: audio_session + sha256: f9e7711a0e24ca8b40f5d7ac374c3c6e55016f3157912badd18199cdbbca5c4d url: "https://pub.dev" source: hosted - version: "2.13.0" + version: "0.2.4" basic_utils: dependency: "direct main" description: @@ -69,10 +69,10 @@ packages: dependency: "direct main" description: name: bcrypt - sha256: "9dc3f234d5935a76917a6056613e1a6d9b53f7fa56f98e24cd49b8969307764b" + sha256: "6073a700cbbc59f1d4ab27cd532755e3de5e676c4941f535f351374df849270b" url: "https://pub.dev" source: hosted - version: "1.1.3" + version: "1.2.0" boolean_selector: dependency: transitive description: @@ -101,10 +101,10 @@ packages: dependency: transitive description: name: build_daemon - sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa" + sha256: "39ab65f7c60c19af64b9ef96e6a5d3ab48355f7dddfd98a9079d55a8cb6628fc" url: "https://pub.dev" source: hosted - version: "4.0.4" + version: "4.1.7" build_resolvers: dependency: transitive description: @@ -133,26 +133,66 @@ packages: dependency: transitive description: name: built_collection - sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + sha256: "44922ecebd8e3d0cef743dadd3b54df4e87e2a4c52a29465a1872aa9e192caa8" url: "https://pub.dev" source: hosted - version: "5.1.1" + version: "5.1.2" built_value: dependency: transitive description: name: built_value - sha256: a30f0a0e38671e89a492c44d005b5545b830a961575bbd8336d42869ff71066d + sha256: f87ea98192116f7093cb214551ce1929caae0681fdba282b3d8b4462adee7bb7 + url: "https://pub.dev" + source: hosted + version: "8.13.0" + camera: + dependency: "direct main" + description: + name: camera + sha256: "4a0863bc142f6fbfdca19161205574fd8a8f00d4753b48d214c4dfbdcc534c51" + url: "https://pub.dev" + source: hosted + version: "0.12.2" + camera_android_camerax: + dependency: transitive + description: + name: camera_android_camerax + sha256: daefacb4c2c575426772a83ac312b93e2c49c003224962cddab904426dc04dbc + url: "https://pub.dev" + source: hosted + version: "0.7.6+2" + camera_avfoundation: + dependency: transitive + description: + name: camera_avfoundation + sha256: "971f7b4938ae761797dd667c078af92f1b6a1bb7760774c0cbcf9c9d4a14bdf1" url: "https://pub.dev" source: hosted - version: "8.12.0" + version: "0.11.1" + camera_platform_interface: + dependency: transitive + description: + name: camera_platform_interface + sha256: c22b8403d7925c6cc6a37fc0cf01f645c1400bdfb0e765f81373a3ac080d93e3 + url: "https://pub.dev" + source: hosted + version: "2.15.1" + camera_web: + dependency: transitive + description: + name: camera_web + sha256: "54183db5a296cf29478dd150d7685b761f9e8eeb4a11114bcbc2792adea7cb3b" + url: "https://pub.dev" + source: hosted + version: "0.3.6" characters: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" checked_yaml: dependency: transitive description: @@ -161,6 +201,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.4" + chewie: + dependency: "direct main" + description: + name: chewie + sha256: "7606034230e56f0258ef5a75260fdc1d69c66b4c3724f7cc9613bca954858dc3" + url: "https://pub.dev" + source: hosted + version: "1.17.4" cli_util: dependency: transitive description: @@ -173,18 +221,26 @@ packages: dependency: transitive description: name: clock - sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "1.1.3" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "1ef22a0be3af9370bd9481ac76db114db92bfe75d5ca2b2d7bc911764478a4d9" + url: "https://pub.dev" + source: hosted + version: "2.2.0" code_builder: dependency: transitive description: name: code_builder - sha256: "11654819532ba94c34de52ff5feb52bd81cba1de00ef2ed622fd50295f9d4243" + sha256: "811709c1badd02fc054039a13f66e0db1961865f9a314175f68c3eaeebec786f" url: "https://pub.dev" source: hosted - version: "4.11.0" + version: "4.13.0" collection: dependency: transitive description: @@ -193,6 +249,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + connectivity_plus: + dependency: "direct main" + description: + name: connectivity_plus + sha256: d7749fd36d8b404a4935612b94eca7c3ce3705377ab678e24ff2a4301436f741 + url: "https://pub.dev" + source: hosted + version: "7.3.2" + connectivity_plus_platform_interface: + dependency: transitive + description: + name: connectivity_plus_platform_interface + sha256: "3c09627c536d22fd24691a905cdd8b14520de69da52c7a97499c8be5284a32ed" + url: "https://pub.dev" + source: hosted + version: "2.1.0" convert: dependency: transitive description: @@ -201,30 +273,70 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.2" + crop_your_image: + dependency: "direct main" + description: + name: crop_your_image + sha256: "8cd2936d5e2f1a23b330390df0c7e59d685892d63f374196e498905e0896cc2c" + url: "https://pub.dev" + source: hosted + version: "2.0.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6 + url: "https://pub.dev" + source: hosted + version: "0.3.5+5" crypto: dependency: "direct main" description: name: crypto - sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 url: "https://pub.dev" source: hosted - version: "3.0.6" + version: "3.0.8" cryptography: dependency: "direct main" description: name: cryptography - sha256: d146b76d33d94548cf035233fbc2f4338c1242fa119013bead807d033fc4ae05 + sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0" url: "https://pub.dev" source: hosted - version: "2.7.0" + version: "2.9.0" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + cupertino_icons: + dependency: transitive + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" dart_jsonwebtoken: dependency: "direct main" description: name: dart_jsonwebtoken - sha256: "21ce9f8a8712f741e8d6876a9c82c0f8a257fe928c4378a91d8527b92a3fd413" + sha256: ad84e60181696513d04d5f2078e0bbc20365b911f46f647797317414bdc88fbe url: "https://pub.dev" source: hosted - version: "3.2.0" + version: "3.4.1" + dart_mcp: + dependency: transitive + description: + name: dart_mcp + sha256: "852b51da915d679be8d051e2e3b6c68ed19fe685f1c676bb35272a2d73ceac7a" + url: "https://pub.dev" + source: hosted + version: "0.5.2" dart_style: dependency: transitive description: @@ -237,26 +349,34 @@ packages: dependency: transitive description: name: dbus - sha256: "79e0c23480ff85dc68de79e2cd6334add97e48f7f4865d17686dd6ea81a47e8c" + sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612 + url: "https://pub.dev" + source: hosted + version: "0.8.0" + decimal: + dependency: transitive + description: + name: decimal + sha256: "2c3c8b74f2948066d3f42585477aec9cfc48fefd7a723a4d4274a6c71a5c0df7" url: "https://pub.dev" source: hosted - version: "0.7.11" + version: "3.2.6" device_info_plus: dependency: transitive description: name: device_info_plus - sha256: "49413c8ca514dea7633e8def233b25efdf83ec8522955cc2c0e3ad802927e7c6" + sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa url: "https://pub.dev" source: hosted - version: "12.1.0" + version: "13.3.0" device_info_plus_platform_interface: dependency: transitive description: name: device_info_plus_platform_interface - sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f + sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" url: "https://pub.dev" source: hosted - version: "7.0.3" + version: "8.1.0" easy_localization: dependency: "direct main" description: @@ -273,14 +393,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.0.2" - ed25519_edwards: - dependency: transitive - description: - name: ed25519_edwards - sha256: "6ce0112d131327ec6d42beede1e5dfd526069b18ad45dcf654f15074ad9276cd" - url: "https://pub.dev" - source: hosted - version: "0.3.1" email_validator: dependency: "direct main" description: @@ -289,6 +401,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0" + equatable: + dependency: transitive + description: + name: equatable + sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2" + url: "https://pub.dev" + source: hosted + version: "2.1.0" fake_async: dependency: transitive description: @@ -301,10 +421,18 @@ packages: dependency: transitive description: name: ffi - sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" file: dependency: transitive description: @@ -313,54 +441,78 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" - firebase_core: + file_picker: dependency: "direct main" description: - name: firebase_core - sha256: "4dd96f05015c0dcceaa47711394c32971aee70169625d5e2477e7676c01ce0ee" + name: file_picker + sha256: "079dc46b753abbddb7f77cd87e6ed9ecc62902580707514568321bdf8e050a86" url: "https://pub.dev" source: hosted - version: "4.1.1" - firebase_core_platform_interface: + version: "13.3.3" + file_picker_darwin: dependency: transitive description: - name: firebase_core_platform_interface - sha256: "5873a370f0d232918e23a5a6137dbe4c2c47cf017301f4ea02d9d636e52f60f0" + name: file_picker_darwin + sha256: b7d3a6bd26a18c503d29070fc2d7b26fbfe918d08a6bcd984b6e806ff5ad923f url: "https://pub.dev" source: hosted - version: "6.0.1" - firebase_core_web: + version: "2.5.1" + file_picker_linux: dependency: transitive description: - name: firebase_core_web - sha256: "61a51037312dac781f713308903bb7a1762a7f92f7bc286a3a0947fb2a713b82" + name: file_picker_linux + sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b" url: "https://pub.dev" source: hosted - version: "3.1.1" - firebase_messaging: - dependency: "direct main" + version: "2.0.4" + file_picker_platform_interface: + dependency: transitive + description: + name: file_picker_platform_interface + sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20" + url: "https://pub.dev" + source: hosted + version: "4.2.0" + file_picker_web: + dependency: transitive + description: + name: file_picker_web + sha256: "50749a6da2984fc29609e102ad4d80fd1d07e6895150f8e4922086167d9d45d8" + url: "https://pub.dev" + source: hosted + version: "4.2.1" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab + url: "https://pub.dev" + source: hosted + version: "0.9.4+1" + file_selector_macos: + dependency: transitive description: - name: firebase_messaging - sha256: ba12ad0b600e0c939fbb9391e1cd3320a5b5dad5284276b9182fc21eb1e72c2b + name: file_selector_macos + sha256: d785431f1910aac8a50e5c492cae912320158030a88703c67b9ef7f1f96fd7ba url: "https://pub.dev" source: hosted - version: "16.0.2" - firebase_messaging_platform_interface: + version: "0.9.5+2" + file_selector_platform_interface: dependency: transitive description: - name: firebase_messaging_platform_interface - sha256: b4bade67bfc09fcc56eb012b3fc72b59ca9e2259a34cdfb81b368169770ff536 + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" url: "https://pub.dev" source: hosted - version: "4.7.2" - firebase_messaging_web: + version: "2.7.0" + file_selector_windows: dependency: transitive description: - name: firebase_messaging_web - sha256: "8ae4a00d178993feb79603cad324b53696375cbb78805e8eb603fe331866629d" + name: file_selector_windows + sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec url: "https://pub.dev" source: hosted - version: "4.0.2" + version: "0.9.3+6" fixnum: dependency: transitive description: @@ -382,6 +534,11 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + flutter_driver: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_launcher_icons: dependency: "direct main" description: @@ -402,95 +559,111 @@ packages: dependency: "direct main" description: name: flutter_local_notifications - sha256: "7ed76be64e8a7d01dfdf250b8434618e2a028c9dfa2a3c41dc9b531d4b3fc8a5" + sha256: "58f9ea245d7194363c05f7a012bbc73291736c2d8b5f555a8e0ea3f9121868b4" url: "https://pub.dev" source: hosted - version: "19.4.2" + version: "23.0.1" flutter_local_notifications_linux: dependency: transitive description: name: flutter_local_notifications_linux - sha256: e3c277b2daab8e36ac5a6820536668d07e83851aeeb79c446e525a70710770a5 + sha256: bcbcf3c15e33b6866805092308f5f6ef27e1191874f6a92ef59213a0812a79a2 url: "https://pub.dev" source: hosted - version: "6.0.0" + version: "9.0.0" flutter_local_notifications_platform_interface: dependency: transitive description: name: flutter_local_notifications_platform_interface - sha256: "277d25d960c15674ce78ca97f57d0bae2ee401c844b6ac80fcd972a9c99d09fe" + sha256: "4a49db4ce3d633ebc85c85b5fa959572600ec10bd097419c454579444308a0a0" url: "https://pub.dev" source: hosted - version: "9.1.0" + version: "13.0.0" + flutter_local_notifications_web: + dependency: transitive + description: + name: flutter_local_notifications_web + sha256: ef117694fbfcd82308ab0e324cfc9282fa50c192e24ec54a58173ae327ebc544 + url: "https://pub.dev" + source: hosted + version: "2.0.0" flutter_local_notifications_windows: dependency: transitive description: name: flutter_local_notifications_windows - sha256: "8d658f0d367c48bd420e7cf2d26655e2d1130147bca1eea917e576ca76668aaf" + sha256: "8e80ac29433c71e267493b397457e3a8430c5c1d9c76bb58a6971c016cdba3d7" url: "https://pub.dev" source: hosted - version: "1.0.3" + version: "4.0.1" flutter_localizations: dependency: transitive description: flutter source: sdk version: "0.0.0" + flutter_mcp_toolkit_core: + dependency: transitive + description: + name: flutter_mcp_toolkit_core + sha256: "60b7b4fe760f038d45f076b0898e0f2719c8af68038943989e4a4cae89531737" + url: "https://pub.dev" + source: hosted + version: "7.1.0" flutter_plugin_android_lifecycle: dependency: transitive description: name: flutter_plugin_android_lifecycle - sha256: b0694b7fb1689b0e6cc193b3f1fcac6423c4f93c74fb20b806c6b6f196db0c31 + sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785" url: "https://pub.dev" source: hosted - version: "2.0.30" + version: "2.0.35" flutter_secure_storage: dependency: "direct main" description: name: flutter_secure_storage - sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea" + sha256: d4e1fb6b2cb524868929e78dc0282fa000554b22060fb53789dc481c9fc95bb8 url: "https://pub.dev" source: hosted - version: "9.2.4" - flutter_secure_storage_linux: + version: "11.2.0" + flutter_secure_storage_darwin: dependency: transitive description: - name: flutter_secure_storage_linux - sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688 + name: flutter_secure_storage_darwin + sha256: a031ceac9b070e62ef183cd7f7d1a8798ebde402d5049f0fe6eb3a51bd797a21 url: "https://pub.dev" source: hosted - version: "1.2.3" - flutter_secure_storage_macos: + version: "0.4.3" + flutter_secure_storage_linux: dependency: transitive description: - name: flutter_secure_storage_macos - sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247" + name: flutter_secure_storage_linux + sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea url: "https://pub.dev" source: hosted - version: "3.1.3" + version: "3.0.3" flutter_secure_storage_platform_interface: dependency: transitive description: name: flutter_secure_storage_platform_interface - sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8 + sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045" url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "2.1.1" flutter_secure_storage_web: dependency: transitive description: name: flutter_secure_storage_web - sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9 + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "2.1.1" flutter_secure_storage_windows: dependency: transitive description: name: flutter_secure_storage_windows - sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709 + sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" url: "https://pub.dev" source: hosted - version: "3.1.2" + version: "4.2.2" flutter_test: dependency: "direct dev" description: flutter @@ -505,26 +678,87 @@ packages: dependency: "direct main" description: name: fluttertoast - sha256: "144ddd74d49c865eba47abe31cbc746c7b311c82d6c32e571fd73c4264b740e2" + sha256: a5c39007e19fff5eeb7810d5be651c02bb5a1c06104bdd203b037bbfe49bd827 url: "https://pub.dev" source: hosted - version: "9.0.0" + version: "10.0.2" + from_json_to_json: + dependency: transitive + description: + name: from_json_to_json + sha256: a29219df65cd20b1b17be8141ee51b3103d1cd95b192b7512139f3ae44775f49 + url: "https://pub.dev" + source: hosted + version: "0.5.0" frontend_server_client: dependency: transitive description: name: frontend_server_client - sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + sha256: "2b56423afc7651a81da53ed3a4f9f51e92572293f54d0d54e19b759f13714849" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "4.2.0" + fuchsia_remote_debug_protocol: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + geolocator: + dependency: "direct main" + description: + name: geolocator + sha256: ee2212a3df8292ec4c90b91183b8001d3f5a800823c974b570c5f9344ca320dc + url: "https://pub.dev" + source: hosted + version: "14.0.1" + geolocator_android: + dependency: transitive + description: + name: geolocator_android + sha256: e67583809a1fab5f4a2255902978e2bc095ace9451fde0d9624e54facd0a5c22 + url: "https://pub.dev" + source: hosted + version: "5.2.1" + geolocator_apple: + dependency: transitive + description: + name: geolocator_apple + sha256: a1e177f3081089724f2095856aeb96eb8d7d1c59e425aed8dd4de7aa2c11ab66 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + geolocator_platform_interface: + dependency: transitive + description: + name: geolocator_platform_interface + sha256: e012af6b7e2674e7500237ab11e44ac9119e87fd0105e7bb55cde1750e8e5d80 + url: "https://pub.dev" + source: hosted + version: "4.4.1" + geolocator_web: + dependency: transitive + description: + name: geolocator_web + sha256: "19e485a0f8d6a88abcf9c53cba3a4105e14b7435ed8ac1c108c067b938fe8429" + url: "https://pub.dev" + source: hosted + version: "4.1.4" + geolocator_windows: + dependency: transitive + description: + name: geolocator_windows + sha256: "175435404d20278ffd220de83c2ca293b73db95eafbdc8131fe8609be1421eb6" + url: "https://pub.dev" + source: hosted + version: "0.2.5" glob: dependency: transitive description: name: glob - sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" url: "https://pub.dev" source: hosted - version: "2.1.3" + version: "2.2.0" graphs: dependency: transitive description: @@ -549,22 +783,38 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.1" + hooks: + dependency: transitive + description: + name: hooks + sha256: eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f + url: "https://pub.dev" + source: hosted + version: "2.2.0" + html: + dependency: transitive + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" http: dependency: "direct main" description: name: http - sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007 + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" url: "https://pub.dev" source: hosted - version: "1.5.0" + version: "1.6.0" http_multi_server: dependency: transitive description: name: http_multi_server - sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + sha256: "361668bdd71f0ae2dc6d17b75a593520f3c414af6534f9eed1aa72049dd71d18" url: "https://pub.dev" source: hosted - version: "3.2.2" + version: "3.2.3" http_parser: dependency: transitive description: @@ -577,34 +827,151 @@ packages: dependency: transitive description: name: image - sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928" + sha256: "89ed75b2f8231fe676808c5564f9590d728024ded7ac782a7ed8474f1c95b72a" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: e71b1bd9e40124041128d60fc3034c7b1598e1bba4e570bba0c70301c817013a + url: "https://pub.dev" + source: hosted + version: "1.2.4" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: "8a7823d5d3e884f7780829d85d92110d072bdcd9ed48e2be158d2abe91a912d4" + url: "https://pub.dev" + source: hosted + version: "0.8.13+25" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: f4e5650a81b268af3886bc789216ff6d56bdfa79934f93f1a5a8a303b8f60f77 + url: "https://pub.dev" + source: hosted + version: "0.8.13+15" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "2dee4b4e3be429db71472c9c559c981498070a61af1ba82e0e4986fc5dadc042" + url: "https://pub.dev" + source: hosted + version: "2.11.2" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + integration_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + intentcall_core: + dependency: transitive + description: + name: intentcall_core + sha256: "5943bf2101129d2c1c7e011d5987bc873e83506c4de0245b400159011054d51a" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + intentcall_schema: + dependency: transitive + description: + name: intentcall_schema + sha256: be0df75cb88f5d40b3d0928843e8c722564014e5e6806c33eec5b8d4f1a3b56f url: "https://pub.dev" source: hosted - version: "4.5.4" + version: "1.2.0" intl: dependency: transitive description: name: intl - sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" url: "https://pub.dev" source: hosted - version: "0.20.2" + version: "0.20.3" io: dependency: transitive description: name: io - sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + is_dart_empty_or_not: + dependency: transitive + description: + name: is_dart_empty_or_not + sha256: "1454632c2b961175d4c2807310713cbcbd054a51e63c545dc86c3eb9b2b061b0" + url: "https://pub.dev" + source: hosted + version: "0.4.0" + jni: + dependency: transitive + description: + name: jni + sha256: "2e91e6087291affd10b31b6c872f3e3ac7dc5d93b51b5ba485d930c8f08bde6c" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" + url: "https://pub.dev" + source: hosted + version: "1.0.4+1" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" url: "https://pub.dev" source: hosted - version: "1.0.5" + version: "1.0.0" js: dependency: transitive description: name: js - sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" url: "https://pub.dev" source: hosted - version: "0.6.7" + version: "0.7.2" json_annotation: dependency: "direct main" description: @@ -613,6 +980,22 @@ packages: url: "https://pub.dev" source: hosted version: "4.9.0" + json_rpc_2: + dependency: transitive + description: + name: json_rpc_2 + sha256: "82dfd37d3b2e5030ae4729e1d7f5538cbc45eb1c73d618b9272931facac3bec1" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + json_schema_builder: + dependency: transitive + description: + name: json_schema_builder + sha256: "657db3229ba10305c48e8686e8b3aca16e12e639c3a7b96687a6eeb7836b6e1b" + url: "https://pub.dev" + source: hosted + version: "0.1.7" json_serializable: dependency: "direct dev" description: @@ -621,14 +1004,30 @@ packages: url: "https://pub.dev" source: hosted version: "6.8.0" - jwt_decoder: + just_audio: dependency: "direct main" description: - name: jwt_decoder - sha256: "54774aebf83f2923b99e6416b4ea915d47af3bde56884eb622de85feabbc559f" + name: just_audio + sha256: e60aa97b233ddea025e13dfac59195207f528fa5e9e4a4a49a8c0766701e5fe6 url: "https://pub.dev" source: hosted - version: "2.0.1" + version: "0.10.6" + just_audio_platform_interface: + dependency: transitive + description: + name: just_audio_platform_interface + sha256: "2532c8d6702528824445921c5ff10548b518b13f808c2e34c2fd54793b999a6a" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + just_audio_web: + dependency: transitive + description: + name: just_audio_web + sha256: "6ba8a2a7e87d57d32f0f7b42856ade3d6a9fbe0f1a11fabae0a4f00bb73f0663" + url: "https://pub.dev" + source: hosted + version: "0.4.16" leak_tracker: dependency: transitive description: @@ -657,50 +1056,50 @@ packages: dependency: transitive description: name: lints - sha256: a5e2b223cb7c9c8efdc663ef484fdd95bb243bff242ef5b13e26883547fce9a0 + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" url: "https://pub.dev" source: hosted - version: "6.0.0" + version: "6.1.0" local_auth: dependency: "direct main" description: name: local_auth - sha256: "434d854cf478f17f12ab29a76a02b3067f86a63a6d6c4eb8fbfdcfe4879c1b7b" + sha256: ecf24edf2283c509ecd217e3595f6f71034b68888d28ad1dae6bfa0857b816ac url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "3.0.2" local_auth_android: dependency: transitive description: name: local_auth_android - sha256: "1ee0e63fb8b5c6fa286796b5fb1570d256857c2f4a262127e728b36b80a570cf" + sha256: e2ceb84cdecefe1bc0ddd4ac308b0f6525bbfa0a60d0e552082b2970e1fb38c2 url: "https://pub.dev" source: hosted - version: "1.0.53" + version: "2.3.0" local_auth_darwin: dependency: transitive description: name: local_auth_darwin - sha256: "699873970067a40ef2f2c09b4c72eb1cfef64224ef041b3df9fdc5c4c1f91f49" + sha256: "45a9db01b57082bc9d6115cb25eb8fc0b72f43e5f330819bdd8352ecdae87589" url: "https://pub.dev" source: hosted - version: "1.6.1" + version: "2.0.5" local_auth_platform_interface: dependency: transitive description: name: local_auth_platform_interface - sha256: "1b842ff177a7068442eae093b64abe3592f816afd2a533c0ebcdbe40f9d2075a" + sha256: f98b8e388588583d3f781f6806e4f4c9f9e189d898d27f0c249b93a1973dd122 url: "https://pub.dev" source: hosted - version: "1.0.10" + version: "1.1.0" local_auth_windows: dependency: transitive description: name: local_auth_windows - sha256: bc4e66a29b0fdf751aafbec923b5bed7ad6ed3614875d8151afe2578520b2ab5 + sha256: d72b8a441e5e6a679902f87c51529fcce65f442d77598484cf35454c3d733eda url: "https://pub.dev" source: hosted - version: "1.0.11" + version: "2.0.2" logging: dependency: transitive description: @@ -713,42 +1112,42 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.20" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" - meta: - dependency: transitive + version: "0.13.0" + mcp_toolkit: + dependency: "direct main" description: - name: meta - sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + name: mcp_toolkit + sha256: "9e49e48582625980d0ae73001f44509b1d304d5c7cc415b7f6aaa67a9f0114d2" url: "https://pub.dev" source: hosted - version: "1.16.0" - mime: + version: "7.0.1" + meta: dependency: transitive description: - name: mime - sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "2.0.0" - mobile_scanner: + version: "1.19.0" + mime: dependency: "direct main" description: - name: mobile_scanner - sha256: "5e7e09d904dc01de071b79b3f3789b302b0ed3c9c963109cd3f83ad90de62ecf" + name: mime + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 url: "https://pub.dev" source: hosted - version: "7.1.2" + version: "2.1.0" nested: dependency: transitive description: @@ -757,6 +1156,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.0" + nm: + dependency: transitive + description: + name: nm + sha256: "2ae480aa3379716b8bb58dfebb168e2919394c92b629efaaa0baaa5d140786e6" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: c965d264fd4b0b4dd402dce9d049b70656bf98d3ca108b9bc55d2544ceadbe5e + url: "https://pub.dev" + source: hosted + version: "9.6.4" package_config: dependency: transitive description: @@ -765,14 +1180,30 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + package_info_plus: + dependency: transitive + description: + name: package_info_plus + sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908" + url: "https://pub.dev" + source: hosted + version: "10.2.2" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 + url: "https://pub.dev" + source: hosted + version: "4.1.0" page_transition: dependency: "direct main" description: name: page_transition - sha256: "9d2a780d7d68b53ae82fbcc43e06a16195e6775e9aae40e55dc0cbb593460f9d" + sha256: "61dac670e80ebdd7da847c21841e1dfd8f9ab483b3a0c5fddc877ad8d23b69ee" url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.2.2" path: dependency: transitive description: @@ -785,42 +1216,42 @@ packages: dependency: "direct main" description: name: path_provider - sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 url: "https://pub.dev" source: hosted - version: "2.1.5" + version: "2.1.6" path_provider_android: dependency: transitive description: name: path_provider_android - sha256: "993381400e94d18469750e5b9dcb8206f15bc09f9da86b9e44a9b0092a0066db" + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" url: "https://pub.dev" source: hosted - version: "2.2.18" + version: "2.3.1" path_provider_foundation: dependency: transitive description: name: path_provider_foundation - sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd" + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" url: "https://pub.dev" source: hosted - version: "2.4.2" + version: "2.6.0" path_provider_linux: dependency: transitive description: name: path_provider_linux - sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.2.2" path_provider_platform_interface: dependency: transitive description: name: path_provider_platform_interface - sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.1.3" path_provider_windows: dependency: transitive description: @@ -833,18 +1264,18 @@ packages: dependency: transitive description: name: petitparser - sha256: "1a97266a94f7350d30ae522c0af07890c70b8e62c71e8e3920d1db4d23c057d1" + sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790" url: "https://pub.dev" source: hosted - version: "7.0.1" + version: "7.1.0" platform: dependency: transitive description: name: platform - sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec url: "https://pub.dev" source: hosted - version: "3.1.6" + version: "3.2.0" plugin_platform_interface: dependency: transitive description: @@ -865,18 +1296,26 @@ packages: dependency: transitive description: name: pool - sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" url: "https://pub.dev" source: hosted - version: "1.5.2" + version: "1.5.3" posix: dependency: transitive description: name: posix - sha256: "6323a5b0fa688b6a010df4905a56b00181479e6d10534cecfecede2aa55add61" + sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63" url: "https://pub.dev" source: hosted - version: "6.0.3" + version: "6.5.4" + process: + dependency: transitive + description: + name: process + sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891" + url: "https://pub.dev" + source: hosted + version: "5.0.6" provider: dependency: "direct main" description: @@ -889,50 +1328,162 @@ packages: dependency: transitive description: name: pub_semver - sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.2.1" pubspec_parse: dependency: transitive description: name: pubspec_parse - sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" + sha256: "9ac81c01ffd6a9cf9b2713288834fbaaf6aebde05ffdf02d380e68b8e06f27d8" url: "https://pub.dev" source: hosted - version: "1.5.0" + version: "1.7.0" qr_code_scanner_plus: dependency: "direct main" description: name: qr_code_scanner_plus - sha256: a0f1ac8e13299b3db2646635f252fe2ec67222b848b24ed34d11052faf080bfa + sha256: a49eb677d59becaab21a27bf908f860fd033987777cdc04e621e4b75f97531fa + url: "https://pub.dev" + source: hosted + version: "2.3.2" + rational: + dependency: transitive + description: + name: rational + sha256: cb808fb6f1a839e6fc5f7d8cb3b0a10e1db48b3be102de73938c627f0b636336 + url: "https://pub.dev" + source: hosted + version: "2.2.3" + receive_sharing_intent: + dependency: "direct main" + description: + name: receive_sharing_intent + sha256: "72f229a38f2910029c11d840770c173b27072e348ef3376130b37514bc4556f6" + url: "https://pub.dev" + source: hosted + version: "1.9.0" + record: + dependency: "direct main" + description: + name: record + sha256: "3bbb68002de8bb2fc7178b6c955254fa882e2fe4c33fa98db4b98dd662d8a1d6" + url: "https://pub.dev" + source: hosted + version: "7.2.0" + record_android: + dependency: transitive + description: + name: record_android + sha256: "68c8cb40628a460b2a8bdf746697bd798a71cca7b03b8dac20e752d50425900f" + url: "https://pub.dev" + source: hosted + version: "2.3.0" + record_darwin: + dependency: transitive + description: + name: record_darwin + sha256: "6ff6477febaa928ae3a294014f1254c766aaf6bb8f288f02cbe7cda1b9e9be87" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + record_linux: + dependency: transitive + description: + name: record_linux + sha256: a2c1680b908c899e8198ad46e553adbfba4d66fe41c1314705cf3afb888f8033 + url: "https://pub.dev" + source: hosted + version: "2.2.0" + record_platform_interface: + dependency: transitive + description: + name: record_platform_interface + sha256: "970b2a2c4ac4dc666adca8a41fefc3c4b0c62ef1dfc3c46ba5400def7155ac1a" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + record_use: + dependency: transitive + description: + name: record_use + sha256: "1cb8564af8d43b464294411db9217f5ec04891c6f22ee2c32d73ae05e88a6bd2" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + record_web: + dependency: transitive + description: + name: record_web + sha256: "15852c45e3ac621090d919373faa5400ddffaf28403525359041132526a02b1d" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + record_windows: + dependency: transitive + description: + name: record_windows + sha256: c708162ff3195e4b8898242410b66233a5081699f519226c4afe985d1eb877e0 + url: "https://pub.dev" + source: hosted + version: "2.4.0" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + schemantic: + dependency: transitive + description: + name: schemantic + sha256: "1252e78063c2d124831337bf8e9d146cbd6d9cf575f5346a9c85c5911c430239" + url: "https://pub.dev" + source: hosted + version: "0.2.3" + share_plus: + dependency: "direct main" + description: + name: share_plus + sha256: db40767f130189d53f3ae8a6393c217ff4a492da1baff718a9873679c0c00224 + url: "https://pub.dev" + source: hosted + version: "13.3.1" + share_plus_platform_interface: + dependency: transitive + description: + name: share_plus_platform_interface + sha256: "365ef7379fc22507256adda3385152942ffce08935452bc972c2e52a0bebae41" url: "https://pub.dev" source: hosted - version: "2.0.12" + version: "7.2.0" shared_preferences: dependency: transitive description: name: shared_preferences - sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f" url: "https://pub.dev" source: hosted - version: "2.5.3" + version: "2.5.6" shared_preferences_android: dependency: transitive description: name: shared_preferences_android - sha256: bd14436108211b0d4ee5038689a56d4ae3620fd72fd6036e113bf1345bc74d9e + sha256: "137dedccacb394b8f470d6c9b435ffc3d33faaa6ce2949c4f54a61007d64396d" url: "https://pub.dev" source: hosted - version: "2.4.13" + version: "2.5.5" shared_preferences_foundation: dependency: transitive description: name: shared_preferences_foundation - sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + sha256: "89435cb71ecb1ad1bf29ef73a381f871a06f433d4182b7e2ba7243b02b2c544b" url: "https://pub.dev" source: hosted - version: "2.5.4" + version: "2.6.2" shared_preferences_linux: dependency: transitive description: @@ -945,10 +1496,10 @@ packages: dependency: transitive description: name: shared_preferences_platform_interface - sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.2" shared_preferences_web: dependency: transitive description: @@ -969,10 +1520,10 @@ packages: dependency: transitive description: name: shelf - sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + sha256: e75e9cf311d7fd712048038cc17c25199c38536c20330d53e7db058b543d5a48 url: "https://pub.dev" source: hosted - version: "1.4.2" + version: "1.4.3" shelf_web_socket: dependency: transitive description: @@ -981,6 +1532,20 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.1" + shept_openapi_client_dart: + dependency: "direct main" + description: + path: "../shept_openapi_client_dart" + relative: true + source: path + version: "0.5.0" + shept_websocket_client_dart: + dependency: "direct main" + description: + path: "../shept_websocket_client_dart" + relative: true + source: path + version: "0.5.0" sky_engine: dependency: transitive description: flutter @@ -1006,10 +1571,10 @@ packages: dependency: transitive description: name: source_span - sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" url: "https://pub.dev" source: hosted - version: "1.10.1" + version: "1.10.2" sprintf: dependency: "direct main" description: @@ -1022,10 +1587,10 @@ packages: dependency: transitive description: name: stack_trace - sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" url: "https://pub.dev" source: hosted - version: "1.12.1" + version: "1.12.2" stream_channel: dependency: transitive description: @@ -1038,10 +1603,10 @@ packages: dependency: transitive description: name: stream_transform - sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + sha256: a00e5f18bffc764f923e7dec1038527f7fe7a1791361a7117f0358193f13d53a url: "https://pub.dev" source: hosted - version: "2.1.1" + version: "2.1.2" string_scanner: dependency: transitive description: @@ -1050,6 +1615,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + sync_http: + dependency: transitive + description: + name: sync_http + sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" + url: "https://pub.dev" + source: hosted + version: "0.3.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: a77637ebe1460f3b48cac89a790d2eb634f0a8593cab0d3f340c6db174ba9b94 + url: "https://pub.dev" + source: hosted + version: "3.6.1+1" term_glyph: dependency: transitive description: @@ -1062,18 +1643,18 @@ packages: dependency: transitive description: name: test_api - sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.6" + version: "0.7.12" timezone: dependency: transitive description: name: timezone - sha256: dd14a3b83cfd7cb19e7888f1cbc20f258b8d71b54c06f79ac585f14093a287d1 + sha256: "9f4e5a1a0e4fef7dd3424842c0575db01bfb7a11730e8d55753fcd5c5c98767b" url: "https://pub.dev" source: hosted - version: "0.10.1" + version: "0.11.2" timing: dependency: transitive description: @@ -1090,46 +1671,54 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + universal_io: + dependency: transitive + description: + name: universal_io + sha256: f63cbc48103236abf48e345e07a03ce5757ea86285ed313a6a032596ed9301e2 + url: "https://pub.dev" + source: hosted + version: "2.3.1" url_launcher: dependency: "direct main" description: name: url_launcher - sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda url: "https://pub.dev" source: hosted - version: "6.3.2" + version: "6.3.3" url_launcher_android: dependency: transitive description: name: url_launcher_android - sha256: "199bc33e746088546a39cc5f36bac5a278c5e53b40cb3196f99e7345fdcfae6b" + sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" url: "https://pub.dev" source: hosted - version: "6.3.22" + version: "6.3.33" url_launcher_ios: dependency: transitive description: name: url_launcher_ios - sha256: d80b3f567a617cb923546034cc94bfe44eb15f989fe670b37f26abdb9d939cb7 + sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" url: "https://pub.dev" source: hosted - version: "6.3.4" + version: "6.4.2" url_launcher_linux: dependency: transitive description: name: url_launcher_linux - sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935" + sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" url: "https://pub.dev" source: hosted - version: "3.2.1" + version: "3.2.3" url_launcher_macos: dependency: transitive description: name: url_launcher_macos - sha256: c043a77d6600ac9c38300567f33ef12b0ef4f4783a2c1f00231d2b1941fea13f + sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" url: "https://pub.dev" source: hosted - version: "3.2.3" + version: "3.2.6" url_launcher_platform_interface: dependency: transitive description: @@ -1142,66 +1731,138 @@ packages: dependency: transitive description: name: url_launcher_web - sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.3" url_launcher_windows: dependency: transitive description: name: url_launcher_windows - sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77" + sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" url: "https://pub.dev" source: hosted - version: "3.1.4" + version: "3.1.6" + uuid: + dependency: "direct main" + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" vector_math: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.4.4" vibration: dependency: "direct main" description: name: vibration - sha256: "1fd51cb0f91c6d512734ca0e282dd87fbc7f389b6da5f03c77709ba2cf8fa901" + sha256: "3424f7856b971a2ce94d22be3a3abfb5b9b5984562fdedd621f4e67574be7254" url: "https://pub.dev" source: hosted - version: "3.1.4" + version: "3.2.1" vibration_platform_interface: dependency: transitive description: name: vibration_platform_interface - sha256: "4134fbfcd427b59a7a91f8733292e4e9b29a7f1e8224ff0d80f5745fbf0743c6" + sha256: "258c273268f8aa40c88d29741137c536874a738779b92ddb8aa32ed093721ec5" + url: "https://pub.dev" + source: hosted + version: "0.1.2" + video_player: + dependency: "direct main" + description: + name: video_player + sha256: "07ae1e03f2d4c8e2e9a75ee678f90acbc4506d4458a9c628512d119a1eee5754" + url: "https://pub.dev" + source: hosted + version: "2.14.1" + video_player_android: + dependency: transitive + description: + name: video_player_android + sha256: d27054dea34d748a44f06d433a57005d2aac69944485b0abbaed3303dbcfa3f1 + url: "https://pub.dev" + source: hosted + version: "2.12.2" + video_player_avfoundation: + dependency: transitive + description: + name: video_player_avfoundation + sha256: "7d620d8c69d00c158a5c57bf3d2a051833b547631203ff724664fbf301024bc1" + url: "https://pub.dev" + source: hosted + version: "2.12.3" + video_player_platform_interface: + dependency: transitive + description: + name: video_player_platform_interface + sha256: "92c0fbabe20c788e71fd10d26cea998d0d253282e65d145aed0818731cf593ce" + url: "https://pub.dev" + source: hosted + version: "6.9.0" + video_player_web: + dependency: transitive + description: + name: video_player_web + sha256: "9f3c00be2ef9b76a95d94ac5119fb843dca6f2c69e6c9968f6f2b6c9e7afbdeb" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + video_trimmer: + dependency: "direct main" + description: + name: video_trimmer + sha256: b6d16e80bb7df0ad5acbde6b69359df14a60e866643afd7402db6a494fa0513a url: "https://pub.dev" source: hosted - version: "0.1.1" + version: "6.0.0" vm_service: dependency: transitive description: name: vm_service - sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" + url: "https://pub.dev" + source: hosted + version: "15.4.0" + wakelock_plus: + dependency: transitive + description: + name: wakelock_plus + sha256: "39a1d99085cf3190d41305bca05f0c0d77522f355f7f99bb648ee231192d9d68" url: "https://pub.dev" source: hosted - version: "15.0.2" + version: "1.8.2" + wakelock_plus_platform_interface: + dependency: transitive + description: + name: wakelock_plus_platform_interface + sha256: "764c25504562abc8ac3406f5d175f126b276e6ba916c7c2675690b73368ca384" + url: "https://pub.dev" + source: hosted + version: "1.7.0" watcher: dependency: transitive description: name: watcher - sha256: "5bf046f41320ac97a469d506261797f35254fa61c641741ef32dacda98b7d39c" + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" url: "https://pub.dev" source: hosted - version: "1.1.3" + version: "1.2.1" web: dependency: transitive description: name: web - sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b url: "https://pub.dev" source: hosted - version: "1.1.1" + version: "1.1.2" web_socket: dependency: transitive description: @@ -1218,40 +1879,38 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.3" - whisper_openapi_client_dart: - dependency: "direct main" - description: - path: "." - ref: HEAD - resolved-ref: b3511cc765cb349df2a9e7355a7dbb865145b079 - url: "https://github.com/jsfraz/whisper_openapi_client_dart.git" - source: git - version: "0.0.1" - whisper_websocket_client_dart: - dependency: "direct main" + webdriver: + dependency: transitive description: - path: "." - ref: HEAD - resolved-ref: "5e2d056568f13c1b72780d16a39d9e69bc1ce002" - url: "https://github.com/jsfraz/whisper_websocket_client_dart.git" - source: git - version: "1.0.0" + name: webdriver + sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e" + url: "https://pub.dev" + source: hosted + version: "3.2.0" win32: dependency: transitive description: name: win32 - sha256: "66814138c3562338d05613a6e368ed8cfb237ad6d64a9e9334be3f309acfca03" + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d url: "https://pub.dev" source: hosted - version: "5.14.0" + version: "6.4.0" win32_registry: dependency: transitive description: name: win32_registry - sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae" + sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" url: "https://pub.dev" source: hosted - version: "2.1.0" + version: "3.0.3" + windows_file_picker: + dependency: transitive + description: + name: windows_file_picker + sha256: cd1be37ada0abcfaa55bddb7410e8515844e35cd77669c35d9a28a15722299d8 + url: "https://pub.dev" + source: hosted + version: "2.0.2" xdg_directories: dependency: transitive description: @@ -1264,18 +1923,18 @@ packages: dependency: transitive description: name: xml - sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + sha256: "0fe8cc98946def31cbcbc8734aa4067031e6f65ea3a78a508060bfed2200bfeb" url: "https://pub.dev" source: hosted - version: "6.6.1" + version: "7.1.0" yaml: dependency: transitive description: name: yaml - sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea url: "https://pub.dev" source: hosted - version: "3.1.3" + version: "3.1.4" sdks: - dart: ">=3.9.0 <4.0.0" - flutter: ">=3.35.0" + dart: ">=3.13.0 <4.0.0" + flutter: ">=3.47.0" diff --git a/pubspec.yaml b/pubspec.yaml index ff69205..bd404b8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,8 +1,9 @@ -name: whisper +name: shept description: "Secure private self-hosted end-to-end encryption messaging app." publish_to: 'none' # Remove this line if you wish to publish to pub.dev -# TODO change version when relasing new version -version: 0.0.1 +# Bump before every release; the release workflow tags v and fails if +# that tag already exists. The build number after + must only ever grow. +version: 0.4.0+8 environment: sdk: '>=3.4.3 <4.0.0' @@ -10,44 +11,66 @@ environment: dependencies: basic_utils: ^5.7.0 bcrypt: ^1.1.3 + camera: ^0.12.2 + chewie: ^1.17.4 + connectivity_plus: ^7.3.2 + crop_your_image: ^2.0.1 + receive_sharing_intent: ^1.9.0 + share_plus: ^13.3.1 + video_trimmer: ^6.0.0 crypto: ^3.0.5 cryptography: ^2.7.0 dart_jsonwebtoken: ^3.2.0 easy_localization: ^3.0.7 email_validator: ^3.0.0 - firebase_core: ^4.0.0 - firebase_messaging: ^16.0.0 + file_picker: ^13.3.3 + # Firebase is retired. The code is commented out, not deleted, so it can be + # revived or stripped later. Re-enable both lines to bring push back. + # firebase_core: ^5.1.0 + # firebase_messaging: ^17.0.1 flutter: sdk: flutter flutter_colorpicker: ^1.1.0 flutter_launcher_icons: ^0.14.3 - flutter_local_notifications: ^19.2.1 - flutter_secure_storage: ^9.2.4 - fluttertoast: ^9.0.0 + flutter_local_notifications: ^23.0.0 + flutter_secure_storage: ^11.2.0 + fluttertoast: ^10.0.2 + geolocator: ^14.0.1 hive: ^2.2.3 http: ^1.2.1 + image_picker: ^1.2.2 json_annotation: ^4.9.0 - jwt_decoder: ^2.0.1 - local_auth: ^2.3.0 - mobile_scanner: ^7.0.0 + just_audio: ^0.10.5 + local_auth: ^3.0.1 + mcp_toolkit: 7.0.1 + mime: ^2.0.0 page_transition: ^2.2.1 path_provider: ^2.1.3 pointycastle: ^4.0.0 provider: ^6.1.2 qr_code_scanner_plus: ^2.0.6 + record: ^7.1.2 sprintf: ^7.0.0 url_launcher: ^6.3.1 + uuid: ^4.5.3 vibration: ^3.1.2 - whisper_openapi_client_dart: + video_player: ^2.11.1 + # Clients are pinned by release tag: the app records which contract it was + # built against. Local development overrides the paths at the bottom. + shept_openapi_client_dart: git: - url: https://github.com/jsfraz/whisper_openapi_client_dart.git - whisper_websocket_client_dart: + url: https://github.com/jsfraz/shept_openapi_client_dart.git + ref: v0.5.0 + shept_websocket_client_dart: git: - url: https://github.com/jsfraz/whisper_websocket_client_dart.git + url: https://github.com/jsfraz/shept_websocket_client_dart.git + ref: v0.5.0 dev_dependencies: flutter_test: sdk: flutter + integration_test: + sdk: flutter flutter_lints: ^6.0.0 hive_generator: ^2.0.1 build_runner: ^2.4.12 @@ -56,5 +79,6 @@ dev_dependencies: flutter: uses-material-design: true assets: - # - assets/images/ + # Only the raster: the SVG source stays out of the bundle. + - assets/images/chat_bg.png - assets/translations/ diff --git a/test/admin_format_test.dart b/test/admin_format_test.dart new file mode 100644 index 0000000..1e04adf --- /dev/null +++ b/test/admin_format_test.dart @@ -0,0 +1,33 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/admin_format.dart'; + +User user(String name) => User(name, name, 'public-key', false); + +void main() { + test('invite lifetime is bucketed into minutes, hours and days', () { + expect( + inviteRemaining(const Duration(seconds: 20)), (value: 1, unit: 'min')); + expect( + inviteRemaining(const Duration(minutes: 14)), (value: 14, unit: 'min')); + expect(inviteRemaining(const Duration(minutes: 90)), (value: 1, unit: 'h')); + expect(inviteRemaining(const Duration(days: 3, hours: 5)), + (value: 3, unit: 'd')); + }); + + test('expired invites have no remaining lifetime', () { + expect(inviteRemaining(const Duration(seconds: -1)), isNull); + }); + + test('users are sorted by name, case insensitive', () { + final sorted = + sortedByUsername([user('zdeněk'), user('Adam'), user('bob')]); + expect(sorted.map((u) => u.username), ['Adam', 'bob', 'zdeněk']); + }); + + test('sorting keeps the input list untouched', () { + final users = [user('b'), user('a')]; + sortedByUsername(users); + expect(users.map((u) => u.username), ['b', 'a']); + }); +} diff --git a/test/admin_user_list_item_test.dart b/test/admin_user_list_item_test.dart new file mode 100644 index 0000000..c1f8b19 --- /dev/null +++ b/test/admin_user_list_item_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/widgets/admin_user_list_item.dart'; + +Widget app(User user, VoidCallback onDelete) { + return MaterialApp( + home: Scaffold(body: AdminUserListItem(user, onDelete: onDelete)), + ); +} + +void main() { + testWidgets('shows the initial, the name and no badge for a normal user', + (tester) async { + await tester.pumpWidget(app(User('1', 'test', 'key', false), () {})); + + expect(find.text('T'), findsOneWidget); + expect(find.text('test'), findsOneWidget); + expect(find.text('adminBadge'), findsNothing); + }); + + testWidgets('marks admins with a badge', (tester) async { + await tester.pumpWidget(app(User('1', 'root', 'key', true), () {})); + + expect(find.text('adminBadge'), findsOneWidget); + }); + + testWidgets('the overflow menu offers the delete action', (tester) async { + var deleted = 0; + await tester.pumpWidget(app(User('1', 'test', 'key', false), () { + deleted++; + })); + + await tester.tap(find.byIcon(Icons.more_vert)); + await tester.pumpAndSettle(); + + expect(find.text('deleteUser'), findsOneWidget); + expect(deleted, 0); + + await tester.tap(find.text('deleteUser')); + await tester.pumpAndSettle(); + + expect(deleted, 1); + }); +} diff --git a/test/api_client_test.dart b/test/api_client_test.dart new file mode 100644 index 0000000..d89a2f7 --- /dev/null +++ b/test/api_client_test.dart @@ -0,0 +1,14 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/io_client.dart'; +import 'package:shept/utils/singleton.dart'; + +void main() { + // The generated client has no timeout of its own; the app has to install a + // transport that gives up on a stalled server instead of hanging a future. + test('the api client uses an explicit http transport', () { + final api = Singleton.createApiClient('https://chat.example.com'); + + expect(api.basePath, 'https://chat.example.com'); + expect(api.client, isA()); + }); +} diff --git a/test/attachment_confirm_sheet_test.dart b/test/attachment_confirm_sheet_test.dart new file mode 100644 index 0000000..0957d35 --- /dev/null +++ b/test/attachment_confirm_sheet_test.dart @@ -0,0 +1,101 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/widgets/attachment_confirm_sheet.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + setUpAll(() async { + // easy_localization reads the locale from shared_preferences + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + }); + + // One app for the whole test: easy_localization loads its bundle once, and a + // second pumpWidget would leave the tree without translations. + testWidgets('the sheet returns the caption and the view-once choice', + (tester) async { + AttachmentConfirmResult? result; + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Builder( + builder: (inner) => Scaffold( + body: Column( + children: [ + ElevatedButton( + onPressed: () async { + result = await AttachmentConfirmSheet.show(inner, + count: 2, initialCaption: 'draft'); + }, + child: const Text('album'), + ), + ElevatedButton( + onPressed: () async { + result = await AttachmentConfirmSheet.show(inner, + count: 1, allowViewOnce: true); + }, + child: const Text('single'), + ), + ElevatedButton( + onPressed: () async { + result = await AttachmentConfirmSheet.show(inner, + count: 1, allowViewOnce: false); + }, + child: const Text('plain'), + ), + ], + ), + ), + ), + ); + }), + )); + // Let easy_localization load the bundle before interacting. + await tester.pumpAndSettle(); + + // Cancel + await tester.tap(find.text('album')); + await tester.pumpAndSettle(); + expect(find.text('draft'), findsOneWidget); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(result, isNull); + + // Send: the exit animation keeps rebuilding the sheet, which used to touch + // a controller that had already been disposed. + await tester.tap(find.text('album')); + await tester.pumpAndSettle(); + await tester.tap(find.byType(FilledButton)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(result!.caption, 'draft'); + expect(result!.viewOnce, isFalse); + + // One visual attachment can be turned into a single view. + await tester.tap(find.text('single')); + await tester.pumpAndSettle(); + expect(find.byType(CheckboxListTile), findsOneWidget); + await tester.tap(find.byType(CheckboxListTile)); + await tester.pumpAndSettle(); + await tester.tap(find.byType(FilledButton)); + await tester.pumpAndSettle(); + expect(result!.viewOnce, isTrue); + + // An album or a file is never offered the switch. + await tester.tap(find.text('plain')); + await tester.pumpAndSettle(); + expect(find.byType(CheckboxListTile), findsNothing); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + }); +} diff --git a/test/auth_refresh_fallback_test.dart b/test/auth_refresh_fallback_test.dart new file mode 100644 index 0000000..de8b492 --- /dev/null +++ b/test/auth_refresh_fallback_test.dart @@ -0,0 +1,211 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:pointycastle/export.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/utils.dart'; +import 'package:shept_openapi_client_dart/api.dart'; + +/// flutter_test replaces HttpClient with one that answers 400 and never touches +/// the network; this test serves its own backend on loopback. +class _RealHttpOverrides extends HttpOverrides {} + +/// An unsigned JWT that only has to be readable by the local expiry check. +String tokenExpiring({required Duration inFuture, String typ = 'access'}) { + String encode(Map value) => + base64Url.encode(utf8.encode(jsonEncode(value))).replaceAll('=', ''); + final payload = { + 'sub': 'user', + 'typ': typ, + 'exp': DateTime.now().add(inFuture).millisecondsSinceEpoch ~/ 1000, + }; + return '${encode({'alg': 'HS256', 'typ': 'JWT'})}.${encode(payload)}.sig'; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory dir; + late HttpServer server; + late AsymmetricKeyPair keys; + late List requestedPaths; + const challenge = 'test-challenge-1'; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_auth_fallback_test'); + Hive.init(dir.path); + Hive.registerAdapter(ProfileAdapter()); + Hive.registerAdapter(UserAdapter()); + // Not used here, but the box collection is shared with the message tests. + Hive.registerAdapter(PrivateMessageAdapter()); + // 2048 bits is enough here: the fake server never verifies the signature. + keys = bu.CryptoUtils.generateRSAKeyPair(); + + // path_provider is not registered in a unit test; CacheUtils needs a dir. + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => dir.path, + ); + // The login now registers the installation, and the device id lives in + // secure storage. Keep it in memory for the test. + final secureStorage = {}; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.it_nomads.com/flutter_secure_storage'), + (call) async { + final args = (call.arguments as Map?) ?? const {}; + switch (call.method) { + case 'read': + return secureStorage[args['key']]; + case 'write': + secureStorage[args['key'] as String] = args['value'] as String; + return null; + case 'delete': + secureStorage.remove(args['key']); + return null; + case 'readAll': + return Map.from(secureStorage); + case 'deleteAll': + secureStorage.clear(); + return null; + } + return null; + }, + ); + }); + + setUp(() async { + HttpOverrides.global = _RealHttpOverrides(); + requestedPaths = []; + Singleton().boxCollectionKey = List.filled(32, 7); + Singleton().profile = Profile( + 'http://localhost', + User('user', 'tester', 'public-key', false), + 'public-key', + bu.CryptoUtils.encodeRSAPrivateKeyToPem(keys.privateKey as RSAPrivateKey), + tokenExpiring(inFuture: const Duration(minutes: 10)), + tokenExpiring(inFuture: const Duration(days: 6), typ: 'refresh'), + true, + ); + }); + + tearDown(() async { + await server.close(force: true); + }); + + Future startServer({required int refreshStatus}) async { + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) async { + requestedPaths.add(request.uri.path); + final body = await utf8.decoder.bind(request).join(); + request.response.headers.contentType = ContentType.json; + if (request.uri.path == '/api/auth/challenge') { + request.response.statusCode = 200; + request.response + .write(jsonEncode({'challenge': challenge, 'expiresIn': 30})); + } else if (request.uri.path == '/api/auth/refresh') { + request.response.statusCode = refreshStatus; + request.response.write(refreshStatus == 200 + ? jsonEncode({ + 'accessToken': 'refreshed-access', + 'refreshToken': 'rotated-refresh', + }) + : jsonEncode({'error': 'refresh session was revoked'})); + } else if (request.uri.path == '/api/auth') { + expect(body, contains('token')); + // The signed login token must carry the one-time challenge. + final token = + (jsonDecode(body) as Map)['token'] as String; + final payload = jsonDecode(utf8.decode( + base64Url.decode(base64Url.normalize(token.split('.')[1])))) + as Map; + expect(payload['nonce'], challenge); + request.response.statusCode = 200; + request.response.write(jsonEncode({ + 'accessToken': 'fresh-access', + 'refreshToken': 'fresh-refresh', + // The login answer names the server build now; the model requires it. + 'serverVersion': '0.1.0', + })); + } else { + request.response.statusCode = 404; + request.response.write(jsonEncode({'error': 'not found'})); + } + await request.response.close(); + }); + Singleton().api = ApiClient(basePath: 'http://127.0.0.1:${server.port}'); + } + + test('a refused refresh falls back to the RSA login', () async { + // The token in the store predates revocable sessions: the server answers + // 401 and the app used to stay unauthorized forever. + await startServer(refreshStatus: 401); + Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); + + await Utils.authCheck(); + + expect(requestedPaths, contains('/api/auth/refresh')); + expect(requestedPaths, contains('/api/auth/challenge')); + expect(requestedPaths, contains('/api/auth')); + expect(Singleton().profile.accessToken, 'fresh-access'); + expect(Singleton().profile.refreshToken, 'fresh-refresh'); + expect(Singleton().profile.accessToken, isNot('old-access')); + expect(Singleton().profile.refreshToken, isNot('legacy-refresh')); + }); + + test('a working refresh does not trigger a full login', () async { + await startServer(refreshStatus: 200); + Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); + + await Utils.authCheck(); + + expect(requestedPaths, ['/api/auth/refresh']); + expect(Singleton().profile.accessToken, 'refreshed-access'); + // The server rotates the refresh token; keeping the old one would break the + // next refresh. + expect(Singleton().profile.refreshToken, 'rotated-refresh'); + }); + + test('concurrent callers share one renewal', () async { + // The refresh token is single use: two parallel refreshes would burn the + // session, so a resume must not fan out. + await startServer(refreshStatus: 200); + Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); + + await Future.wait( + [Utils.authCheck(), Utils.authCheck(), Utils.authCheck()]); + + expect(requestedPaths, ['/api/auth/refresh']); + expect(Singleton().profile.accessToken, 'refreshed-access'); + }); + + test('a live access token skips the network entirely', () async { + await startServer(refreshStatus: 200); + final accessToken = Singleton().profile.accessToken; + + await Utils.authCheck(); + + expect(requestedPaths, isEmpty); + expect(Singleton().profile.accessToken, accessToken); + }); + + test('the profile survives a restart with the new tokens', () async { + await startServer(refreshStatus: 401); + Singleton().profile.accessToken = tokenExpiring(inFuture: Duration.zero); + + await Utils.authCheck(); + + final stored = await CacheUtils.getProfile(); + expect(stored.accessToken, 'fresh-access'); + expect(stored.refreshToken, 'fresh-refresh'); + }); +} diff --git a/test/auto_download_test.dart b/test/auto_download_test.dart new file mode 100644 index 0000000..f032e95 --- /dev/null +++ b/test/auto_download_test.dart @@ -0,0 +1,57 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/utils/auto_download.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_auto_download_test'); + Hive.init(dir.path); + }); + + setUp(() async { + await Hive.openBox('settings'); + await Hive.box('settings').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + MediaReference reference(MediaType type, int size) => + MediaReference('id', Uint8List(32), type, size); + + test('a voice message is always fetched, whatever the network', () async { + await CacheUtils.setAutoDownloadPolicy(AutoDownloadPolicy.never); + + expect( + await AutoDownload.allows(reference(MediaType.voice, 5 << 20)), isTrue); + expect(await AutoDownload.allows(reference(MediaType.sticker, 5 << 20)), + isTrue); + }); + + test('a large photo is not fetched under the never policy', () async { + await CacheUtils.setAutoDownloadPolicy(AutoDownloadPolicy.never); + + expect(await AutoDownload.allows(reference(MediaType.image, 4 << 20)), + isFalse); + }); + + test('a small attachment is fetched even under the never policy', () async { + await CacheUtils.setAutoDownloadPolicy(AutoDownloadPolicy.never); + + expect(await AutoDownload.allows(reference(MediaType.image, 1024)), isTrue); + }); + + test('the default policy is Wi-Fi only', () async { + expect(await CacheUtils.getAutoDownloadPolicy(), AutoDownloadPolicy.wifi); + }); +} diff --git a/test/avatar_rule_test.dart b/test/avatar_rule_test.dart new file mode 100644 index 0000000..00ca8ea --- /dev/null +++ b/test/avatar_rule_test.dart @@ -0,0 +1,83 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/chat_bubble.dart'; + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + // One app for the whole test: easy_localization loads its bundle once. + testWidgets('the avatar closes a run, unless the caller says otherwise', + (tester) async { + final message = + PrivateMessage('2', 'ahoj', DateTime(2026), DateTime(2026), true); + + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ChatBubble( + null, + message, + null, + peer, + accentColor: Colors.blue, + ), + ), + ), + ); + }), + )); + await tester.pumpAndSettle(); + expect(find.byType(CircleAvatar), findsOneWidget); + + // The live-location marker follows, so this message does not close the run. + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ChatBubble( + null, + message, + null, + peer, + accentColor: Colors.blue, + showAvatar: false, + ), + ), + ), + ); + }), + )); + await tester.pumpAndSettle(); + expect(find.byType(CircleAvatar), findsNothing); + }); +} diff --git a/test/batch_decrypt_test.dart b/test/batch_decrypt_test.dart new file mode 100644 index 0000000..11f590c --- /dev/null +++ b/test/batch_decrypt_test.dart @@ -0,0 +1,55 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:basic_utils/basic_utils.dart' as bu; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/crypto_utils.dart'; + +void main() { + test('album is decoded once per stored json', () { + final message = + PrivateMessage('1', '', DateTime.now(), DateTime.now(), false); + + message.setAlbum([ + AlbumItem(mediaId: 'a', type: 'image', size: 1), + ]); + final first = message.album; + expect(first.single.mediaId, 'a'); + // Cached: the same list instance comes back. + expect(identical(message.album, first), isTrue); + + message.setAlbum([ + AlbumItem(mediaId: 'b', type: 'image', size: 1), + ]); + expect(message.album.single.mediaId, 'b'); + }); + + test('batch decryption round-trips and keeps failures as null', () async { + final keyPair = await CryptoUtils.getRSAKeyPair(); + final publicKey = keyPair.publicKey as bu.RSAPublicKey; + final privateKeyPem = bu.CryptoUtils.encodeRSAPrivateKeyToPem( + keyPair.privateKey as bu.RSAPrivateKey); + + final payload = Uint8List.fromList(utf8.encode('ahoj')); + final encrypted = await CryptoUtils.encryptMessageData(payload, publicKey); + final valid = { + 'data': encrypted['encryptedData']!, + 'key': encrypted['encryptedKey']!, + 'nonce': encrypted['nonce']!, + 'mac': encrypted['mac']!, + }; + // Same ciphertext with a wrong MAC must fail on its own. + final broken = { + ...valid, + 'mac': Uint8List.fromList(List.filled(16, 7)), + }; + + final result = + await CryptoUtils.decryptMessageBatch([valid, broken], privateKeyPem); + + expect(result, hasLength(2)); + expect(result.first, payload); + expect(result.last, isNull); + }); +} diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart new file mode 100644 index 0000000..c36d12c --- /dev/null +++ b/test/chat_bubble_test.dart @@ -0,0 +1,313 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/text_envelope.dart'; +import 'package:shept/widgets/chat_bubble.dart'; +import 'package:shept/widgets/media_bubble.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +/// Plain text of everything the bubble rendered, spans included. +String renderedText(WidgetTester tester) => tester + .widgetList(find.byType(RichText)) + .map((widget) => widget.text.toPlainText()) + .join('\n'); + +/// Style of the span that renders exactly [text], null when it is not there. +TextStyle? spanStyle(WidgetTester tester, String text) { + for (final widget in tester.widgetList(find.byType(RichText))) { + TextStyle? found; + widget.text.visitChildren((span) { + if (span is TextSpan && span.text == text) { + found = span.style; + return false; + } + return true; + }); + if (found != null) { + return found; + } + } + return null; +} + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + // isMe compares against the signed-in user. + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('the bubble renders, quotes, selects and replies', + (tester) async { + // One app for the whole test: easy_localization loads its asset once, and a + // second pumpWidget would leave the tree without translations. + final shown = ValueNotifier(const SizedBox()); + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ValueListenableBuilder( + valueListenable: shown, + builder: (_, child, __) => child, + ), + ), + ), + ); + }), + )); + + Future show(Widget child) async { + shown.value = child; + await tester.pumpAndSettle(); + } + + // Formatting: the markers never reach the screen. + await show(ChatBubble( + null, + PrivateMessage( + '2', 'the **bold** part', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + expect(renderedText(tester), contains('the bold part')); + expect(renderedText(tester), isNot(contains('**'))); + + // A reply shows what it quotes, and tapping the quote jumps to it. + var jumped = false; + await show(ChatBubble( + null, + PrivateMessage('2', 'souhlas', DateTime(2026), DateTime(2026), true) + ..setReplyTo(ReplyRef( + senderId: '1', + sentAt: DateTime(2025), + preview: 'původní dotaz', + )), + null, + peer, + accentColor: Colors.blue, + onTapQuote: () => jumped = true, + )); + expect(renderedText(tester), contains('původní dotaz')); + expect(renderedText(tester), contains('souhlas')); + await tester.tap(find.text('původní dotaz')); + await tester.pumpAndSettle(); + expect(jumped, isTrue); + + // Selection mode marks the bubble. + await show(ChatBubble( + null, + PrivateMessage('2', 'x', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + selectionMode: true, + selected: true, + )); + expect(find.byIcon(Icons.check_circle), findsOneWidget); + + // Double tap adds the quick reaction instead of quoting. + var reacted = false; + var replied = false; + await show(ChatBubble( + null, + PrivateMessage('2', 'ahoj', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + onReply: () => replied = true, + onQuickReact: () => reacted = true, + )); + await tester.tap(find.text('ahoj')); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tap(find.text('ahoj')); + await tester.pumpAndSettle(); + expect(reacted, isTrue); + expect(replied, isFalse); + + // A long message can be unfolded. + await show(ChatBubble( + null, + PrivateMessage('2', 'x' * 700, DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + expect(find.text('Show full message'), findsOneWidget); + await tester.tap(find.text('Show full message')); + await tester.pumpAndSettle(); + expect(find.text('Show less'), findsOneWidget); + + // A forwarded message says so above its body. + await show(ChatBubble( + null, + PrivateMessage( + '2', 'přeposlaný text', DateTime(2026), DateTime(2026), true) + ..forwarded = true, + null, + peer, + accentColor: Colors.blue, + )); + expect(find.text('Forwarded'), findsOneWidget); + expect(renderedText(tester), contains('přeposlaný text')); + + // Only the peer's cursor covering the message shows a tick; there is no + // single "delivered" tick any more. + final sent = DateTime(2026, 11, 19, 12); + await show(ChatBubble( + null, + PrivateMessage('1', 'odesláno', sent, sent, true), + null, + peer, + accentColor: Colors.blue, + )); + expect(find.byIcon(Icons.done), findsNothing); + expect(find.byIcon(Icons.done_all), findsNothing); + + await show(ChatBubble( + null, + PrivateMessage('1', 'přečteno', sent, sent, true), + null, + peer, + accentColor: Colors.blue, + readAt: sent, + )); + expect(find.byIcon(Icons.done_all), findsOneWidget); + + // Reactions are one badge hanging on the bubble's bottom edge: no gap + // between the emoji and none between the badge and the bubble. + final sentAt = DateTime(2026, 11, 19, 12); + var reactionsOpened = 0; + var actionsOpened = 0; + await show(ChatBubble( + null, + PrivateMessage('1', 'reaguj', sentAt, sentAt, true) + ..reactions = {'1': '❤️', '2': '😂'}, + null, + peer, + accentColor: Colors.blue, + onActions: () => actionsOpened++, + onReactions: () => reactionsOpened++, + )); + expect(find.text('❤️'), findsOneWidget); + expect(find.text('😂'), findsOneWidget); + final body = tester.getRect(find.text('reaguj')); + final heart = tester.getRect(find.text('❤️')); + final laugh = tester.getRect(find.text('😂')); + // Overlapping the bubble instead of sitting below it. + expect(heart.top, lessThan(body.bottom + 5)); + // The two emoji are one badge, not two chips with a gap. + expect(laugh.left - heart.right, lessThan(8)); + // Tapping the badge asks who reacted, not for the action sheet. + await tester.tap(find.text('❤️')); + await tester.pumpAndSettle(); + expect(reactionsOpened, 1); + expect(actionsOpened, 0); + + // Phone numbers and e-mails are underlined like a link. + await show(ChatBubble( + null, + PrivateMessage('2', 'volej +420 123 456 789 nebo piš na jan@example.com', + DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + for (final tappable in ['+420 123 456 789', 'jan@example.com']) { + final style = spanStyle(tester, tappable); + expect(style, isNotNull, reason: tappable); + expect(style!.decoration, TextDecoration.underline, reason: tappable); + expect(style.decorationStyle ?? TextDecorationStyle.solid, + TextDecorationStyle.solid, + reason: tappable); + } + + // An attachment is the bubble: no coloured frame or padding around it. + await show(ChatBubble( + null, + PrivateMessage( + '2', + '', + DateTime(2026), + DateTime(2026), + true, + mediaTypeStr: MediaType.image.name, + downloadStatus: MediaDownloadStatus.failed, + ), + null, + peer, + accentColor: Colors.blue, + )); + final mediaFrame = tester.widget(find + .ancestor( + of: find.byType(MediaBubble), matching: find.byType(Container)) + .first); + expect(mediaFrame.padding, EdgeInsets.zero); + expect((mediaFrame.decoration as BoxDecoration?)?.color, isNull); + + // A voice message shows the reaction it carries: the badge sits inside the + // bubble's edge, so a quick react there is not a silent no-op. + var mediaReactions = 0; + await show(ChatBubble( + null, + PrivateMessage('2', '', DateTime(2026), DateTime(2026), true, + mediaTypeStr: MediaType.voice.name, + downloadStatus: MediaDownloadStatus.failed) + ..reactions = {'2': '👍'}, + null, + peer, + accentColor: Colors.blue, + onReactions: () => mediaReactions++, + )); + expect(find.text('👍'), findsOneWidget); + // The badge on a media bubble is tappable too: it used to hang outside its + // parent's bounds, which paints but never hits. + await tester.tap(find.text('👍')); + await tester.pumpAndSettle(); + expect(mediaReactions, 1); + + // A jump lights the target bubble and drops the frame again afterwards. + Future frame(ChatBubble bubble) async { + await show(bubble); + return tester + .widget(find + .ancestor( + of: find.text('cíl'), + matching: find.byType(AnimatedContainer)) + .first) + .foregroundDecoration; + } + + ChatBubble target({required bool highlight, bool selected = false}) => + ChatBubble( + null, + PrivateMessage('2', 'cíl', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + highlight: highlight, + selected: selected, + ); + expect(await frame(target(highlight: false)), isNull); + expect(await frame(target(highlight: true)), isNotNull); + expect(await frame(target(highlight: true, selected: true)), isNotNull); + }); +} diff --git a/test/chat_date_test.dart b/test/chat_date_test.dart new file mode 100644 index 0000000..5dbb886 --- /dev/null +++ b/test/chat_date_test.dart @@ -0,0 +1,43 @@ +import 'package:easy_localization/easy_localization.dart'; +// intl is pinned through easy_localization; same import as the app itself. +// ignore: depend_on_referenced_packages +import 'package:intl/date_symbol_data_local.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/chat_date.dart'; + +void main() { + final now = DateTime(2026, 6, 10, 12); + + setUpAll(() async { + await initializeDateFormatting('en'); + Intl.defaultLocale = 'en'; + }); + + String label(DateTime when) => chatDateLabel(when, + todayLabel: 'Today', yesterdayLabel: 'Yesterday', now: now); + + test('today carries the localized label and the time', () { + expect(label(DateTime(2026, 6, 10, 9, 5)), 'Today 09:05'); + }); + + test('yesterday carries its own label', () { + expect(label(DateTime(2026, 6, 9, 23, 59)), 'Yesterday 23:59'); + }); + + test('the last week shows the weekday name', () { + final when = DateTime(2026, 6, 7, 8, 30); + expect(label(when), '${DateFormat.EEEE().format(when)} 08:30'); + }); + + test('an older message this year shows the date without the year', () { + final when = DateTime(2026, 5, 3, 8); + expect(label(when), DateFormat.MMMMd().format(when)); + expect(label(when).contains('2026'), isFalse); + }); + + test('a message from another year shows the year', () { + final when = DateTime(2025, 12, 31, 8); + expect(label(when), DateFormat.yMMMMd().format(when)); + expect(label(when).contains('2025'), isTrue); + }); +} diff --git a/test/chat_info_media_test.dart b/test/chat_info_media_test.dart new file mode 100644 index 0000000..0f1fc6b --- /dev/null +++ b/test/chat_info_media_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/message_notifier.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +PrivateMessage message(String? type, String? path, DateTime sentAt, + {int? downloadStatus}) { + return PrivateMessage('1', '', sentAt, sentAt, false, + mediaTypeStr: type, + localPath: path, + downloadStatus: downloadStatus ?? MediaDownloadStatus.ready); +} + +PrivateMessage album(DateTime sentAt, String path, MediaType type, + {int status = MediaDownloadStatus.ready}) { + final result = PrivateMessage('1', '', sentAt, sentAt, false); + result.setAlbum([ + AlbumItem( + mediaId: 'a', + type: type.name, + size: 1, + localPath: path, + status: status), + ]); + return result; +} + +void main() { + test('shared media needs a local file, whatever the status says', () { + final now = DateTime(2026, 11, 12, 12); + final media = MessageNotifier.viewableMedia([ + message('image', '/tmp/a.jpg', now), + message('video', '/tmp/b.mp4', now.subtract(const Duration(minutes: 1))), + // Voice messages are not part of the overview + message('voice', '/tmp/c.m4a', now.subtract(const Duration(minutes: 2))), + // Not downloaded yet + message('image', null, now.subtract(const Duration(minutes: 3))), + // Still downloading + message('image', null, now.subtract(const Duration(minutes: 4)), + downloadStatus: MediaDownloadStatus.pending), + // A stale failure flag must not hide a file that is right there + message('image', '/tmp/e.jpg', now.subtract(const Duration(minutes: 5)), + downloadStatus: MediaDownloadStatus.expired), + // Plain text + message(null, null, now.subtract(const Duration(minutes: 6))), + ]); + + expect(media.map((m) => m.localPath), + ['/tmp/a.jpg', '/tmp/b.mp4', '/tmp/e.jpg']); + }); + + test('an album contributes each of its attachments', () { + final now = DateTime(2026, 11, 12, 12); + final media = MessageNotifier.viewableMedia([ + album(now, '/tmp/a.jpg', MediaType.image), + album(now.subtract(const Duration(minutes: 1)), '/tmp/b.mp4', + MediaType.video, + status: MediaDownloadStatus.failed), + ]); + + expect(media.map((m) => m.localPath), ['/tmp/a.jpg', '/tmp/b.mp4']); + expect(media.first.mediaType, MediaType.image); + }); +} diff --git a/test/chat_list_item_test.dart b/test/chat_list_item_test.dart new file mode 100644 index 0000000..096e5a8 --- /dev/null +++ b/test/chat_list_item_test.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/chat_list_item.dart'; + +Widget app(PrivateMessage last, {DateTime? peerReadAt}) { + return MaterialApp( + home: Scaffold( + body: ChatListItem(User('1', 'peer', 'key', false), last, () {}, + peerReadAt: peerReadAt), + ), + ); +} + +void main() { + setUp(() { + Singleton().profile = Profile('http://localhost', + User('me', 'me', 'key', false), 'key', 'private-key', '', '', true); + }); + + final sentAt = DateTime(2026, 5, 1, 12); + PrivateMessage own() => PrivateMessage('me', 'text', sentAt, sentAt, false); + PrivateMessage theirs() => PrivateMessage('1', 'text', sentAt, sentAt, false); + + testWidgets('an own message carries the tick once the cursor covers it', + (tester) async { + await tester.pumpWidget(app(own(), peerReadAt: sentAt)); + expect(find.byIcon(Icons.done_all), findsOneWidget); + }); + + testWidgets('no tick while the cursor is behind the message', (tester) async { + await tester.pumpWidget( + app(own(), peerReadAt: sentAt.subtract(const Duration(seconds: 1)))); + expect(find.byIcon(Icons.done_all), findsNothing); + }); + + testWidgets('an incoming message never carries the tick', (tester) async { + await tester.pumpWidget(app(theirs(), peerReadAt: sentAt)); + expect(find.byIcon(Icons.done_all), findsNothing); + }); + + testWidgets('receipts off means no tick', (tester) async { + await tester.pumpWidget(app(own())); + expect(find.byIcon(Icons.done_all), findsNothing); + }); +} diff --git a/test/chat_media_page_test.dart b/test/chat_media_page_test.dart new file mode 100644 index 0000000..7694a37 --- /dev/null +++ b/test/chat_media_page_test.dart @@ -0,0 +1,76 @@ +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/pages/chat_media_page.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_chat_media_page'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + await Hive.openBox('conversations'); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + Widget app() => EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: const ChatMediaPage('peer'), + ); + }), + ); + + testWidgets('an empty chat says so instead of drawing nothing', + (tester) async { + await tester.runAsync(() => tester.pumpWidget(app())); + await tester.pumpAndSettle(); + + expect(find.text('No media in this chat yet'), findsOneWidget); + }); + + testWidgets('a document shows its extension badge', (tester) async { + final sentAt = DateTime(2026, 11, 20, 12); + // Hive writes are real file I/O: outside runAsync the fake test clock would + // wait on them forever. + await tester.runAsync(() => CacheUtils.addPrivateMessages('peer', [ + PrivateMessage('peer', '', sentAt, sentAt, true, + localPath: '/tmp/shept_test_report.pdf', + mediaTypeStr: MediaType.file.name, + fileName: 'report.pdf'), + ])); + + await tester.runAsync(() => tester.pumpWidget(app())); + await tester.pumpAndSettle(); + + expect(find.text('PDF'), findsOneWidget); + expect(find.text('No media in this chat yet'), findsNothing); + }); +} diff --git a/test/chat_scroll_test.dart b/test/chat_scroll_test.dart new file mode 100644 index 0000000..0a0062d --- /dev/null +++ b/test/chat_scroll_test.dart @@ -0,0 +1,37 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/chat_scroll.dart'; + +void main() { + group('windowForAddition', () { + test('includes the target plus a margin of newer messages', () { + // 100 messages, target at 40, 5 above it: 100 - 40 + 5. + expect(windowForAddition(100, 40), 65); + }); + + test('the newest message needs only the margin', () { + expect(windowForAddition(100, 99), 6); + }); + + test('the oldest message needs the whole conversation', () { + expect(windowForAddition(100, 0), 100); + }); + + test('never asks for more than there is', () { + expect(windowForAddition(3, 0), 3); + }); + }); + + group('nextJumpOffset', () { + test('moves one viewport towards newer messages', () { + expect(nextJumpOffset(1000, 600), 400); + }); + + test('stops at the newest message instead of going negative', () { + expect(nextJumpOffset(200, 600), 0); + }); + + test('returns the same offset when already at the newest message', () { + expect(nextJumpOffset(0, 600), 0); + }); + }); +} diff --git a/test/chat_theme_dialog_test.dart b/test/chat_theme_dialog_test.dart new file mode 100644 index 0000000..b42e108 --- /dev/null +++ b/test/chat_theme_dialog_test.dart @@ -0,0 +1,79 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/dialog_utils.dart'; +import 'package:shept/widgets/theme_palette.dart'; + +/// The per-chat dialog shares the app theme's palette, and adds the one choice +/// that only a chat has: fall back to the global color. +void main() { + testWidgets( + 'the chat dialog hands back the picked color, and null for global', + (tester) async { + final calls = []; + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showDialog( + context: context, + builder: (context) => DialogUtils.chatThemeDialog( + context, + current: Colors.blue, + onChanged: (color) async => calls.add(color), + )), + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const ValueKey('themeSwatch-8'))); + await tester.pumpAndSettle(); + expect(calls.last?.toARGB32(), Colors.teal.toARGB32()); + + // The inherit tile is the chat dialog's own choice: the app theme dialog + // has no such tile. + await tester.tap(find.byKey(const ValueKey('themeSwatch-global'))); + await tester.pumpAndSettle(); + expect(calls.last, isNull); + }); + + testWidgets('a swatch repaints the sample before the dialog is confirmed', + (tester) async { + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => DialogUtils.chatThemeDialog( + context, + current: null, + onChanged: (_) async {}, + )), + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + // Nothing picked yet: the sample follows the global theme. + expect(tester.widget(find.byType(ThemePreview)).seed, isNull); + + final swatch = find.byKey(const ValueKey('themeSwatch-8')); + await tester.ensureVisible(swatch); + await tester.pumpAndSettle(); + await tester.tap(swatch); + await tester.pumpAndSettle(); + + // A rebuild used to reset the pick to the value the page had on open, so + // the preview only moved once the dialog was confirmed. + expect( + tester.widget(find.byType(ThemePreview)).seed?.toARGB32(), + Colors.teal.toARGB32()); + }); +} diff --git a/test/chat_theme_test.dart b/test/chat_theme_test.dart new file mode 100644 index 0000000..43682c6 --- /dev/null +++ b/test/chat_theme_test.dart @@ -0,0 +1,33 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/utils/cache_utils.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_chat_theme_test'); + Hive.init(dir.path); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('per-chat theme is stored, read and cleared', () async { + expect(await CacheUtils.getChatTheme('7'), isNull); + + await CacheUtils.setChatTheme('7', const Color(0xFF3366CC)); + expect(await CacheUtils.getChatTheme('7'), const Color(0xFF3366CC)); + + // Another chat is not affected + expect(await CacheUtils.getChatTheme('8'), isNull); + + await CacheUtils.clearChatTheme('7'); + expect(await CacheUtils.getChatTheme('7'), isNull); + }); +} diff --git a/test/conversation_meta_test.dart b/test/conversation_meta_test.dart new file mode 100644 index 0000000..a336afe --- /dev/null +++ b/test/conversation_meta_test.dart @@ -0,0 +1,100 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; + +PrivateMessage message(String senderId, DateTime sentAt, {bool read = false}) { + return PrivateMessage(senderId, 'text', sentAt, sentAt, read); +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_conversation_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + for (final name in ['privateMessages', 'conversations', 'user']) { + await Hive.openBox(name); + await Hive.box(name).clear(); + } + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('unread counts only incoming unread messages', () async { + final base = DateTime(2026, 5, 1, 12); + await CacheUtils.addPrivateMessages('peer', [ + message('peer', base), + message('peer', base.add(const Duration(minutes: 1))), + message('peer', base.add(const Duration(minutes: 2)), read: true), + message('me', base.add(const Duration(minutes: 3)), read: true), + ]); + + final counts = await CacheUtils.getUnreadCounts(); + expect(counts['peer'], 2); + expect(await CacheUtils.firstUnreadSentAt('peer'), base); + }); + + test('a read conversation has no anchor', () async { + await CacheUtils.addPrivateMessages( + 'peer', [message('peer', DateTime(2026, 5, 1), read: true)]); + expect(await CacheUtils.firstUnreadSentAt('peer'), isNull); + }); + + test('pin and unpin keep the box clean', () async { + expect(await CacheUtils.isConversationPinned('peer'), isFalse); + + await CacheUtils.setConversationPinned('peer', true); + expect(await CacheUtils.isConversationPinned('peer'), isTrue); + expect(await CacheUtils.getPinnedConversations(), {'peer'}); + + await CacheUtils.setConversationPinned('peer', false); + expect(await CacheUtils.isConversationPinned('peer'), isFalse); + expect(await CacheUtils.getPinnedConversations(), isEmpty); + // Unpinning removes the entry instead of storing a false flag. + expect(Hive.box('conversations').containsKey('peer'), isFalse); + }); + + test('pinned conversations sort before newer ones', () async { + final base = DateTime(2026, 5, 1, 12); + await CacheUtils.addPrivateMessages('old', [message('old', base)]); + await CacheUtils.addPrivateMessages('new', [ + message('new', base.add(const Duration(hours: 1))), + ]); + + var chats = await CacheUtils.getLatestPrivateMessages(); + expect(chats.keys.first.id, 'new'); + + await CacheUtils.setConversationPinned('old', true); + chats = await CacheUtils.getLatestPrivateMessages(); + expect(chats.keys.first.id, 'old'); + }); + + test('deleting a chat drops its pin', () async { + await CacheUtils.addPrivateMessages( + 'peer', [message('peer', DateTime(2026, 5, 1))]); + await CacheUtils.setConversationPinned('peer', true); + + await CacheUtils.deletePrivateMessagesWithUser('peer'); + + expect(await CacheUtils.getPinnedConversations(), isEmpty); + }); + + test('the chat list gets cursors only from chats with receipts on', () async { + final readAt = DateTime(2026, 5, 1, 12, 0, 0, 123, 456); + await CacheUtils.setPeerReadAt('on', readAt); + await CacheUtils.setReadReceiptsEnabled('on', true); + await CacheUtils.setPeerReadAt('off', readAt); + + expect(await CacheUtils.peerReadAts(), {'on': readAt}); + }); +} diff --git a/test/crypto_test.dart b/test/crypto_test.dart index 87fe904..a4c0958 100644 --- a/test/crypto_test.dart +++ b/test/crypto_test.dart @@ -1,18 +1,43 @@ +import 'dart:convert'; + import 'package:basic_utils/basic_utils.dart' as bu; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter/foundation.dart'; -import 'package:whisper/utils/crypto_utils.dart'; +import 'package:shept/utils/crypto_utils.dart'; void main() async { test('generate RSA keypair asynchronously', () async { - var keyPair = await CryptoUtils.getRSAKeyPair(); - debugPrint('${bu.CryptoUtils.encodeRSAPublicKeyToPem(keyPair.publicKey as bu.RSAPublicKey)}\n'); - debugPrint('${bu.CryptoUtils.encodeRSAPrivateKeyToPem(keyPair.privateKey as bu.RSAPrivateKey)}\n'); + var keyPair = await CryptoUtils.getRSAKeyPair(); + debugPrint( + '${bu.CryptoUtils.encodeRSAPublicKeyToPem(keyPair.publicKey as bu.RSAPublicKey)}\n'); + debugPrint( + '${bu.CryptoUtils.encodeRSAPrivateKeyToPem(keyPair.privateKey as bu.RSAPrivateKey)}\n'); }); test('generate JWT token', () async { var keyPair = await CryptoUtils.getRSAKeyPair(); - final token = await CryptoUtils.generateRsaJwt(1, keyPair.privateKey as bu.RSAPrivateKey); + final token = await CryptoUtils.generateRsaJwt( + '1', keyPair.privateKey as bu.RSAPrivateKey, + nonce: 'test-challenge', deviceId: 'device'); debugPrint(token); }); + + test('the login token tolerates a server clock behind the phone', () async { + var keyPair = await CryptoUtils.getRSAKeyPair(); + final token = await CryptoUtils.generateRsaJwt( + '1', keyPair.privateKey as bu.RSAPrivateKey, + nonce: 'test-challenge', deviceId: 'device'); + + final payload = jsonDecode(utf8 + .decode(base64Url.decode(base64Url.normalize(token.split('.')[1])))) + as Map; + final notBefore = + DateTime.fromMillisecondsSinceEpoch((payload['nbf'] as int) * 1000); + // A token whose nbf is "now" is rejected by a server whose clock is a + // little behind; it must already be valid. + expect(notBefore.isBefore(DateTime.now()), isTrue); + expect( + notBefore.isAfter(DateTime.now().subtract(const Duration(minutes: 1))), + isTrue); + }); } diff --git a/test/date_format_test.dart b/test/date_format_test.dart index 0adc25f..aec57c5 100644 --- a/test/date_format_test.dart +++ b/test/date_format_test.dart @@ -17,4 +17,4 @@ void main() { // Friday debugPrint(DateFormat.EEEE().format(DateTime.now().toLocal())); }); -} \ No newline at end of file +} diff --git a/test/delete_message_test.dart b/test/delete_message_test.dart new file mode 100644 index 0000000..480e5a9 --- /dev/null +++ b/test/delete_message_test.dart @@ -0,0 +1,65 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; + +void main() { + late Directory dir; + late PrivateMessage keep; + late PrivateMessage drop; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_delete_message_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + keep = PrivateMessage( + '2', 'keep me', DateTime(2026, 1, 1), DateTime(2026, 1, 1), true); + drop = PrivateMessage( + '1', 'drop me', DateTime(2026, 1, 2), DateTime(2026, 1, 2), true); + await CacheUtils.addPrivateMessages('1', [keep, drop]); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('deletePrivateMessage removes only the matching message', () async { + await CacheUtils.deletePrivateMessage('1', drop); + + final messages = await CacheUtils.getPrivateMessages('1'); + expect(messages.length, 1); + expect(messages.single.message, 'keep me'); + // The other conversation is untouched + expect(await CacheUtils.getPrivateMessages('2'), isEmpty); + }); + + test('delete for everyone keeps a tombstone instead of a gap', () async { + final media = PrivateMessage( + '1', 'with a photo', DateTime(2026, 1, 3), DateTime(2026, 1, 3), false, + mediaTypeStr: 'image', localPath: dir.path, reactions: {'1': '👍'}); + await CacheUtils.addPrivateMessages('1', [media]); + + final at = DateTime(2026, 1, 4); + await CacheUtils.markMessageDeleted('1', media.sentAt, at); + + final messages = await CacheUtils.getPrivateMessages('1'); + final tombstone = + messages.firstWhere((message) => message.sentAt == media.sentAt); + expect(tombstone.isDeleted, isTrue); + expect(tombstone.deletedAt, at); + expect(tombstone.message, isEmpty); + expect(tombstone.isMedia, isFalse); + expect(tombstone.reactions, isNull); + // Nothing left to read, so it cannot raise a badge. + expect(tombstone.read, isTrue); + expect(messages.length, 3); + }); +} diff --git a/test/deleted_bubble_test.dart b/test/deleted_bubble_test.dart new file mode 100644 index 0000000..c795e3d --- /dev/null +++ b/test/deleted_bubble_test.dart @@ -0,0 +1,59 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/chat_bubble.dart'; +import 'package:shept/widgets/media_bubble.dart'; + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('a deleted message keeps its place as a tombstone', ( + tester, + ) async { + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: const Locale('en'), + home: Scaffold( + body: Center( + child: ChatBubble( + null, + PrivateMessage('2', '', DateTime(2026), DateTime(2026), true) + ..deletedAt = DateTime(2026) + ..mediaTypeStr = 'image', + null, + peer, + accentColor: Colors.blue, + ), + ), + ), + ); + }), + )); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + + expect(find.text('Message deleted'), findsOneWidget); + // The attachment is gone with the content. + expect(find.byType(MediaBubble), findsNothing); + }); +} diff --git a/test/device_and_sync_test.dart b/test/device_and_sync_test.dart new file mode 100644 index 0000000..069edb8 --- /dev/null +++ b/test/device_and_sync_test.dart @@ -0,0 +1,68 @@ +import 'dart:io'; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/utils/cache_utils.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_device_sync_test'); + Hive.init(dir.path); + // The device id lives in secure storage, which a unit test has to fake. + final secureStorage = {}; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.it_nomads.com/flutter_secure_storage'), + (call) async { + final args = (call.arguments as Map?) ?? const {}; + switch (call.method) { + case 'read': + return secureStorage[args['key']]; + case 'write': + secureStorage[args['key'] as String] = args['value'] as String; + return null; + case 'delete': + secureStorage.remove(args['key']); + return null; + } + return null; + }, + ); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('the device id is created once and reused', () async { + final first = await CacheUtils.getOrCreateDeviceId(); + expect(first, isNotEmpty); + // A second login must reuse it, otherwise a revocation cannot target it. + expect(await CacheUtils.getOrCreateDeviceId(), first); + }); + + test('the device label is a readable platform name', () { + expect(CacheUtils.deviceLabel, isNotEmpty); + expect(CacheUtils.devicePlatform, Platform.operatingSystem); + }); + + test('the archive cursor starts at zero and never moves backwards', () async { + expect(await CacheUtils.getSyncSeq(), 0); + + await CacheUtils.setSyncSeq(10); + expect(await CacheUtils.getSyncSeq(), 10); + + // Two overlapping sync answers may arrive out of order; the stale one must + // not rewind the cursor, or the same messages would be fetched again. + await CacheUtils.setSyncSeq(4); + expect(await CacheUtils.getSyncSeq(), 10); + + await CacheUtils.setSyncSeq(12); + expect(await CacheUtils.getSyncSeq(), 12); + }); +} diff --git a/test/disappearing_test.dart b/test/disappearing_test.dart new file mode 100644 index 0000000..6b088fa --- /dev/null +++ b/test/disappearing_test.dart @@ -0,0 +1,97 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/disappearing.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/message_actions.dart'; +import 'package:shept/utils/text_envelope.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +PrivateMessage message(String senderId, DateTime sentAt, + {DateTime? expiresAt, bool viewOnce = false}) { + return PrivateMessage(senderId, 'text', sentAt, sentAt, true, + expiresAt: expiresAt, viewOnce: viewOnce); +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_disappearing_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('a control message carries its state and timer both ways', () { + final parsed = + tryParseSystemEnvelope(buildSystemEnvelope('propose', 86400))!; + expect(parsed.state, 'propose'); + expect(parsed.seconds, 86400); + + // Anything that is not a control message stays text. + expect( + tryParseSystemEnvelope(Uint8List.fromList(utf8.encode('hi'))), isNull); + expect( + tryParseSystemEnvelope(Uint8List.fromList( + utf8.encode(jsonEncode({'kind': 'system', 'state': 'nope'})))), + isNull); + }); + + test('a view-once flag rides inside the media envelope', () { + final reference = MediaReference( + 'media-id', Uint8List.fromList([1, 2, 3]), MediaType.image, 3); + final parsed = MediaUtils.tryParseMediaEnvelope( + MediaUtils.buildMediaEnvelope(reference, '', viewOnce: true))!; + expect(parsed.viewOnce, isTrue); + final plain = MediaUtils.tryParseMediaEnvelope( + MediaUtils.buildMediaEnvelope(reference, ''))!; + expect(plain.viewOnce, isFalse); + }); + + // The sweep is what actually removes a disappearing message on this device. + test('the sweep drops expired rows and keeps the rest', () async { + final now = DateTime.now(); + await CacheUtils.addPrivateMessages('peer', [ + message('peer', now.subtract(const Duration(hours: 2)), + expiresAt: now.subtract(const Duration(hours: 1))), + message('peer', now.subtract(const Duration(minutes: 1)), + expiresAt: now.add(const Duration(hours: 1))), + message('peer', now), + ]); + + expect(await CacheUtils.purgeExpiredMessages(), 1); + final left = await CacheUtils.getPrivateMessages('peer'); + expect(left.length, 2); + }); + + test('a view-once attachment may not be forwarded', () { + final now = DateTime.now(); + expect(MessageActions.canForward(message('peer', now, viewOnce: true)), + isFalse); + expect(MessageActions.canForward(message('peer', now)), isTrue); + }); + + test('timers are labelled in their own unit', () { + // No localization is initialised here, so only the numeric labels are + // asserted; "off" is a translated word. + expect(disappearingLabel(3600), '1 h'); + expect(disappearingLabel(86400), '1 d'); + expect(disappearingLabel(604800), '7 d'); + }); +} diff --git a/test/edit_dialog_test.dart b/test/edit_dialog_test.dart new file mode 100644 index 0000000..c809d88 --- /dev/null +++ b/test/edit_dialog_test.dart @@ -0,0 +1,67 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/message_actions.dart'; +import 'package:shept/utils/singleton.dart'; + +/// Closing the edit dialog used to dispose its controller while the route was +/// still animating out; that trips `InheritedElement.debugDeactivated` on a +/// device (red screen after a successful edit). The dialog now owns its +/// controller, and this test locks the close path in. +void main() { + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('the edit dialog opens and closes without a framework assert', + (tester) async { + final message = + PrivateMessage('1', 'hello', DateTime(2026), DateTime(2026), true) + ..id = '00000000-0000-4000-8000-000000000000'; + + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: Builder(builder: (inner) { + return ElevatedButton( + onPressed: () => MessageActions.edit(inner, message, '5'), + child: const Text('edit'), + ); + }), + ), + ), + ); + }), + )); + await tester.pumpAndSettle(); + + await tester.tap(find.text('edit')); + await tester.pumpAndSettle(); + expect(find.text('Edit message'), findsOneWidget); + + // Typing then cancelling is the same teardown path as confirming. + await tester.enterText(find.byType(TextField), 'hello again'); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text('Edit message'), findsNothing); + }); +} diff --git a/test/file_media_test.dart b/test/file_media_test.dart new file mode 100644 index 0000000..840f32e --- /dev/null +++ b/test/file_media_test.dart @@ -0,0 +1,155 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/message_notifier.dart'; +import 'package:shept/widgets/media_bubble.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +PrivateMessage media(String type, String? path, DateTime sentAt, + {String? fileName, int size = 1024}) { + return PrivateMessage('1', '', sentAt, sentAt, false, + mediaTypeStr: type, + localPath: path, + mediaSize: size, + fileName: fileName, + downloadStatus: MediaDownloadStatus.ready); +} + +void main() { + group('detectType', () { + test('documents become files', () { + expect(MediaUtils.detectType('/tmp/invoice.pdf'), MediaType.file); + expect(MediaUtils.detectType('/tmp/archive.zip'), MediaType.file); + }); + + test('known media keeps its own type', () { + expect(MediaUtils.detectType('/tmp/photo.png'), MediaType.image); + expect(MediaUtils.detectType('/tmp/anim.gif'), MediaType.gif); + expect(MediaUtils.detectType('/tmp/clip.mp4'), MediaType.video); + expect(MediaUtils.detectType('/tmp/song.mp3'), MediaType.voice); + }); + }); + + test('baseName keeps the name with its extension', () { + expect( + MediaUtils.baseName('/data/user/0/files/invoice.pdf'), 'invoice.pdf'); + expect(MediaUtils.baseName('no-slash.txt'), 'no-slash.txt'); + }); + + test('documents get an icon per type', () { + expect(MediaUtils.iconForFileName('invoice.pdf'), Icons.picture_as_pdf); + expect(MediaUtils.iconForFileName('report.docx'), Icons.description); + expect(MediaUtils.iconForFileName('budget.xlsx'), Icons.table_chart); + expect(MediaUtils.iconForFileName('slides.pptx'), Icons.slideshow); + expect(MediaUtils.iconForFileName('pack.zip'), Icons.folder_zip); + expect(MediaUtils.iconForFileName('notes.txt'), Icons.article); + expect(MediaUtils.iconForFileName('blob'), Icons.insert_drive_file); + expect(MediaUtils.iconForFileName(null), Icons.insert_drive_file); + }); + + test('sizes are formatted for the bubble', () { + expect(MediaUtils.formatBytes(512), '512 B'); + expect(MediaUtils.formatBytes(2048), '2.0 KB'); + expect(MediaUtils.formatBytes(3 * 1024 * 1024), '3.0 MB'); + }); + + test('a document without a caption previews its name', () { + final message = media('file', '/tmp/invoice.pdf', DateTime(2026, 11, 13), + fileName: 'invoice.pdf'); + expect(message.preview, 'invoice.pdf'); + expect(message.mediaType, MediaType.file); + }); + + test('shared media keeps documents, still drops voice', () { + final now = DateTime(2026, 11, 13, 12); + final viewable = MessageNotifier.viewableMedia([ + media('file', '/tmp/a.pdf', now, fileName: 'a.pdf'), + media('voice', '/tmp/b.m4a', now.subtract(const Duration(minutes: 1))), + ]); + expect(viewable.map((m) => m.fileName), ['a.pdf']); + }); + + test('the file name survives a Hive round trip', () async { + final dir = Directory.systemTemp.createTempSync('shept_file_media_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + + final message = + media('file', null, DateTime(2026, 11, 13), fileName: 'a.pdf'); + message.mediaId = 'media-1'; + await CacheUtils.addPrivateMessages('7', [message]); + final stored = await CacheUtils.getPrivateMessages('7'); + + expect(stored.single.fileName, 'a.pdf'); + expect(stored.single.mediaTypeStr, 'file'); + + // A finished download replaces the encrypted size with the real one + await CacheUtils.updatePrivateMessageMedia('7', stored.single.mediaId!, + downloadStatus: MediaDownloadStatus.ready, mediaSize: 4096); + final updated = await CacheUtils.getPrivateMessages('7'); + expect(updated.single.mediaSize, 4096); + + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + testWidgets('the document bubble shows the name and the size', + (tester) async { + final message = media('file', '/tmp/invoice.pdf', DateTime(2026, 11, 13), + fileName: 'invoice.pdf', size: 2048); + + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: MediaBubble( + message: message, + bubbleColor: Colors.blue, + textColor: Colors.white, + onRetry: () {}, + canRetry: false, + conversationUserId: '1', + ), + ), + )); + await tester.pump(); + + expect(find.text('invoice.pdf'), findsOneWidget); + expect(find.text('2.0 KB'), findsOneWidget); + expect(find.byIcon(Icons.picture_as_pdf), findsOneWidget); + }); + + testWidgets('pending voice and file bubbles are not square', (tester) async { + PrivateMessage pending(String type, {String? fileName}) => PrivateMessage( + '1', '', DateTime(2026, 11, 13), DateTime(2026, 11, 13), false, + mediaTypeStr: type, + mediaSize: 2048, + fileName: fileName, + downloadStatus: MediaDownloadStatus.pending); + + Widget bubble(PrivateMessage message) => MaterialApp( + home: Scaffold( + body: MediaBubble( + message: message, + bubbleColor: Colors.blue, + textColor: Colors.white, + onRetry: () {}, + canRetry: false, + conversationUserId: '1', + ), + ), + ); + + await tester.pumpWidget(bubble(pending('voice'))); + expect(tester.getSize(find.byType(MediaBubble)), const Size(236, 56)); + + await tester.pumpWidget(bubble(pending('file', fileName: 'invoice.pdf'))); + expect(find.text('invoice.pdf'), findsOneWidget); + final fileSize = tester.getSize(find.byType(MediaBubble)); + expect(fileSize.width, greaterThan(fileSize.height)); + expect(fileSize.height, lessThan(100)); + }); +} diff --git a/test/link_utils_test.dart b/test/link_utils_test.dart new file mode 100644 index 0000000..0304bf0 --- /dev/null +++ b/test/link_utils_test.dart @@ -0,0 +1,35 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/link_utils.dart'; + +void main() { + test('text without a link stays plain', () { + final parts = splitLinks('ahoj, jak je?'); + expect(parts, [(text: 'ahoj, jak je?', url: null)]); + }); + + test('a link in the middle is split out', () { + final parts = splitLinks('mrkni na https://example.com/a?b=1 a dej vědět'); + expect(parts.map((p) => p.url), [null, 'https://example.com/a?b=1', null]); + expect(parts.first.text, 'mrkni na '); + expect(parts.last.text, ' a dej vědět'); + }); + + test('a sentence-final dot is not part of the link', () { + final parts = splitLinks('viz https://example.com.'); + final link = parts.firstWhere((p) => p.url != null); + expect(link.url, 'https://example.com'); + expect(parts.last, (text: '.', url: null)); + }); + + test('several links and http scheme are handled', () { + final parts = splitLinks('http://a.cz a https://b.cz/x'); + expect(parts.where((p) => p.url != null).map((p) => p.url), + ['http://a.cz', 'https://b.cz/x']); + }); + + test('text starting with a link produces no empty plain piece', () { + final parts = splitLinks('https://example.com'); + expect(parts, hasLength(1)); + expect(parts.single.url, 'https://example.com'); + }); +} diff --git a/test/live_location_bubble_test.dart b/test/live_location_bubble_test.dart new file mode 100644 index 0000000..f5b7c86 --- /dev/null +++ b/test/live_location_bubble_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/live_location.dart'; +import 'package:shept/utils/presence.dart'; +import 'package:shept/widgets/live_location_bubble.dart'; + +void main() { + final peer = User('2', 'peer', '', false); + final presence = PresenceNotifier.instance; + + setUp(presence.clear); + tearDown(presence.clear); + + testWidgets('no session means no bubble', (tester) async { + await tester.pumpWidget( + MaterialApp(home: Scaffold(body: LiveLocationBubble(peer)))); + expect(find.byType(InkWell), findsNothing); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('the peer sharing location shows one bubble with time left', ( + tester, + ) async { + presence.applyLiveLocation( + peer.id, + LiveLocationPoint(50.08, 14.42, + until: DateTime.now().add(const Duration(minutes: 5))), + ); + await tester.pumpWidget( + MaterialApp(home: Scaffold(body: LiveLocationBubble(peer)))); + await tester.pump(); + + expect(find.textContaining('liveLocationTheirs'), findsOneWidget); + expect(find.byType(InkWell), findsOneWidget); + + // Unmount and drop the session: both own timers. + await tester.pumpWidget(const SizedBox()); + presence.clear(); + }); +} diff --git a/test/location_test.dart b/test/location_test.dart new file mode 100644 index 0000000..b76f09f --- /dev/null +++ b/test/location_test.dart @@ -0,0 +1,62 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/live_location.dart'; +import 'package:shept/utils/text_envelope.dart'; + +void main() { + // A location is a text message with one optional key, so an older client + // still shows the coordinates instead of raw JSON. + test('a location survives the text envelope and keeps a text fallback', () { + const location = LocationRef(50.087, 14.421, accuracy: 12, label: 'Praha'); + final parsed = tryParseTextEnvelope( + buildTextEnvelope(location.body, null, location: location))!; + + expect(parsed.body, '📍 50.08700, 14.42100'); + expect(parsed.location!.lat, 50.087); + expect(parsed.location!.lng, 14.421); + expect(parsed.location!.label, 'Praha'); + expect(parsed.location!.accuracy, 12); + }); + + test('a plain text envelope has no location', () { + final parsed = tryParseTextEnvelope(buildTextEnvelope('hello', null))!; + expect(parsed.location, isNull); + }); + + // The relayed position is one string the server cannot read; only the parts + // have to survive the base64 round trip. + test('an encrypted payload round-trips through the frame', () { + final parts = { + 'encryptedData': Uint8List.fromList([1, 2, 3]), + 'encryptedKey': Uint8List.fromList([4, 5]), + 'nonce': Uint8List.fromList([6]), + 'mac': Uint8List.fromList([7, 8]), + }; + final decoded = decodeEncryptedPayload(encodeEncryptedPayload(parts))!; + expect(decoded['encryptedData'], [1, 2, 3]); + expect(decoded['encryptedKey'], [4, 5]); + expect(decoded['nonce'], [6]); + expect(decoded['mac'], [7, 8]); + }); + + test('a malformed payload is dropped, not thrown', () { + expect(decodeEncryptedPayload('not base64!'), isNull); + expect( + decodeEncryptedPayload( + base64Encode(utf8.encode(jsonEncode({'data': 1})))), + isNull); + }); + + test('a position carries its deadline', () { + final point = LiveLocationPoint(1.5, 2.5, + accuracy: 3, until: DateTime.utc(2026, 11, 21, 12)); + final parsed = + LiveLocationPoint.fromJson(Map.from(point.toJson())); + expect(parsed.lat, 1.5); + expect(parsed.lng, 2.5); + expect(parsed.accuracy, 3); + expect(parsed.until, DateTime.utc(2026, 11, 21, 12)); + }); +} diff --git a/test/media_album_test.dart b/test/media_album_test.dart new file mode 100644 index 0000000..17eb1f6 --- /dev/null +++ b/test/media_album_test.dart @@ -0,0 +1,215 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/message_notifier.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +MediaReference _reference(String id, {MediaType type = MediaType.image}) => + MediaReference( + id, + Uint8List.fromList(List.generate(32, (i) => i)), + type, + 1024, + width: 800, + height: 600, + fileName: 'photo.jpg', + ); + +void main() { + group('media envelope', () { + test('single media keeps the v1 envelope', () { + final envelope = MediaUtils.buildMediaEnvelope(_reference('m1'), 'hi'); + final parsed = MediaUtils.tryParseMediaEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.references.single.mediaId, 'm1'); + expect(parsed.caption, 'hi'); + }); + + test('album round trips every reference in order', () { + final envelope = MediaUtils.buildAlbumEnvelope( + [_reference('a'), _reference('b'), _reference('c')], + 'album caption', + ); + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['sheptMsg'], MediaUtils.envelopeVersionAlbum); + + final parsed = MediaUtils.tryParseMediaEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.references.map((r) => r.mediaId), ['a', 'b', 'c']); + expect(parsed.caption, 'album caption'); + }); + + test('an album can be a single view', () { + final envelope = MediaUtils.buildAlbumEnvelope( + [_reference('a'), _reference('b')], + '', + viewOnce: true, + ); + final parsed = MediaUtils.tryParseMediaEnvelope(envelope); + expect(parsed!.viewOnce, isTrue); + expect(parsed.references.length, 2); + }); + + test('plain text is not an envelope', () { + final parsed = MediaUtils.tryParseMediaEnvelope( + Uint8List.fromList(utf8.encode('just text'))); + expect(parsed, isNull); + }); + + test('an unknown envelope version is not parsed', () { + final parsed = MediaUtils.tryParseMediaEnvelope(Uint8List.fromList( + utf8.encode('{"sheptMsg":99,"kind":"media","media":[]}'))); + expect(parsed, isNull); + }); + }); + + group('upload limit', () { + test('accounts for the transport overhead', () { + expect(MediaUtils.uploadFits(MediaUtils.maxUploadBytes), isFalse); + expect( + MediaUtils.uploadFits( + MediaUtils.maxUploadBytes - MediaUtils.transportOverheadBytes), + isTrue); + expect( + MediaUtils.uploadFits(MediaUtils.maxUploadBytes - + MediaUtils.transportOverheadBytes + + 1), + isFalse); + }); + }); + + group('album items', () { + test('serialize and deserialize', () { + final message = + PrivateMessage('1', 'cap', DateTime(2026), DateTime(2026), true); + message.setAlbum([ + AlbumItem( + mediaId: 'a', + type: MediaType.image.name, + size: 10, + width: 100, + height: 50, + fileName: 'a.jpg', + localPath: '/tmp/a', + ), + AlbumItem( + mediaId: 'b', + type: MediaType.video.name, + size: 20, + durationMs: 1500, + status: MediaDownloadStatus.pending, + ), + ]); + + expect(message.isAlbum, isTrue); + expect(message.isMedia, isTrue); + expect(message.mediaType, isNull); + final items = message.album; + expect(items.length, 2); + expect(items.first.isReady, isTrue); + expect(items.first.fileName, 'a.jpg'); + expect(items.last.isReady, isFalse); + expect(items.last.durationMs, 1500); + expect(message.localPaths, ['/tmp/a']); + }); + + test('expands into one entry per attachment for the viewer', () { + final message = + PrivateMessage('1', 'cap', DateTime(2026), DateTime(2026), true); + message.setAlbum([ + AlbumItem( + mediaId: 'a', + type: MediaType.image.name, + size: 1, + localPath: '/tmp/a'), + AlbumItem( + mediaId: 'b', + type: MediaType.image.name, + size: 1, + localPath: '/tmp/b'), + ]); + + final expanded = MessageNotifier.albumMedia(message); + expect(expanded.map((m) => m.mediaId), ['a', 'b']); + expect(expanded.every((m) => m.localPath != null), isTrue); + expect(MessageNotifier.viewableMedia([message]).length, 2); + }); + }); + + group('cache', () { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_album_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDown(() async { + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('updating one album attachment keeps the others untouched', () async { + final message = PrivateMessage( + '1', 'cap', DateTime(2026, 1, 1), DateTime(2026, 1, 1), true, + downloadStatus: MediaDownloadStatus.pending); + message.setAlbum([ + AlbumItem( + mediaId: 'a', + type: MediaType.image.name, + size: 1, + status: MediaDownloadStatus.pending), + AlbumItem( + mediaId: 'b', + type: MediaType.image.name, + size: 1, + status: MediaDownloadStatus.pending), + ]); + await CacheUtils.addPrivateMessages('1', [message]); + + await CacheUtils.updatePrivateMessageMedia('1', 'b', + localPath: '/tmp/b', downloadStatus: MediaDownloadStatus.ready); + + final stored = (await CacheUtils.getPrivateMessages('1')).single; + final items = stored.album; + expect(items[0].status, MediaDownloadStatus.pending); + expect(items[0].localPath, isNull); + expect(items[1].status, MediaDownloadStatus.ready); + expect(items[1].localPath, '/tmp/b'); + // Not everything is ready yet, so the message stays pending. + expect(stored.downloadStatus, MediaDownloadStatus.pending); + + await CacheUtils.updatePrivateMessageMedia('1', 'a', + localPath: '/tmp/a', downloadStatus: MediaDownloadStatus.ready); + final done = (await CacheUtils.getPrivateMessages('1')).single; + expect(done.downloadStatus, MediaDownloadStatus.ready); + }); + + test('send status is stored on the message', () async { + final message = PrivateMessage( + '1', 'hi', DateTime(2026, 2, 1), DateTime(2026, 2, 1), true, + sendStatus: SendStatus.sending); + await CacheUtils.addPrivateMessages('1', [message]); + await CacheUtils.updateStoredMessage('1', message, (stored) { + stored.sendStatus = SendStatus.sent; + }); + final stored = (await CacheUtils.getPrivateMessages('1')).single; + expect(stored.sendStatus, SendStatus.sent); + await CacheUtils.deletePrivateMessagesWithUser('1'); + }); + }); +} diff --git a/test/media_autoplay_test.dart b/test/media_autoplay_test.dart new file mode 100644 index 0000000..c1d8eac --- /dev/null +++ b/test/media_autoplay_test.dart @@ -0,0 +1,166 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/media_autoplay.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_media_autoplay_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + // isMe compares against the signed-in user. + Singleton().profile = + Profile('', User('me', 'me', '', false), '', '', '', '', false); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + MediaAutoplay.request.value = null; + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + PrivateMessage voice(DateTime sentAt, + {String? path = '/tmp/voice', String sender = 'peer'}) => + PrivateMessage(sender, '', sentAt, sentAt, true, + mediaTypeStr: 'voice', localPath: path, durationMs: 1000); + + PrivateMessage note(DateTime sentAt, + {String? path = '/tmp/note', String sender = 'peer'}) => + PrivateMessage(sender, '', sentAt, sentAt, true, + mediaTypeStr: 'video', + localPath: path, + durationMs: 1000, + mediaRefJson: '{"videoNote":true}'); + + test('the next voice message in the chat is requested', () async { + final first = DateTime(2026, 1, 1, 10); + final second = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [voice(first), voice(second)]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a text message between two voice messages is skipped', () async { + final first = DateTime(2026, 1, 1, 10); + final text = DateTime(2026, 1, 1, 10, 1); + final second = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + PrivateMessage('1', 'hello', text, text, true), + voice(second), + ]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a voice message without a local copy is skipped and the end stops', + () async { + final first = DateTime(2026, 1, 1, 10); + final missing = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + voice(missing, path: null), + ]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); + + test('playback stops instead of playing our own voice message', () async { + final first = DateTime(2026, 1, 1, 10); + final mine = DateTime(2026, 1, 1, 10, 1); + final later = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + voice(first), + voice(mine, sender: 'me'), + voice(later), + ]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); + + test('the next round note in the chat is requested', () async { + final first = DateTime(2026, 1, 1, 10); + final second = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [note(first), note(second)]); + + await MediaAutoplay.nextRoundNote('1', first); + + expect(MediaAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a plain video between two round notes is skipped', () async { + final first = DateTime(2026, 1, 1, 10); + final plain = DateTime(2026, 1, 1, 10, 1); + final second = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + note(first), + PrivateMessage('peer', '', plain, plain, true, + mediaTypeStr: 'video', localPath: '/tmp/video'), + note(second), + ]); + + await MediaAutoplay.nextRoundNote('1', first); + + expect(MediaAutoplay.request.value, CacheUtils.messageKey('1', second)); + }); + + test('a round note without a local copy is skipped and the end stops', + () async { + final first = DateTime(2026, 1, 1, 10); + final missing = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [ + note(first), + note(missing, path: null), + ]); + + await MediaAutoplay.nextRoundNote('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); + + test('the round note chain stops at our own note', () async { + final first = DateTime(2026, 1, 1, 10); + final mine = DateTime(2026, 1, 1, 10, 1); + final later = DateTime(2026, 1, 1, 10, 2); + await CacheUtils.addPrivateMessages('1', [ + note(first), + note(mine, sender: 'me'), + note(later), + ]); + + await MediaAutoplay.nextRoundNote('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); + + test('the voice chain does not pick up a round note', () async { + final first = DateTime(2026, 1, 1, 10); + final round = DateTime(2026, 1, 1, 10, 1); + await CacheUtils.addPrivateMessages('1', [voice(first), note(round)]); + + await MediaAutoplay.next('1', first); + + expect(MediaAutoplay.request.value, isNull); + }); +} diff --git a/test/media_cache_test.dart b/test/media_cache_test.dart new file mode 100644 index 0000000..05b8e92 --- /dev/null +++ b/test/media_cache_test.dart @@ -0,0 +1,52 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/singleton.dart'; + +/// A chat list disposes the rows that leave the viewport, so a photo scrolling +/// back into view used to be decrypted again from disk: the spinner stayed up +/// for as long as the queue behind it. +void main() { + final key = List.generate(32, (i) => i + 1); + final plain = Uint8List.fromList(List.generate(2048, (i) => i % 251)); + late Directory dir; + + setUpAll(() { + dir = Directory.systemTemp.createTempSync('shept_media_cache_test'); + Singleton().boxCollectionKey = key; + }); + + tearDownAll(() async { + MediaUtils.clearDecryptCache(); + await dir.delete(recursive: true); + }); + + Future stored(String name) async { + final path = '${dir.path}/$name'; + await File(path).writeAsBytes(await MediaUtils.encryptWith(plain, key)); + return path; + } + + test('a decrypted attachment is served from memory the second time', + () async { + final path = await stored('one'); + expect(await MediaUtils.decryptAtRest(path), plain); + + // The file is gone, so only the cache can answer this one. + await File(path).delete(); + expect(await MediaUtils.decryptAtRest(path), plain); + }); + + test('clearing the cache sends the next read back to the file', () async { + final path = await stored('two'); + await MediaUtils.decryptAtRest(path); + + MediaUtils.clearDecryptCache(); + await File(path).delete(); + + await expectLater( + MediaUtils.decryptAtRest(path), throwsA(isA())); + }); +} diff --git a/test/media_guard_test.dart b/test/media_guard_test.dart new file mode 100644 index 0000000..8a0ee00 --- /dev/null +++ b/test/media_guard_test.dart @@ -0,0 +1,74 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +PrivateMessage media(DateTime sentAt, + {String? mediaId, String? localPath, String? albumItemPath}) { + final message = PrivateMessage('peer', '', sentAt, sentAt, true, + mediaId: mediaId, + mediaTypeStr: albumItemPath == null ? MediaType.image.name : null, + localPath: localPath); + if (albumItemPath != null) { + message.setAlbum([ + AlbumItem( + mediaId: mediaId!, + type: MediaType.image.name, + size: 1, + localPath: albumItemPath), + ]); + } + return message; +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_media_guard_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + final base = DateTime(2026, 6, 1, 12); + + test('a downloaded attachment counts as local', () async { + await CacheUtils.addPrivateMessages( + 'peer', [media(base, mediaId: 'm1', localPath: '/tmp/a.bin')]); + expect(await CacheUtils.hasMediaLocally('peer', 'm1'), isTrue); + }); + + test('a placeholder waiting for download does not', () async { + await CacheUtils.addPrivateMessages('peer', [media(base, mediaId: 'm2')]); + expect(await CacheUtils.hasMediaLocally('peer', 'm2'), isFalse); + }); + + test('an album item counts when it has a local file', () async { + await CacheUtils.addPrivateMessages( + 'peer', [media(base, mediaId: 'm3', albumItemPath: '/tmp/a.bin')]); + expect(await CacheUtils.hasMediaLocally('peer', 'm3'), isTrue); + }); + + test('another conversation does not count', () async { + await CacheUtils.addPrivateMessages( + 'peer', [media(base, mediaId: 'm4', localPath: '/tmp/a.bin')]); + expect(await CacheUtils.hasMediaLocally('other', 'm4'), isFalse); + }); + + test('an empty store reports nothing local', () async { + expect(await CacheUtils.hasMediaLocally('peer', 'nope'), isFalse); + }); +} diff --git a/test/media_rekey_test.dart b/test/media_rekey_test.dart new file mode 100644 index 0000000..7ac704c --- /dev/null +++ b/test/media_rekey_test.dart @@ -0,0 +1,20 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/media_utils.dart'; + +void main() { + test('re-encrypted media only decrypts with the new key', () async { + final plain = Uint8List.fromList(List.generate(256, (i) => i % 251)); + final oldKey = List.filled(32, 1); + final newKey = List.filled(32, 2); + + final blob = await MediaUtils.encryptWith(plain, oldKey); + final reencrypted = await MediaUtils.encryptWith( + await MediaUtils.decryptWith(blob, oldKey), newKey); + + expect(await MediaUtils.decryptWith(reencrypted, newKey), plain); + await expectLater( + MediaUtils.decryptWith(reencrypted, oldKey), throwsA(anything)); + }); +} diff --git a/test/media_upload_test.dart b/test/media_upload_test.dart new file mode 100644 index 0000000..10acda8 --- /dev/null +++ b/test/media_upload_test.dart @@ -0,0 +1,34 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/media_utils.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + // A resumed upload appends to the bytes the server already holds, so it must + // rebuild the exact same ciphertext from the recorded key and nonce. + test('re-encrypting with the recorded key and nonce reproduces the blob', + () async { + final bytes = Uint8List.fromList(List.generate(5000, (i) => i % 251)); + + final first = await MediaUtils.encryptForTransport(bytes); + final resumed = await MediaUtils.encryptForTransport(bytes, + key: first.key, nonce: first.nonce); + + expect(resumed.blob, equals(first.blob)); + expect(resumed.nonce, equals(first.nonce)); + expect(await MediaUtils.decryptTransport(resumed.blob, resumed.key), + equals(bytes)); + }); + + test('a fresh upload encrypts with its own key', () async { + final bytes = Uint8List.fromList(List.generate(5000, (i) => i % 251)); + + final first = await MediaUtils.encryptForTransport(bytes); + final second = await MediaUtils.encryptForTransport(bytes); + + expect(second.key, isNot(equals(first.key))); + expect(second.blob, isNot(equals(first.blob))); + }); +} diff --git a/test/message_actions_test.dart b/test/message_actions_test.dart new file mode 100644 index 0000000..7c1e185 --- /dev/null +++ b/test/message_actions_test.dart @@ -0,0 +1,137 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/message_actions.dart'; +import 'package:shept/utils/singleton.dart'; + +void main() { + setUpAll(() async { + // easy_localization reads the locale from shared_preferences + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + // isMe compares against the signed-in user, needed by the resend action. + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('the sheet offers only the actions that apply', (tester) async { + // Swapped between the two steps; the app is built once so the localization + // asset is loaded only once. + var message = + PrivateMessage('2', 'hello', DateTime(2026), DateTime(2026), true); + + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Builder(builder: (inner) { + return Scaffold( + body: Center( + child: ElevatedButton( + onPressed: () => + MessageActions.showSheet(inner, message, '5'), + child: const Text('open'), + ), + ), + ); + }), + ); + }), + )); + await tester.pumpAndSettle(); + + // Text message: copy, forward, delete. Nothing to save. + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Forward'), findsOneWidget); + expect(find.text('Delete for me'), findsOneWidget); + expect(find.text('Save attachment'), findsNothing); + expect(find.text('Share to another app'), findsOneWidget); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + // Attachment on disk without a caption: save, forward, delete, no copy. + message = PrivateMessage('2', '', DateTime(2026), DateTime(2026), true, + localPath: '/tmp/shept_media_test', mediaTypeStr: 'image'); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Save attachment'), findsOneWidget); + expect(find.text('Forward'), findsOneWidget); + expect(find.text('Delete for me'), findsOneWidget); + expect(find.text('Copy'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + // Resend is offered only for my own message whose send failed. + message = PrivateMessage('1', 'hello', DateTime(2026), DateTime(2026), true, + sendStatus: SendStatus.failed); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Send again'), findsOneWidget); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + message = + PrivateMessage('1', 'hello', DateTime(2026), DateTime(2026), true); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Send again'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + // An archived message gains the reaction row and the pin entry; only an own + // text message can be edited. + message = PrivateMessage('2', 'hello', DateTime(2026), DateTime(2026), true) + ..id = '00000000-0000-4000-8000-000000000000'; + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('👍'), findsOneWidget); + expect(find.text('Pin'), findsOneWidget); + expect(find.text('Edit message'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + message = PrivateMessage('1', 'hello', DateTime(2026), DateTime(2026), true) + ..id = '00000000-0000-4000-8000-000000000000'; + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Edit message'), findsOneWidget); + expect(find.text('Unpin'), findsNothing); + + // Close the sheet + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + // An own attachment offers the caption edit too. + message = PrivateMessage( + '1', 'caption', DateTime(2026), DateTime(2026), true, + localPath: '/tmp/shept_media_test', mediaTypeStr: 'image') + ..id = '00000000-0000-4000-8000-000000000000'; + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + expect(find.text('Edit message'), findsOneWidget); + expect(find.text('Save attachment'), findsOneWidget); + }); +} diff --git a/test/message_format_test.dart b/test/message_format_test.dart new file mode 100644 index 0000000..389685c --- /dev/null +++ b/test/message_format_test.dart @@ -0,0 +1,125 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/message_format.dart'; + +/// Renders the parsed pieces back as text, so a test can assert on the whole +/// message without caring how the parser grouped it. +String flat(List pieces) => pieces.map((p) => p.text).join(); + +List styled(List pieces, MessageStyle style) => + pieces.where((p) => p.style == style).toList(); + +void main() { + group('inline styles', () { + test('bold, italic, strike and mono', () { + final pieces = parseMessage('a **b** *c* ~~d~~ `e` f'); + expect(flat(pieces), 'a b c d e f'); + expect(styled(pieces, MessageStyle.bold).single.text, 'b'); + expect(styled(pieces, MessageStyle.italic).single.text, 'c'); + expect(styled(pieces, MessageStyle.strike).single.text, 'd'); + expect(styled(pieces, MessageStyle.mono).single.text, 'e'); + }); + + test('bold wins over italic at the same position', () { + final pieces = parseMessage('**bold**'); + expect(pieces.single.style, MessageStyle.bold); + expect(pieces.single.text, 'bold'); + }); + + test('spoiler is its own style', () { + final pieces = parseMessage('there is ||a secret|| here'); + expect(styled(pieces, MessageStyle.spoiler).single.text, 'a secret'); + }); + + test('an unclosed marker stays literal', () { + expect(flat(parseMessage('**unclosed')), '**unclosed'); + expect(flat(parseMessage('a *b')), 'a *b'); + }); + + test('empty markers are literal', () { + expect(flat(parseMessage('****')), '****'); + }); + + test('fenced code block becomes one code piece', () { + final pieces = parseMessage('before\n```\ncode line\n```\nafter'); + final code = styled(pieces, MessageStyle.code).single; + expect(code.text, 'code line'); + expect(flat(pieces), 'before\ncode line\nafter'); + }); + + test('an unterminated fence runs to the end', () { + final pieces = parseMessage('x\n```\nstill code'); + expect(styled(pieces, MessageStyle.code).single.text, 'still code'); + }); + }); + + group('tappable entities', () { + test('links keep their address', () { + final pieces = parseMessage('see https://example.com/a now'); + final link = pieces.singleWhere((p) => p.kind == MessageKind.link); + expect(link.text, 'https://example.com/a'); + }); + + test('a phone number is detected', () { + final pieces = parseMessage('volej +420 123 456 789 díky'); + final phone = pieces.singleWhere((p) => p.kind == MessageKind.phone); + expect(phone.text, '+420 123 456 789'); + }); + + test('a short number is not a phone number', () { + final pieces = parseMessage('mám 3 kusy'); + expect(pieces.any((p) => p.kind == MessageKind.phone), isFalse); + }); + + test('an e-mail address is detected', () { + final pieces = parseMessage('napiš na jan.novak@example.com prosím'); + final email = pieces.singleWhere((p) => p.kind == MessageKind.email); + expect(email.text, 'jan.novak@example.com'); + }); + + test('an @ without a dotted domain is not an e-mail', () { + final pieces = parseMessage('jsem @doma'); + expect(pieces.any((p) => p.kind == MessageKind.email), isFalse); + }); + + test('a link beats an e-mail that starts at the same place', () { + final pieces = parseMessage('https://example.com/a'); + expect(pieces.single.kind, MessageKind.link); + }); + + test('formatting and links combine', () { + final pieces = parseMessage('**přečti** https://example.com'); + expect(styled(pieces, MessageStyle.bold).single.text, 'přečti'); + expect(pieces.singleWhere((p) => p.kind == MessageKind.link).text, + 'https://example.com'); + }); + }); + + group('emoji only', () { + test('a single emoji', () { + expect(isEmojiOnly('😀'), isTrue); + expect(emojiCount('😀'), 1); + }); + + test('a short emoji run', () { + expect(isEmojiOnly('😀🎉👍'), isTrue); + expect(emojiCount('😀🎉👍'), 3); + }); + + test('skin tone and variation selectors count as one emoji', () { + expect(isEmojiOnly('👍🏽'), isTrue); + expect(isEmojiOnly('❤️'), isTrue); + }); + + test('text with an emoji is not emoji only', () { + expect(isEmojiOnly('ahoj 😀'), isFalse); + }); + + test('digits alone are not an emoji', () { + expect(isEmojiOnly('123'), isFalse); + }); + + test('empty text is not an emoji', () { + expect(isEmojiOnly(''), isFalse); + }); + }); +} diff --git a/test/message_lifecycle_test.dart b/test/message_lifecycle_test.dart new file mode 100644 index 0000000..db7a30e --- /dev/null +++ b/test/message_lifecycle_test.dart @@ -0,0 +1,165 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +/// The local side of the lifecycle: an edit rewrites the stored text, a +/// reaction is a per-user map, a pin lives on the chat, and the mutation cursor +/// only moves forward. All four are what sync and live frames write into. +void main() { + late Directory dir; + const peer = 'peer-id'; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_lifecycle_test'); + Hive.init(dir.path); + if (!Hive.isAdapterRegistered(3)) { + Hive.registerAdapter(PrivateMessageAdapter()); + } + }); + + setUp(() async { + for (final box in ['privateMessages', 'conversations', 'settings']) { + await Hive.openBox(box); + await Hive.box(box).clear(); + } + final sentAt = DateTime(2026, 11, 19, 12); + await CacheUtils.addPrivateMessages(peer, [ + PrivateMessage(peer, 'before', sentAt, sentAt, true)..id = 'message-id', + ]); + }); + + tearDownAll(() async { + await Hive.deleteFromDisk(); + await dir.delete(recursive: true); + }); + + test('an edit replaces the text and marks the message', () async { + final editedAt = DateTime(2026, 11, 19, 12, 5); + await CacheUtils.markMessageEdited( + peer, DateTime(2026, 11, 19, 12), 'after', editedAt); + + final message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.message, 'after'); + expect(message.isEdited, isTrue); + expect(message.editedAt, editedAt); + }); + + test('a reaction is set per user, replaced and removed', () async { + final sentAt = DateTime(2026, 11, 19, 12); + await CacheUtils.setMessageReaction(peer, sentAt, 'me', '👍'); + await CacheUtils.setMessageReaction(peer, sentAt, 'peer-id', '❤️'); + + var message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.reactions, {'me': '👍', 'peer-id': '❤️'}); + expect(message.reactionEmojis, ['❤️', '👍']); + + // The same user reacting again replaces the emoji instead of adding one. + await CacheUtils.setMessageReaction(peer, sentAt, 'me', '😂'); + message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.reactions, {'me': '😂', 'peer-id': '❤️'}); + + await CacheUtils.setMessageReaction(peer, sentAt, 'me', null); + message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.reactions, {'peer-id': '❤️'}); + + await CacheUtils.setMessageReaction(peer, sentAt, 'peer-id', null); + message = (await CacheUtils.getPrivateMessages(peer)).single; + expect(message.reactions, isNull); + }); + + test('pins are shared state of the chat and can be replaced', () async { + await CacheUtils.setConversationPinned(peer, true); + await CacheUtils.setMessagePinned( + peer, 'message-id', DateTime(2026, 11, 19, 12, 6)); + + var pins = await CacheUtils.getPinnedMessages(peer); + expect(pins.keys, ['message-id']); + // The chat being pinned to the top of the list is a different flag and must + // survive. + expect(await CacheUtils.isConversationPinned(peer), isTrue); + + // A server page is authoritative: anything missing was unpinned elsewhere. + await CacheUtils.replacePinnedMessages(peer, {}); + pins = await CacheUtils.getPinnedMessages(peer); + expect(pins, isEmpty); + + await CacheUtils.setMessagePinned(peer, 'message-id', null); + expect(await CacheUtils.getPinnedMessages(peer), isEmpty); + }); + + test('read receipts are off by default and the peer cursor only moves on', + () async { + const peer = 'peer-id'; + expect(await CacheUtils.isReadReceiptsEnabled(peer), isFalse); + + await CacheUtils.setReadReceiptsEnabled(peer, true); + expect(await CacheUtils.isReadReceiptsEnabled(peer), isTrue); + + await CacheUtils.setPeerReadAt(peer, DateTime(2026, 11, 19, 12, 5)); + expect(await CacheUtils.getPeerReadAt(peer), DateTime(2026, 11, 19, 12, 5)); + + // Out of order frames must not take the tick back. + await CacheUtils.setPeerReadAt(peer, DateTime(2026, 11, 19, 12, 1)); + expect(await CacheUtils.getPeerReadAt(peer), DateTime(2026, 11, 19, 12, 5)); + + await CacheUtils.setReadReceiptsEnabled(peer, false); + expect(await CacheUtils.isReadReceiptsEnabled(peer), isFalse); + }); + + test('a stored media reference rebuilds the envelope for a caption edit', + () async { + final key = Uint8List.fromList([1, 2, 3, 4]); + final reference = MediaReference('media-id', key, MediaType.image, 100, + width: 640, height: 480); + final message = + PrivateMessage(peer, 'caption', DateTime(2026), DateTime(2026), true) + ..mediaId = 'media-id' + ..mediaTypeStr = 'image' + ..mediaRefJson = jsonEncode(reference.toJson()); + + final rebuilt = message.mediaReferences; + expect(rebuilt, isNotNull); + expect(rebuilt!.single.mediaId, 'media-id'); + expect(rebuilt.single.key, key); + expect(rebuilt.single.width, 640); + + // An album is rebuilt from the per-item keys instead. + final album = + PrivateMessage(peer, 'album', DateTime(2026), DateTime(2026), true) + ..setAlbum([ + AlbumItem( + mediaId: 'a', + type: 'image', + size: 10, + keyB64: base64Encode(key), + ), + AlbumItem( + mediaId: 'b', + type: 'image', + size: 20, + keyB64: base64Encode(key), + ), + ]); + expect(album.mediaReferences, hasLength(2)); + expect(album.mediaReferences!.first.mediaId, 'a'); + + // Without the key there is nothing to re-encrypt, so editing is refused. + final legacy = + PrivateMessage(peer, 'legacy', DateTime(2026), DateTime(2026), true) + ..mediaTypeStr = 'image'; + expect(legacy.mediaReferences, isNull); + }); + + test('the mutation cursor never moves backwards', () async { + await CacheUtils.setSyncEventSeq(5); + await CacheUtils.setSyncEventSeq(3); + expect(await CacheUtils.getSyncEventSeq(), 5); + }); +} diff --git a/test/message_search_test.dart b/test/message_search_test.dart new file mode 100644 index 0000000..cbe9668 --- /dev/null +++ b/test/message_search_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/message_search.dart'; + +PrivateMessage text(String body, DateTime sentAt, {String? fileName}) { + return PrivateMessage('peer', body, sentAt, sentAt, true, fileName: fileName); +} + +MessageHit hit(String conversation, PrivateMessage message) => + MessageHit(conversation, message); + +/// Renders a highlighted line back to text, marking matches in brackets, so a +/// test can assert on the split without inspecting styles. +String marked(String text, String needle) => highlightParts(text, needle) + .map((part) => part.match ? '[${part.text}]' : part.text) + .join(); + +void main() { + final base = DateTime(2026, 6, 1, 12); + + group('text matching', () { + test('is case-insensitive and matches inside a word', () { + final query = MessageSearchQuery(text: 'AHOJ'); + expect(query.matches(hit('a', text('tak ahoj tam', base))), isTrue); + expect(query.matches(hit('a', text('nic', base))), isFalse); + }); + + test('an empty query matches everything', () { + const query = MessageSearchQuery(); + expect(query.isEmpty, isTrue); + expect(query.matches(hit('a', text('cokoli', base))), isTrue); + }); + + test('an attachment is findable by its file name', () { + final query = MessageSearchQuery(text: 'smlouva'); + final message = text('', base, fileName: 'Smlouva-2026.pdf'); + expect(query.matches(hit('a', message)), isTrue); + }); + + test('the conversation filter scopes the search', () { + final query = MessageSearchQuery(text: 'ahoj', conversationId: 'b'); + expect(query.matches(hit('a', text('ahoj', base))), isFalse); + expect(query.matches(hit('b', text('ahoj', base))), isTrue); + }); + }); + + group('result ordering', () { + test('newest first and capped', () { + final hits = [ + for (var i = 0; i < searchResultLimit + 5; i++) + hit('a', text('ahoj', base.add(Duration(minutes: i)))), + ]; + final result = + filterMessages(hits, const MessageSearchQuery(text: 'ahoj')); + expect(result.length, searchResultLimit); + expect(result.first.message.sentAt.isAfter(result.last.message.sentAt), + isTrue); + }); + }); + + group('snippet', () { + test('short text is returned as it is', () { + expect(snippet('ahoj', 'ahoj'), 'ahoj'); + }); + + test('long text is cut around the match', () { + final long = '${'a' * 100} hledané ${'b' * 100}'; + final value = snippet(long, 'hledané', radius: 10); + expect(value.startsWith('…'), isTrue); + expect(value.endsWith('…'), isTrue); + expect(value, contains('hledané')); + expect(value.length, lessThan(long.length)); + }); + + test('a missing needle still returns a short window', () { + final value = snippet('a' * 200, 'nic'); + expect(value.endsWith('…'), isTrue); + expect(value.length, 81); + }); + }); + + group('highlighting', () { + test('no needle is a single plain run', () { + expect(highlightParts('ahoj', '').single.match, isFalse); + }); + + test('every occurrence is marked, case-insensitively', () { + expect(marked('Ahoj ahoj AHoj', 'ahoj'), '[Ahoj] [ahoj] [AHoj]'); + }); + + test('the text around the matches is preserved', () { + expect(marked('tak ahoj tam', 'ahoj'), 'tak [ahoj] tam'); + }); + + test('a needle that is not there changes nothing', () { + final parts = highlightParts('tak ahoj tam', 'nic'); + expect(parts.single.text, 'tak ahoj tam'); + expect(parts.single.match, isFalse); + }); + }); +} diff --git a/test/message_store_test.dart b/test/message_store_test.dart new file mode 100644 index 0000000..e44f7db --- /dev/null +++ b/test/message_store_test.dart @@ -0,0 +1,169 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +PrivateMessage message(String senderId, String text, DateTime sentAt, + {int sendStatus = SendStatus.sent}) { + return PrivateMessage(senderId, text, sentAt, sentAt, true, + mediaTypeStr: MediaType.image.name, + downloadStatus: MediaDownloadStatus.ready, + sendStatus: sendStatus); +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_message_store_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + await Hive.openBox('pendingSends'); + await Hive.box('pendingSends').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('one key per message: adding a message does not rewrite the chat', + () async { + final base = DateTime(2026, 1, 1); + for (var i = 0; i < 5; i++) { + await CacheUtils.addPrivateMessages( + 'conv', [message('peer', 'msg $i', base.add(Duration(minutes: i)))]); + } + + final box = Hive.box('privateMessages'); + expect(box.length, 5, reason: 'every message has its own entry'); + for (final key in box.keys) { + expect(CacheUtils.conversationOfKey(key), 'conv'); + } + final stored = await CacheUtils.getPrivateMessages('conv'); + expect(stored.map((m) => m.message), + ['msg 0', 'msg 1', 'msg 2', 'msg 3', 'msg 4']); + }); + + test('a redelivered message is stored once', () async { + final sentAt = DateTime(2026, 1, 1); + final first = message('peer', 'hello', sentAt); + await CacheUtils.addPrivateMessages('conv', [first]); + // The server re-sends what was not acknowledged yet. + await CacheUtils.addPrivateMessages( + 'conv', [message('peer', 'hello', sentAt)]); + + final stored = await CacheUtils.getPrivateMessages('conv'); + expect(stored.length, 1); + }); + + test('deleting the last message of a chat leaves no empty conversation', + () async { + final sentAt = DateTime(2026, 1, 2); + final only = message('peer', 'only one', sentAt); + await CacheUtils.addPrivateMessages('conv', [only]); + + await CacheUtils.deletePrivateMessage('conv', only); + + expect(await CacheUtils.getPrivateMessages('conv'), isEmpty); + // This used to throw on `messages.last` and blank the whole chat list. + expect(await CacheUtils.getLatestPrivateMessages(), isEmpty); + }); + + test('the conversation list shows the newest message per chat', () async { + final base = DateTime(2026, 2, 1); + await CacheUtils.addPrivateMessages('a', [ + message('a', 'old', base), + message('a', 'new', base.add(const Duration(minutes: 5))), + ]); + await CacheUtils.addPrivateMessages('b', [ + message('b', 'other', base.add(const Duration(minutes: 1))), + ]); + + final chats = await CacheUtils.getLatestPrivateMessages(); + final byId = { + for (final entry in chats.entries) entry.key.id: entry.value.message + }; + expect(byId['a'], 'new'); + expect(byId['b'], 'other'); + }); + + test('a legacy conversation list is migrated into per-message keys', + () async { + // Format written by older versions: one list under the user id. + await Hive.box('privateMessages').put('legacy', [ + message('legacy', 'first', DateTime(2026, 3, 1)), + message('legacy', 'second', DateTime(2026, 3, 1, 1)), + ]); + + final chats = await CacheUtils.getLatestPrivateMessages(); + expect(chats.keys.single.id, 'legacy'); + expect(chats.values.single.message, 'second'); + + final box = Hive.box('privateMessages'); + expect(box.containsKey('legacy'), isFalse); + expect( + box.keys + .whereType() + .every((key) => CacheUtils.conversationOfKey(key) == 'legacy'), + isTrue); + }); + + test('the delivery ack flips the message to sent and clears the marker', + () async { + final sentAt = DateTime(2026, 4, 1); + final outgoing = + message('peer', 'pending', sentAt, sendStatus: SendStatus.sending); + await CacheUtils.addPrivateMessages('peer', [outgoing]); + await CacheUtils.addPendingSend('peer', sentAt); + + expect((await CacheUtils.getPendingSends())['peer'], hasLength(1)); + + await CacheUtils.markMessageSent('peer', sentAt); + + final stored = await CacheUtils.getPrivateMessages('peer'); + expect(stored.single.sendStatus, SendStatus.sent); + expect(await CacheUtils.getPendingSends(), isEmpty); + expect(Hive.box('pendingSends').isEmpty, isTrue); + }); + + test('a retried message gets a fresh timestamp and keeps its content', + () async { + final oldSentAt = DateTime(2026, 4, 3); + final failed = + message('peer', 'retry me', oldSentAt, sendStatus: SendStatus.failed); + await CacheUtils.addPrivateMessages('peer', [failed]); + await CacheUtils.addPendingSend('peer', oldSentAt); + + final moved = await CacheUtils.retimestampMessage('peer', failed); + + expect(moved, isNotNull); + expect(moved!.sentAt.isAfter(oldSentAt), isTrue); + final box = Hive.box('privateMessages'); + expect(box.containsKey(CacheUtils.messageKey('peer', oldSentAt)), isFalse, + reason: 'the old key is gone, the message is not stored twice'); + final stored = await CacheUtils.getPrivateMessages('peer'); + expect(stored.single.message, 'retry me'); + expect(stored.single.sentAt, moved.sentAt); + // The marker under the old key is dropped; ChatSender adds it back. + expect(Hive.box('pendingSends').isEmpty, isTrue); + }); + + test('an unacknowledged message stays pending for a resend', () async { + final sentAt = DateTime(2026, 4, 2); + await CacheUtils.addPrivateMessages('peer', + [message('peer', 'no ack', sentAt, sendStatus: SendStatus.sending)]); + await CacheUtils.addPendingSend('peer', sentAt); + + final pending = await CacheUtils.getPendingSends(); + expect(pending['peer']!.single.message, 'no ack'); + }); +} diff --git a/test/pbkdf2_salt_test.dart b/test/pbkdf2_salt_test.dart new file mode 100644 index 0000000..909067c --- /dev/null +++ b/test/pbkdf2_salt_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/crypto_utils.dart'; + +void main() { + test('same password and salt derive the same key', () async { + final salt = List.filled(32, 7); + final first = + await CryptoUtils.pbkdf2('correct horse battery staple', salt); + final second = + await CryptoUtils.pbkdf2('correct horse battery staple', salt); + + expect(first, second); + expect(first.length, 32); + }); + + test('a different salt derives a different key', () async { + final a = await CryptoUtils.pbkdf2( + 'correct horse battery staple', List.filled(32, 1)); + final b = await CryptoUtils.pbkdf2( + 'correct horse battery staple', List.filled(32, 2)); + + expect(a, isNot(b)); + }); + + test('generated salts are random 32-byte values', () { + final a = CryptoUtils.generateSalt(); + final b = CryptoUtils.generateSalt(); + + expect(a.length, 32); + expect(a, isNot(b)); + }); + + test('legacy derivation still matches the old md5 salt scheme', () async { + // Guards the migration path for installs created before random salts. + final legacy = + await CryptoUtils.legacyPbkdf2('correct horse battery staple'); + expect(legacy.length, 32); + expect( + legacy, await CryptoUtils.legacyPbkdf2('correct horse battery staple')); + }); +} diff --git a/test/playback_lock_test.dart b/test/playback_lock_test.dart new file mode 100644 index 0000000..aa44389 --- /dev/null +++ b/test/playback_lock_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/playback_lock.dart'; + +void main() { + test('claim hands the lock to the newest source', () { + final first = Object(); + final second = Object(); + PlaybackLock.claim(first); + expect(PlaybackLock.owner.value, same(first)); + PlaybackLock.claim(second); + expect(PlaybackLock.owner.value, same(second)); + }); + + test('release only clears an owned lock', () { + final owner = Object(); + final stranger = Object(); + PlaybackLock.claim(owner); + PlaybackLock.release(stranger); + expect(PlaybackLock.owner.value, same(owner)); + PlaybackLock.release(owner); + expect(PlaybackLock.owner.value, isNull); + }); +} diff --git a/test/playback_speed_test.dart b/test/playback_speed_test.dart new file mode 100644 index 0000000..a064df4 --- /dev/null +++ b/test/playback_speed_test.dart @@ -0,0 +1,20 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/playback_speed.dart'; + +void main() { + test('cycles through 1x, 1.5x, 2x and back', () { + expect(nextSpeed(1.0), 1.5); + expect(nextSpeed(1.5), 2.0); + expect(nextSpeed(2.0), 1.0); + }); + + test('unknown speed falls back to 1x', () { + expect(nextSpeed(0.5), 1.0); + }); + + test('labels drop the decimal for whole speeds', () { + expect(speedLabel(1.0), '1x'); + expect(speedLabel(1.5), '1.5x'); + expect(speedLabel(2.0), '2x'); + }); +} diff --git a/test/presence_test.dart b/test/presence_test.dart new file mode 100644 index 0000000..dc4cc7b --- /dev/null +++ b/test/presence_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/live_location.dart'; +import 'package:shept/utils/presence.dart'; + +void main() { + final presence = PresenceNotifier.instance; + + setUp(() { + presence.clear(); + presence.typingTtl = const Duration(milliseconds: 20); + presence.presenceTtl = const Duration(milliseconds: 30); + }); + + test('presence offline carries the last seen instant', () { + presence.applyPresence('peer', online: true); + expect(presence.isOnline('peer'), isTrue); + expect(presence.lastSeen('peer'), isNull); + + final sawAt = DateTime(2026, 11, 21, 12, 30); + presence.applyPresence('peer', online: false, lastSeenAt: sawAt); + expect(presence.isOnline('peer'), isFalse); + expect(presence.lastSeen('peer'), sawAt); + }); + + // A peer whose app was killed never announces offline, so silence has to + // expire instead of leaving a green dot forever. + test('an unrefreshed online expires into offline', () async { + presence.applyPresence('peer', online: true); + await Future.delayed(const Duration(milliseconds: 60)); + expect(presence.isOnline('peer'), isFalse); + expect(presence.lastSeen('peer'), isNotNull); + }); + + test('a typing hint clears itself', () async { + presence.applyTyping('peer'); + expect(presence.isTyping('peer'), isTrue); + await Future.delayed(const Duration(milliseconds: 60)); + expect(presence.isTyping('peer'), isFalse); + }); + + test('an expired live position means the session stopped', () { + presence.applyLiveLocation( + 'peer', + LiveLocationPoint(50.08, 14.42, + until: DateTime.now().add(const Duration(minutes: 5)))); + expect(presence.liveLocation('peer'), isNotNull); + expect(presence.liveStartedAt('peer'), isNotNull); + + // The sender's stop frame carries an instant that is already gone. + presence.applyLiveLocation( + 'peer', LiveLocationPoint(50.08, 14.42, until: DateTime.now())); + expect(presence.liveLocation('peer'), isNull); + expect(presence.liveStartedAt('peer'), isNull); + }); + + test('clear drops every known peer', () { + presence.applyPresence('peer', online: true); + presence.applyTyping('peer'); + presence.clear(); + expect(presence.isOnline('peer'), isNull); + expect(presence.isTyping('peer'), isFalse); + expect(presence.lastSeen('peer'), isNull); + }); +} diff --git a/test/reaction_list_test.dart b/test/reaction_list_test.dart new file mode 100644 index 0000000..dd2f24c --- /dev/null +++ b/test/reaction_list_test.dart @@ -0,0 +1,22 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/message_actions.dart'; + +/// The reaction list groups by emoji, so one emoji with several participants is +/// one row with their names, and the busiest row is on top. +void main() { + test('reactions group by emoji, most used first', () { + final rows = MessageActions.groupReactions( + {'me': '❤️', 'a': '👍', 'b': '👍', 'c': '❤️', 'd': '👍'}, + (id) => + {'me': 'Me', 'a': 'Adam', 'b': 'Bea', 'c': 'Cyril', 'd': 'Dana'}[id]!, + ); + + expect(rows.map((row) => row.key), ['👍', '❤️']); + expect(rows.first.value, ['Adam', 'Bea', 'Dana']); + expect(rows.last.value, ['Me', 'Cyril']); + }); + + test('an empty map has no rows', () { + expect(MessageActions.groupReactions(const {}, (id) => id), isEmpty); + }); +} diff --git a/test/reaction_picker_test.dart b/test/reaction_picker_test.dart new file mode 100644 index 0000000..e45596b --- /dev/null +++ b/test/reaction_picker_test.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/message_actions.dart'; +import 'package:shept/utils/singleton.dart'; + +/// The reaction row marks the emoji this user already picked, so a second tap +/// reads as "take mine back". +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() { + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('my own reaction is the only highlighted emoji', (tester) async { + final message = PrivateMessage( + '2', 'ahoj', DateTime(2026), DateTime(2026), true, + mediaId: null) + ..id = 'm-1' + ..reactions = {'1': '❤️', '2': '👍'}; + + await tester.pumpWidget(MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => MessageActions.showSheet(context, message, peer.id, + onSelect: () {}), + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + // Six emoji in the row; exactly the heart carries a background. + final marked = tester + .widgetList(find.byType(IconButton)) + .where((button) => button.style != null) + .toList(); + expect(marked, hasLength(1)); + expect((marked.single.icon as Text).data, '❤️'); + // The row is the way a reaction is given: every chip has to be actionable, + // not decoration. (Tapping one would call the API, so only the wiring is + // checked here.) + expect( + tester + .widgetList(find.byType(IconButton)) + .every((button) => button.onPressed != null), + isTrue, + ); + }); +} diff --git a/test/reaction_rebuild_test.dart b/test/reaction_rebuild_test.dart new file mode 100644 index 0000000..03d11aa --- /dev/null +++ b/test/reaction_rebuild_test.dart @@ -0,0 +1,87 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/chat_bubble.dart'; +import 'package:shept/widgets/media_bubble.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +/// A reaction is toggled on an attachment all the time. When the bubble's clip +/// wrapper came and went with it, the attachment was mounted again from +/// scratch: the decoded frame went away and the photo blinked white before it +/// came back. +void main() { + final png = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg=='); + final key = List.generate(32, (i) => i + 1); + final peer = User('2', 'peer', '', false); + late Directory dir; + + setUpAll(() { + dir = Directory.systemTemp.createTempSync('shept_reaction_rebuild'); + Singleton().boxCollectionKey = key; + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + tearDownAll(() async { + MediaUtils.clearDecryptCache(); + await dir.delete(recursive: true); + }); + + Widget app(PrivateMessage message) => MaterialApp( + home: Scaffold( + body: Center( + child: + ChatBubble(null, message, null, peer, accentColor: Colors.blue), + ), + ), + ); + + testWidgets('reacting to an attachment keeps its image mounted', + (tester) async { + final path = '${dir.path}/photo'; + await tester.runAsync(() async { + await File(path).writeAsBytes( + await MediaUtils.encryptWith(Uint8List.fromList(png), key)); + }); + final message = PrivateMessage( + '2', + '', + DateTime(2026), + DateTime(2026), + true, + mediaId: 'media-1', + mediaTypeStr: MediaType.image.name, + localPath: path, + width: 100, + height: 100, + ); + + await tester.pumpWidget(app(message)); + for (var i = 0; i < 20; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20))); + await tester.pump(const Duration(milliseconds: 16)); + } + expect(find.byType(Image), findsOneWidget); + final before = tester.state(find.byType(MediaBubble)); + + // What CacheUtils.setMessageReaction does: same object, a new badge. + message.reactions = {'1': '👍'}; + await tester.pumpWidget(app(message)); + await tester.pump(const Duration(milliseconds: 16)); + + expect(identical(tester.state(find.byType(MediaBubble)), before), isTrue, + reason: 'the attachment must not be re-mounted by a reaction'); + expect(find.text('👍'), findsOneWidget); + expect(find.byType(Image), findsOneWidget); + }); +} diff --git a/test/reaction_store_test.dart b/test/reaction_store_test.dart new file mode 100644 index 0000000..73e67ea --- /dev/null +++ b/test/reaction_store_test.dart @@ -0,0 +1,67 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; + +/// Giving a reaction is a local write after the server call: if the key does +/// not match, the badge never appears even though the server took the request. +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_reaction_store'); + Hive.init(dir.path); + if (!Hive.isAdapterRegistered(3)) { + Hive.registerAdapter(PrivateMessageAdapter()); + } + }); + + setUp(() async { + for (final name in ['privateMessages', 'conversations', 'user']) { + await Hive.openBox(name); + await Hive.box(name).clear(); + } + }); + + tearDownAll(() async { + await Hive.deleteFromDisk(); + await dir.delete(recursive: true); + }); + + test('a reaction lands on the stored message', () async { + final sentAt = DateTime(2026, 11, 20, 12, 0, 0, 123, 456); + await CacheUtils.addPrivateMessages( + 'peer', [PrivateMessage('me', 'ahoj', sentAt, sentAt, true)]); + + await CacheUtils.setMessageReaction('peer', sentAt, 'me', '❤️'); + final stored = await CacheUtils.getPrivateMessages('peer'); + expect(stored.single.reactions, {'me': '❤️'}); + + // Same emoji again is the caller's toggle; null removes it. + await CacheUtils.setMessageReaction('peer', sentAt, 'me', null); + expect( + (await CacheUtils.getPrivateMessages('peer')).single.reactions, isNull); + }); + + test('a reaction lands on a message loaded back from disk', () async { + // Hive keeps the instant to the millisecond, so the copy a new session + // reads has a shorter sentAt than the key it is stored under. + final sentAt = DateTime(2026, 11, 20, 12, 0, 0, 123, 456); + await CacheUtils.addPrivateMessages( + 'peer', [PrivateMessage('peer', 'ahoj', sentAt, sentAt, true)]); + await Hive.box('privateMessages').close(); + await Hive.openBox('privateMessages'); + + final loaded = (await CacheUtils.getPrivateMessages('peer')).single; + expect(loaded.sentAt.microsecondsSinceEpoch, + isNot(sentAt.microsecondsSinceEpoch), + reason: + 'the box rounds the instant, which is what used to break the key'); + + await CacheUtils.setMessageReaction('peer', loaded.sentAt, 'me', '❤️'); + expect((await CacheUtils.getPrivateMessages('peer')).single.reactions, + {'me': '❤️'}); + }); +} diff --git a/test/read_receipt_test.dart b/test/read_receipt_test.dart new file mode 100644 index 0000000..6c2c7f7 --- /dev/null +++ b/test/read_receipt_test.dart @@ -0,0 +1,101 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/message_notifier.dart'; +import 'package:shept/utils/utils.dart'; +import 'package:shept_websocket_client_dart/models/ws_response.dart'; + +Uint8List frame(Map json) => + Uint8List.fromList(utf8.encode(jsonEncode(json))); + +/// A cursor that arrives with a sync page used to land in Hive without any +/// listener hearing about it, so the ticks of an open chat stayed stale until +/// the next message repainted them. +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_read_receipt_test'); + Hive.init(dir.path); + if (!Hive.isAdapterRegistered(3)) { + Hive.registerAdapter(PrivateMessageAdapter()); + } + }); + + setUp(() async { + for (final box in [ + 'privateMessages', + 'conversations', + 'settings', + 'user' + ]) { + await Hive.openBox(box); + await Hive.box(box).clear(); + } + }); + + tearDownAll(() async { + await Hive.deleteFromDisk(); + await dir.delete(recursive: true); + }); + + test('a cursor from a sync page reaches the cache and the UI', () async { + var notified = 0; + void listener() => notified++; + MessageNotifier().addListener(listener); + addTearDown(() => MessageNotifier().removeListener(listener)); + + final readAt = DateTime.utc(2026, 11, 20, 10, 30); + final response = WsResponse.fromUint8List(frame({ + 'type': 'synced', + 'payload': { + 'messages': [], + 'peers': [], + 'events': [], + 'cleared': [], + 'reads': [ + {'v': 1, 'peerId': 'peer-id', 'readAt': readAt.toIso8601String()} + ], + 'syncedThrough': 0, + 'eventsThrough': 0, + 'hasMore': false, + }, + })); + + await Utils.onWsMessageReceived(response); + + expect(notified, greaterThan(0)); + expect(await CacheUtils.getPeerReadAt('peer-id'), readAt.toLocal()); + }); + + test('the cursor keeps the microseconds of a message sentAt', () async { + // A read cursor equals the sentAt of the newest message read; rounding it + // to milliseconds made the message look unread. + final readAt = DateTime(2026, 11, 20, 10, 30, 0, 123, 456); + await CacheUtils.setPeerReadAt('a', readAt); + expect(await CacheUtils.getPeerReadAt('a'), readAt); + }); + + test('a cursor stored in milliseconds still reads', () async { + final readAt = DateTime(2026, 11, 20, 10, 30, 0, 123); + final box = await Hive.openBox('conversations'); + await box.put('a', {'peerReadAt': readAt.millisecondsSinceEpoch}); + expect(await CacheUtils.getPeerReadAt('a'), readAt); + }); + + test('the cursor only moves forward and is keyed per peer', () async { + final later = DateTime(2026, 11, 20, 11); + await CacheUtils.setPeerReadAt('a', later); + await CacheUtils.setPeerReadAt( + 'a', later.subtract(const Duration(hours: 1))); + await CacheUtils.setPeerReadAt('b', later); + + expect(await CacheUtils.getPeerReadAt('a'), later); + expect(await CacheUtils.getPeerReadAt('b'), later); + }); +} diff --git a/test/reconnect_backoff_test.dart b/test/reconnect_backoff_test.dart new file mode 100644 index 0000000..bab142d --- /dev/null +++ b/test/reconnect_backoff_test.dart @@ -0,0 +1,16 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/websocket_manager.dart'; + +void main() { + test('reconnects back off instead of polling every few seconds', () { + expect(WebSocketManager.delayForAttempt(0), const Duration(seconds: 2)); + expect(WebSocketManager.delayForAttempt(1), const Duration(seconds: 4)); + expect(WebSocketManager.delayForAttempt(2), const Duration(seconds: 8)); + expect(WebSocketManager.delayForAttempt(3), const Duration(seconds: 16)); + }); + + test('the delay is capped so a long offline period stays cheap', () { + expect(WebSocketManager.delayForAttempt(10), WebSocketManager.maxDelay); + expect(WebSocketManager.delayForAttempt(100), WebSocketManager.maxDelay); + }); +} diff --git a/test/round_note_playback_test.dart b/test/round_note_playback_test.dart new file mode 100644 index 0000000..95880ef --- /dev/null +++ b/test/round_note_playback_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/round_note_playback.dart'; + +void main() { + group('the floating copy of a round note', () { + test('appears for a live note that is mostly out of sight', () { + expect(shouldPin(active: true, visibleFraction: 0.4), isTrue); + expect(shouldPin(active: true, visibleFraction: 0), isTrue); + }); + + test('stays away while the circle is on screen', () { + expect(shouldPin(active: true, visibleFraction: 0.5), isFalse); + expect(shouldPin(active: true, visibleFraction: 1), isFalse); + }); + + test('is gone when the note finished or was dismissed', () { + expect(shouldPin(active: false, visibleFraction: 0), isFalse); + expect(shouldPin(active: false, visibleFraction: 0.9), isFalse); + }); + }); + + group('a rubber-band bounce', () { + const viewport = Rect.fromLTWH(0, 0, 400, 800); + + test('measures as if the list had settled', () { + // Dragging down at the top of a reversed chat pulls the note 120 dp + // lower than it will sit once released. + const pulled = Rect.fromLTRB(0, 700, 230, 930); + final settled = settledNoteRect(pulled, overscroll: -120, reversed: true); + expect(settled, const Rect.fromLTRB(0, 580, 230, 810)); + expect(visibleFraction(pulled, viewport), lessThan(0.5)); + expect(visibleFraction(settled, viewport), greaterThan(0.9)); + }); + + test('is ignored when the list is inside its range', () { + const note = Rect.fromLTRB(0, 300, 230, 530); + expect(settledNoteRect(note, overscroll: 0, reversed: true), note); + }); + + test('the shift follows the list direction', () { + const note = Rect.fromLTRB(0, 600, 230, 830); + expect( + settledNoteRect(note, overscroll: 120, reversed: true), + const Rect.fromLTRB(0, 720, 230, 950), + ); + expect( + settledNoteRect(note, overscroll: 120, reversed: false), + const Rect.fromLTRB(0, 480, 230, 710), + ); + }); + }); + + group('the share of the note on screen', () { + const note = Rect.fromLTWH(0, 0, 200, 200); + + test('is 1 when the whole circle is inside the viewport', () { + expect(visibleFraction(note, const Rect.fromLTWH(0, 0, 400, 800)), 1); + }); + + test('is the covered part when the circle is half way out', () { + expect(visibleFraction(note, const Rect.fromLTWH(0, 100, 400, 800)), 0.5); + expect( + visibleFraction(note, const Rect.fromLTWH(0, 150, 400, 800)), 0.25); + }); + + test('is 0 when the circle is out of sight', () { + expect(visibleFraction(note, const Rect.fromLTWH(0, 300, 400, 800)), 0); + expect(visibleFraction(note, const Rect.fromLTWH(0, -400, 400, 300)), 0); + }); + }); +} diff --git a/test/search_user_test.dart b/test/search_user_test.dart new file mode 100644 index 0000000..fc034fd --- /dev/null +++ b/test/search_user_test.dart @@ -0,0 +1,110 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/pages/search_user_page.dart'; + +User user(String name) => User(name, name, 'public-key', false); + +Widget app(SearchUserPage page) => MaterialApp(home: page); + +void main() { + testWidgets('searches after the debounce and clears the results', + (tester) async { + final calls = []; + Future?> search(String query) async { + calls.add(query); + return [user('result-$query')]; + } + + await tester.pumpWidget(app(SearchUserPage(search: search))); + await tester.pumpAndSettle(); + final field = find.byType(TextField); + + await tester.enterText(field, 'a'); + await tester.pump(const Duration(milliseconds: 200)); + expect(calls, isEmpty); + + await tester.enterText(field, 'ab'); + await tester.pump(const Duration(milliseconds: 249)); + expect(calls, isEmpty); + + await tester.pump(const Duration(milliseconds: 1)); + await tester.pumpAndSettle(); + expect(calls, ['ab']); + expect(find.text('result-ab'), findsOneWidget); + + await tester.tap(find.byTooltip('clearSearch')); + await tester.pumpAndSettle(); + expect(find.text('result-ab'), findsNothing); + expect(calls, ['ab']); + }); + + testWidgets('ignores a stale response', (tester) async { + final first = Completer?>(); + final second = Completer?>(); + final calls = []; + Future?> search(String query) { + calls.add(query); + return query == 'a' ? first.future : second.future; + } + + await tester.pumpWidget(app(SearchUserPage(search: search))); + await tester.pumpAndSettle(); + final field = find.byType(TextField); + + await tester.enterText(field, 'a'); + await tester.pump(const Duration(milliseconds: 250)); + await tester.enterText(field, 'ab'); + await tester.pump(const Duration(milliseconds: 250)); + expect(calls, ['a', 'ab']); + + second.complete([user('new')]); + await tester.pumpAndSettle(); + expect(find.text('new'), findsOneWidget); + + first.complete([user('old')]); + await tester.pumpAndSettle(); + expect(find.text('new'), findsOneWidget); + expect(find.text('old'), findsNothing); + }); + + testWidgets('keeps results on error and retries', (tester) async { + var fail = false; + Future?> search(String query) async => + fail ? null : [user('alice')]; + + await tester.pumpWidget(app(SearchUserPage(search: search))); + await tester.pumpAndSettle(); + final field = find.byType(TextField); + + await tester.enterText(field, 'a'); + await tester.pump(const Duration(milliseconds: 250)); + await tester.pumpAndSettle(); + expect(find.text('alice'), findsOneWidget); + + fail = true; + await tester.enterText(field, 'ab'); + await tester.pump(const Duration(milliseconds: 250)); + await tester.pumpAndSettle(); + expect(find.text('userSearchFailed'), findsOneWidget); + expect(find.text('alice'), findsOneWidget); + + fail = false; + await tester.tap(find.text('retry')); + await tester.pumpAndSettle(); + expect(find.text('userSearchFailed'), findsNothing); + expect(find.text('alice'), findsOneWidget); + }); + + testWidgets('shows the empty result state', (tester) async { + await tester.pumpWidget(app(SearchUserPage(search: (_) async => []))); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'nobody'); + await tester.pump(const Duration(milliseconds: 250)); + await tester.pumpAndSettle(); + + expect(find.text('noUsersFound'), findsOneWidget); + }); +} diff --git a/test/server_url_and_temp_test.dart b/test/server_url_and_temp_test.dart new file mode 100644 index 0000000..aff6352 --- /dev/null +++ b/test/server_url_and_temp_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/media_utils.dart'; +import 'package:shept/utils/utils.dart'; + +void main() { + group('server url policy', () { + test('https is always allowed', () { + expect(Utils.isAllowedServerUrl('https://chat.example.com'), isTrue); + expect(Utils.isAllowedServerUrl('https://192.168.1.2:8081'), isTrue); + }); + + test('plain http is a debug-only convenience', () { + // Unit tests run in debug mode, so this asserts the debug branch. + expect(Utils.isAllowedServerUrl('http://192.168.1.118:8080'), isTrue); + }); + + test('anything that is not a server address is refused', () { + expect(Utils.isAllowedServerUrl(''), isFalse); + expect(Utils.isAllowedServerUrl('not a url'), isFalse); + expect(Utils.isAllowedServerUrl('ftp://example.com'), isFalse); + expect(Utils.isAllowedServerUrl('file:///etc/passwd'), isFalse); + expect(Utils.isAllowedServerUrl('https://'), isFalse); + }); + }); + + group('plaintext temp media', () { + test('only the app temp files are swept', () { + expect(MediaUtils.isTempMediaName('shept_media_abc.mp4'), isTrue); + expect(MediaUtils.isTempMediaName('shept_send_abc.gif'), isTrue); + expect(MediaUtils.isTempMediaName('shared_prefs.xml'), isFalse); + expect(MediaUtils.isTempMediaName('shept.sqlite'), isFalse); + }); + }); +} diff --git a/test/settings_tile_test.dart b/test/settings_tile_test.dart new file mode 100644 index 0000000..dfcf1e4 --- /dev/null +++ b/test/settings_tile_test.dart @@ -0,0 +1,28 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/widgets/settings_tile.dart'; + +void main() { + testWidgets('row height does not depend on a trailing widget', + (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Column( + children: [ + SettingsTile(icon: Icons.palette, label: 'plain', onPressed: () {}), + SettingsTile( + icon: Icons.notifications, + label: 'switch', + trailing: Switch(value: true, onChanged: (_) {}), + ), + ], + ), + ), + )); + + final plain = tester.getSize(find.byType(SettingsTile).at(0)); + final withSwitch = tester.getSize(find.byType(SettingsTile).at(1)); + expect(plain.height, withSwitch.height); + expect(plain.width, withSwitch.width); + }); +} diff --git a/test/storage_utils_test.dart b/test/storage_utils_test.dart new file mode 100644 index 0000000..f510b3e --- /dev/null +++ b/test/storage_utils_test.dart @@ -0,0 +1,71 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/storage_utils.dart'; + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_storage_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + PrivateMessage attachment(String text, DateTime sentAt, String? path, + {int size = 1000}) => + PrivateMessage('1', text, sentAt, sentAt, true, + mediaTypeStr: 'image', localPath: path, mediaSize: size); + + test('usage sums only attachments that still have a local copy', () async { + final file = File('${dir.path}/a')..writeAsBytesSync([1, 2, 3]); + await CacheUtils.addPrivateMessages('1', [ + attachment('on disk', DateTime.now(), file.path), + attachment('gone', DateTime.now(), null, size: 5000), + ]); + + final usage = await StorageUtils.usageByConversation(); + + expect(usage.single.attachments, 1); + expect(usage.single.bytes, greaterThanOrEqualTo(1000)); + }); + + test('purge drops the file and marks the attachment expired', () async { + final file = File('${dir.path}/b')..writeAsBytesSync([1, 2, 3]); + await CacheUtils.addPrivateMessages('1', [ + attachment( + 'old', DateTime.now().subtract(const Duration(days: 40)), file.path), + ]); + + final freed = await StorageUtils.purgeOlderThanDays(30); + + expect(freed, greaterThanOrEqualTo(1000)); + expect(file.existsSync(), isFalse); + final stored = (await CacheUtils.getPrivateMessages('1')).single; + expect(stored.localPath, isNull); + expect(stored.downloadStatus, MediaDownloadStatus.expired); + }); + + test('purge keeps the media of recent messages', () async { + final file = File('${dir.path}/c')..writeAsBytesSync([1, 2, 3]); + await CacheUtils.addPrivateMessages( + '1', [attachment('new', DateTime.now(), file.path)]); + + await StorageUtils.purgeOlderThanDays(30); + + expect(file.existsSync(), isTrue); + }); +} diff --git a/test/text_envelope_test.dart b/test/text_envelope_test.dart new file mode 100644 index 0000000..196a621 --- /dev/null +++ b/test/text_envelope_test.dart @@ -0,0 +1,96 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/text_envelope.dart'; + +Uint8List bytes(String text) => Uint8List.fromList(utf8.encode(text)); + +void main() { + test('a reply survives the round trip', () { + final sentAt = DateTime(2026, 3, 4, 5, 6, 7); + final envelope = buildTextEnvelope( + 'souhlasím', + ReplyRef( + senderId: 'peer', + sentAt: sentAt, + preview: ReplyRef.previewOf('původní zpráva'), + )); + + final parsed = tryParseTextEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.body, 'souhlasím'); + expect(parsed.reply!.senderId, 'peer'); + expect(parsed.reply!.sentAt, sentAt); + expect(parsed.reply!.preview, 'původní zpráva'); + }); + + test('the envelope is not a media envelope', () { + final envelope = buildTextEnvelope( + 'x', ReplyRef(senderId: 'a', sentAt: DateTime(2026), preview: 'y')); + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['kind'], 'text'); + expect(decoded['sheptMsg'], textEnvelopeVersion); + }); + + test('a forwarded message survives the round trip without a quote', () { + final envelope = buildTextEnvelope('přeposláno', null, forwarded: true); + + final parsed = tryParseTextEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.body, 'přeposláno'); + expect(parsed.forwarded, isTrue); + expect(parsed.reply, isNull); + // The version stays 3: an older reader still opens the body instead of + // showing raw JSON. + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['sheptMsg'], textEnvelopeVersion); + }); + + test('an envelope without the flag is not a forward', () { + final parsed = tryParseTextEnvelope(buildTextEnvelope( + 'x', ReplyRef(senderId: 'a', sentAt: DateTime(2026), preview: 'y'))); + expect(parsed!.forwarded, isFalse); + }); + + test('a one-time location carries its flag', () { + final envelope = buildTextEnvelope('📍 50.08, 14.42', null, + location: const LocationRef(50.08, 14.42), viewOnce: true); + + final parsed = tryParseTextEnvelope(envelope); + expect(parsed!.viewOnce, isTrue); + expect(parsed.location!.lat, 50.08); + // An older reader still opens the body instead of raw JSON. + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['sheptMsg'], textEnvelopeVersion); + }); + + test('plain text is not an envelope', () { + expect(tryParseTextEnvelope(bytes('ahoj')), isNull); + }); + + test('a media envelope is not a text envelope', () { + final media = bytes('{"sheptMsg":1,"kind":"media","media":{}}'); + expect(tryParseTextEnvelope(media), isNull); + }); + + test('a broken body is not an envelope', () { + final broken = bytes('{"sheptMsg":3,"kind":"text","body":5}'); + expect(tryParseTextEnvelope(broken), isNull); + }); + + test('a broken quote is ignored, the body still reads', () { + final broken = + bytes('{"sheptMsg":3,"kind":"text","body":"a","replyTo":{"x":1}}'); + final parsed = tryParseTextEnvelope(broken); + expect(parsed!.body, 'a'); + expect(parsed.reply, isNull); + }); + + test('the preview is capped', () { + final long = 'x' * (ReplyRef.maxPreviewLength + 50); + final preview = ReplyRef.previewOf(long); + expect(preview.length, ReplyRef.maxPreviewLength + 1); + expect(preview.endsWith('…'), isTrue); + }); +} diff --git a/test/theme_dialog_test.dart b/test/theme_dialog_test.dart new file mode 100644 index 0000000..5176caf --- /dev/null +++ b/test/theme_dialog_test.dart @@ -0,0 +1,84 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:provider/provider.dart'; +import 'package:shept/models/app_theme.dart'; +import 'package:shept/utils/dialog_utils.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/theme_notifier.dart'; + +/// The theme dialog applies on tap, so picking a swatch has to move the seed +/// the whole app is seeded with - and show which one is in use. +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('shept_theme_dialog_test'); + Hive.init(dir.path); + if (!Hive.isAdapterRegistered(2)) { + Hive.registerAdapter(AppThemeAdapter()); + } + }); + + setUp(() async { + await Hive.openBox('theme'); + await Hive.box('theme').clear(); + Singleton().appTheme = AppTheme.fromValues(ThemeMode.system, Colors.blue); + }); + + tearDownAll(() async { + await dir.delete(recursive: true); + }); + + Future open(WidgetTester tester) async { + final theme = ThemeNotifier(Singleton().appTheme); + await tester.pumpWidget(ChangeNotifierProvider.value( + value: theme, + child: MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showDialog( + context: context, builder: DialogUtils.themeDialog), + child: const Text('open'), + ), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + } + + testWidgets('a swatch becomes the seed and is marked as picked', + (tester) async { + await open(tester); + expect(find.byIcon(Icons.check), findsOneWidget, reason: 'blue is picked'); + + await tester.tap(find.byKey(const ValueKey('themeSwatch-8'))); + await tester.pumpAndSettle(); + // Let the fire-and-forget Hive write finish before the test tears down. + await tester + .runAsync(() => Future.delayed(const Duration(milliseconds: 50))); + + // getMaterialColor builds a fresh MaterialColor, so compare values. + expect(Singleton().appTheme.color.toARGB32(), Colors.teal.toARGB32()); + // The check has to move to the picked swatch: comparing the stored + // MaterialColor by identity left it on the custom tile forever. + expect( + find.descendant( + of: find.byKey(const ValueKey('themeSwatch-8')), + matching: find.byIcon(Icons.check)), + findsOneWidget, + ); + final swatch = tester.widget(find + .descendant( + of: find.byKey(const ValueKey('themeSwatch-8')), + matching: find.byType(Container)) + .first); + expect((swatch.decoration as BoxDecoration?)?.color?.toARGB32(), + Colors.teal.toARGB32()); + }); +} diff --git a/test/token_expiry_test.dart b/test/token_expiry_test.dart new file mode 100644 index 0000000..930311b --- /dev/null +++ b/test/token_expiry_test.dart @@ -0,0 +1,70 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/utils/utils.dart'; + +String _token(Map payload) { + String encode(Map value) => + base64Url.encode(utf8.encode(jsonEncode(value))).replaceAll('=', ''); + return '${encode({ + 'alg': 'HS256', + 'typ': 'JWT' + })}.${encode(payload)}.signature'; +} + +void main() { + // Replaces the jwt_decoder dependency, which was only used for this check. + test('an expired token is detected without a package', () { + final expired = _token({ + 'sub': 'user', + 'exp': DateTime.now() + .subtract(const Duration(minutes: 1)) + .millisecondsSinceEpoch ~/ + 1000, + }); + expect(Utils.isTokenExpired(expired), isTrue); + }); + + test('a live token is not reported as expired', () { + final live = _token({ + 'sub': 'user', + 'exp': DateTime.now() + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ + 1000, + }); + expect(Utils.isTokenExpired(live), isFalse); + }); + + test('a token without the type claim is not usable', () { + // Issued before the server started requiring `typ`: valid signature and + // expiry, but every request would be rejected. + final legacy = _token({ + 'sub': 'user', + 'exp': DateTime.now() + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ + 1000, + }); + expect(Utils.isTokenExpired(legacy), isFalse); + expect(Utils.isTokenUsable(legacy), isFalse); + }); + + test('a typed token is usable', () { + final typed = _token({ + 'sub': 'user', + 'typ': 'access', + 'exp': DateTime.now() + .add(const Duration(minutes: 5)) + .millisecondsSinceEpoch ~/ + 1000, + }); + expect(Utils.isTokenUsable(typed), isTrue); + }); + + test('a malformed token counts as expired', () { + expect(Utils.isTokenExpired(''), isTrue); + expect(Utils.isTokenExpired('not-a-jwt'), isTrue); + expect(Utils.isTokenExpired('a.b.c'), isTrue); + }); +} diff --git a/test/typing_dots_test.dart b/test/typing_dots_test.dart new file mode 100644 index 0000000..9aedc41 --- /dev/null +++ b/test/typing_dots_test.dart @@ -0,0 +1,47 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shept/widgets/typing_dots.dart'; + +void main() { + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + }); + + Widget app(Widget child, {bool reduceMotion = false}) { + return MaterialApp( + home: MediaQuery( + data: MediaQueryData(disableAnimations: reduceMotion), + child: Scaffold(body: Center(child: child)), + ), + ); + } + + testWidgets('typing is three animated dots', (tester) async { + await tester.pumpWidget(app(const TypingDots())); + await tester.pump(); + // Three circles, no text hint. + expect( + find.byWidgetPredicate((widget) => + widget is Container && + widget.decoration is BoxDecoration && + (widget.decoration as BoxDecoration).shape == BoxShape.circle), + findsNWidgets(3)); + }); + + testWidgets('reduced motion gets a static ellipsis instead', (tester) async { + await tester.pumpWidget(app(const TypingDots(), reduceMotion: true)); + await tester.pump(); + expect(find.text('…'), findsOneWidget); + expect( + find.byWidgetPredicate((widget) => + widget is Container && + widget.decoration is BoxDecoration && + (widget.decoration as BoxDecoration).shape == BoxShape.circle), + findsNothing); + }); +} diff --git a/test/undecryptable_message_test.dart b/test/undecryptable_message_test.dart new file mode 100644 index 0000000..b44dd51 --- /dev/null +++ b/test/undecryptable_message_test.dart @@ -0,0 +1,28 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; + +void main() { + final sentAt = DateTime(2026, 5, 1); + + test('an undecryptable message is kept as a visible placeholder', () { + final message = PrivateMessage('peer', PrivateMessage.undecryptableMarker, + sentAt, DateTime(2026, 5, 1, 0, 1), false); + + expect(message.isUndecryptable, isTrue); + // The chat list shows the placeholder instead of an empty preview. + expect(message.preview, isNotEmpty); + }); + + test('a normal message is not mistaken for the placeholder', () { + final message = PrivateMessage( + 'peer', 'hello', sentAt, DateTime(2026, 5, 1, 0, 1), false); + expect(message.isUndecryptable, isFalse); + expect(message.preview, 'hello'); + }); + + test('an expired attachment is a terminal state, not a failure', () { + // Download retries are pointless once the server dropped the file. + expect(MediaDownloadStatus.expired, isNot(MediaDownloadStatus.failed)); + expect(MediaDownloadStatus.expired, isNot(MediaDownloadStatus.pending)); + }); +} diff --git a/test/user_list_item_test.dart b/test/user_list_item_test.dart new file mode 100644 index 0000000..5807d39 --- /dev/null +++ b/test/user_list_item_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/presence.dart'; +import 'package:shept/widgets/user_list_item.dart'; + +Widget app() => MaterialApp( + home: Scaffold( + body: UserListItem(User('1', 'peer', 'key', false), () {}), + ), + ); + +/// The presence dot is the only green circle on the row. +final dot = find.byWidgetPredicate((widget) => + widget is Container && + widget.decoration is BoxDecoration && + (widget.decoration as BoxDecoration).color == const Color(0xFF2E7D32)); + +void main() { + final presence = PresenceNotifier.instance; + + setUp(() { + presence.clear(); + presence.presenceTtl = const Duration(milliseconds: 30); + }); + tearDown(presence.clear); + + testWidgets('a known online peer gets the badge', (tester) async { + await tester.pumpWidget(app()); + expect(dot, findsNothing); + + presence.applyPresence('1', online: true); + await tester.pump(); + expect(dot, findsOneWidget); + presence.clear(); + }); + + testWidgets('an offline peer has no badge and no unknown status', ( + tester, + ) async { + presence.applyPresence('1', online: false); + await tester.pumpWidget(app()); + expect(dot, findsNothing); + }); +} diff --git a/test/video_note_test.dart b/test/video_note_test.dart new file mode 100644 index 0000000..f614d0d --- /dev/null +++ b/test/video_note_test.dart @@ -0,0 +1,41 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept_websocket_client_dart/models/media_reference.dart'; +import 'package:shept_websocket_client_dart/models/media_type.dart'; + +void main() { + PrivateMessage video({String? referenceJson}) => PrivateMessage( + '1', + '', + DateTime(2026, 11, 23), + DateTime(2026, 11, 23), + true, + mediaTypeStr: 'video', + mediaRefJson: referenceJson, + ); + + String referenceJson({required bool note}) => jsonEncode(MediaReference( + 'id', + Uint8List(32), + MediaType.video, + 1024, + videoNote: note, + ).toJson()); + + test('a round note is recognised from its finished reference', () { + expect(video(referenceJson: referenceJson(note: true)).isVideoNote, isTrue); + }); + + test('a round note still sending is recognised from its marker', () { + expect(video(referenceJson: '{"videoNote":true}').isVideoNote, isTrue); + }); + + test('a plain video is not a round note', () { + expect( + video(referenceJson: referenceJson(note: false)).isVideoNote, isFalse); + expect(video().isVideoNote, isFalse); + }); +} diff --git a/test/view_once_location_test.dart b/test/view_once_location_test.dart new file mode 100644 index 0000000..0ed068f --- /dev/null +++ b/test/view_once_location_test.dart @@ -0,0 +1,91 @@ +import 'dart:convert'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/utils/text_envelope.dart'; +import 'package:shept/widgets/chat_bubble.dart'; +import 'package:shept/widgets/view_once_frame.dart'; + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + PrivateMessage location({bool mine = false, DateTime? openedAt}) { + final at = DateTime(2026); + return PrivateMessage( + mine ? '1' : '2', + '', + at, + at, + true, + viewOnce: true, + openedAt: openedAt, + locationJson: jsonEncode(const LocationRef(50.08, 14.42).toJson()), + ); + } + + Widget app(PrivateMessage message) => EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ChatBubble( + null, + message, + null, + peer, + accentColor: Colors.blue, + ), + ), + ), + ); + }), + ); + + // One app for the whole test: easy_localization loads its bundle once. + testWidgets('a view-once location is a card revealed once', (tester) async { + await tester.pumpWidget(app(location())); + await tester.pumpAndSettle(); + + // The recipient gets the placeholder, and it is tappable. + expect(find.text('Tap to view once'), findsOneWidget); + expect(tester.widget(find.byType(ViewOnceFrame)).onTap, + isNotNull); + // The coordinates are not shown before the reveal. + expect(find.textContaining('50.08'), findsNothing); + + // Once opened it is a tombstone with no way back in. + await tester.pumpWidget(app(location(openedAt: DateTime(2026, 1, 2)))); + await tester.pumpAndSettle(); + expect(find.text('Opened'), findsOneWidget); + expect( + tester.widget(find.byType(ViewOnceFrame)).onTap, isNull); + + // The sender never gets the reveal, only the state. + await tester.pumpWidget(app(location(mine: true))); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byType(ViewOnceFrame)).onTap, isNull); + expect(find.byType(ViewOnceFrame), findsOneWidget); + }); +} diff --git a/test/view_once_preview_test.dart b/test/view_once_preview_test.dart new file mode 100644 index 0000000..6f282a3 --- /dev/null +++ b/test/view_once_preview_test.dart @@ -0,0 +1,79 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:hive/hive.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/utils/cache_utils.dart'; +import 'package:shept/utils/text_envelope.dart'; + +void main() { + late Directory dir; + final now = DateTime(2026, 11, 23, 10); + const location = LocationRef(50.17595, 14.42); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + dir = Directory.systemTemp.createTempSync('shept_view_once_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + await Hive.openBox('privateMessages'); + await Hive.box('privateMessages').clear(); + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + PrivateMessage locationMessage({required bool viewOnce}) => PrivateMessage( + '1', + location.body, + now, + now, + true, + viewOnce: viewOnce, + locationJson: jsonEncode(location.toJson()), + ); + + test('a view-once location never previews its coordinates', () { + final message = locationMessage(viewOnce: true); + + expect(message.preview, 'viewOnceMedia'.tr()); + + message.openedAt = now; + expect(message.preview, 'viewOnceOpened'.tr()); + }); + + test('a normal location previews without the pin emoji', () { + expect(locationMessage(viewOnce: false).preview, '50.17595, 14.42000'); + }); + + test('other previews keep their emojis', () { + final message = PrivateMessage('1', 'ahoj 😀👍 svět', now, now, true); + + expect(message.preview, 'ahoj 😀👍 svět'); + }); + + test('opening a view-once message clears its text and coordinates', () async { + final message = locationMessage(viewOnce: true); + await CacheUtils.addPrivateMessages('2', [message]); + + await CacheUtils.markMessageOpened( + '2', now, now.add(const Duration(minutes: 1))); + + final stored = (await CacheUtils.getPrivateMessages('2')).single; + expect(stored.openedAt, isNotNull); + expect(stored.message, isEmpty); + expect(stored.locationJson, isNull); + expect(stored.preview, 'viewOnceOpened'.tr()); + }); +} diff --git a/test/view_once_test.dart b/test/view_once_test.dart new file mode 100644 index 0000000..08c72f0 --- /dev/null +++ b/test/view_once_test.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shept/models/private_message.dart'; +import 'package:shept/models/profile.dart'; +import 'package:shept/models/user.dart'; +import 'package:shept/utils/singleton.dart'; +import 'package:shept/widgets/media_bubble.dart'; + +Widget app(PrivateMessage message, {String peer = 'peer'}) => MaterialApp( + home: Scaffold( + body: MediaBubble( + message: message, + bubbleColor: Colors.grey, + textColor: Colors.black, + onRetry: () {}, + canRetry: false, + conversationUserId: peer, + ), + ), + ); + +PrivateMessage once({bool mine = false, DateTime? openedAt}) { + final at = DateTime(2026, 5, 1, 12); + return PrivateMessage( + mine ? 'me' : 'peer', + '', + at, + at, + true, + mediaTypeStr: 'image', + downloadStatus: MediaDownloadStatus.pending, + viewOnce: true, + openedAt: openedAt, + ); +} + +void main() { + setUp(() { + Singleton().profile = Profile('http://localhost', + User('me', 'me', 'key', false), 'key', 'private-key', '', '', true); + }); + + testWidgets('the receiver can still open an unopened attachment', ( + tester, + ) async { + await tester.pumpWidget(app(once())); + expect(find.text('viewOnceOpen'), findsNothing); + expect(find.text('viewOnceLoad'), findsOneWidget); + }); + + testWidgets('an opened attachment is a read-only tombstone', (tester) async { + await tester.pumpWidget(app(once(openedAt: DateTime(2026, 5, 1, 12, 5)))); + expect(find.text('viewOnceOpened'), findsOneWidget); + expect(find.text('viewOnceLoad'), findsNothing); + expect(tester.widget(find.byType(InkWell)).onTap, isNull); + }); + + testWidgets('the sender never gets a way to open its own attachment', ( + tester, + ) async { + await tester.pumpWidget(app(once(mine: true))); + expect(find.text('viewOnceSent'), findsOneWidget); + expect(find.text('viewOnceOpen'), findsNothing); + expect(find.text('viewOnceLoad'), findsNothing); + expect(tester.widget(find.byType(InkWell)).onTap, isNull); + }); + + testWidgets('the sender sees the opened state once the peer opened it', ( + tester, + ) async { + await tester.pumpWidget( + app(once(mine: true, openedAt: DateTime(2026, 5, 1, 12, 5)))); + expect(find.text('viewOnceOpenedByPeer'), findsOneWidget); + expect(tester.widget(find.byType(InkWell)).onTap, isNull); + }); + + testWidgets('the self-chat can still open its own attachment', ( + tester, + ) async { + await tester.pumpWidget(app(once(mine: true), peer: 'me')); + expect(find.text('viewOnceLoad'), findsOneWidget); + expect(tester.widget(find.byType(InkWell)).onTap, isNotNull); + }); + + testWidgets('a downloaded album is ready to open, not stuck on download', ( + tester, + ) async { + // An album keeps its copies per item: the message itself has no localPath. + final album = once(); + album.setAlbum([ + AlbumItem(mediaId: 'a', type: 'image', size: 10, localPath: '/a'), + AlbumItem(mediaId: 'b', type: 'video', size: 20, localPath: '/b'), + ]); + await tester.pumpWidget(app(album)); + expect(find.text('viewOnceOpen'), findsOneWidget); + expect(find.text('viewOnceLoad'), findsNothing); + expect(tester.widget(find.byType(InkWell)).onTap, isNotNull); + }); + + testWidgets('an album missing a copy still offers the download', ( + tester, + ) async { + final album = once(); + album.setAlbum([ + AlbumItem(mediaId: 'a', type: 'image', size: 10, localPath: '/a'), + AlbumItem(mediaId: 'b', type: 'video', size: 20), + ]); + await tester.pumpWidget(app(album)); + expect(find.text('viewOnceLoad'), findsOneWidget); + }); +} diff --git a/update.sh b/update.sh new file mode 100755 index 0000000..cf9eb01 --- /dev/null +++ b/update.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +flutter pub get +flutter pub upgrade --major-versions