Compare commits

...
3 Commits
Author SHA1 Message Date
sevenhill b22654b99f Update Qlyra to 1.0.13 with messaging, media and plugin improvements
Build Android (FCM) / build-android-fcm (push) Canceled after 0s
Build Android / build-android (push) Canceled after 0s
Build iOS / build-ios (push) Canceled after 0s
Build Linux / build-linux (push) Canceled after 0s
Build macOS / build-macos (push) Canceled after 0s
Build Windows / build-windows (push) Canceled after 0s
Native crypto / native-crypto (push) Canceled after 0s
Release (main) / android (oneme) (push) Canceled after 0s
Release (main) / android (qlyra) (push) Canceled after 0s
Release (main) / windows (push) Canceled after 0s
Release (main) / linux (push) Canceled after 0s
Release (main) / macos (push) Canceled after 0s
Release (main) / ios (push) Canceled after 0s
Release (main) / release (push) Canceled after 0s
2026-09-10 17:55:55 +03:00
sevenhill 50816588e4 Update Qlyra application
Build Android (FCM) / build-android-fcm (push) Canceled after 0s
Build Android / build-android (push) Canceled after 0s
Build iOS / build-ios (push) Canceled after 0s
Build Linux / build-linux (push) Canceled after 0s
Build macOS / build-macos (push) Canceled after 0s
Build Windows / build-windows (push) Canceled after 0s
Release (main) / android (oneme) (push) Canceled after 0s
Release (main) / android (qlyra) (push) Canceled after 0s
Release (main) / windows (push) Canceled after 0s
Release (main) / linux (push) Canceled after 0s
Release (main) / macos (push) Canceled after 0s
Release (main) / ios (push) Canceled after 0s
Release (main) / release (push) Canceled after 0s
2026-08-30 22:53:15 +03:00
sevenhill 116d3fb1d3 Remove GPLv3 license file
Release (main) / android (oneme) (push) Canceled after 0s
Release (main) / android (qlyra) (push) Canceled after 0s
Release (main) / windows (push) Canceled after 0s
Release (main) / linux (push) Canceled after 0s
Release (main) / macos (push) Canceled after 0s
Release (main) / ios (push) Canceled after 0s
Release (main) / release (push) Canceled after 0s
2026-08-30 22:52:18 +03:00
233 changed files with 20045 additions and 3889 deletions
+60
View File
@@ -0,0 +1,60 @@
name: Android Emulator Smoke
on:
pull_request:
branches:
- main
- 'dev/**'
workflow_dispatch:
jobs:
launch-qlyra:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
submodules: recursive
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
cache: gradle
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
flutter-version: '3.44.3'
channel: stable
cache: true
- name: Setup Rust
uses: ./.github/actions/setup-rust
with:
targets: aarch64-linux-android,armv7-linux-androideabi,x86_64-linux-android
- name: Install dependencies
run: flutter pub get
- name: Build smoke APK
run: flutter build apk --debug --flavor qlyra
- name: Launch on emulator
uses: ReactiveCircus/android-emulator-runner@v2
with:
api-level: 35
arch: x86_64
profile: pixel_6
disable-animations: true
script: |
adb install -r build/app/outputs/flutter-apk/app-qlyra-debug.apk
adb logcat -c
adb shell am start -W -n ru.qlyra.app/.MainActivity
sleep 10
adb shell pidof ru.qlyra.app
if adb logcat -d '*:E' | grep -E 'FATAL EXCEPTION|Process: ru.qlyra.app'; then
exit 1
fi
+39 -8
View File
@@ -10,12 +10,10 @@ on:
- 'lib/**'
- 'android/**'
- 'pubspec.yaml'
- '.github/workflows/build-android-fcm.yml'
pull_request:
paths:
- 'lib/**'
- 'android/**'
- 'pubspec.yaml'
- 'pubspec.lock'
- 'native/**'
- 'third_party/**'
- 'scripts/verify_android_signing.sh'
- '.github/workflows/build-android-fcm.yml'
jobs:
@@ -49,6 +47,27 @@ jobs:
- name: Get dependencies
run: flutter pub get
- name: Verify formatting
run: dart format --output=none --set-exit-if-changed lib test
- name: Flutter analyze
run: flutter analyze --no-fatal-infos lib test
- name: Install native plugin build dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libclang-dev
- name: Prepare native plugin runtime for tests
run: dart run tool/prepare_plugin_runtime.dart
- name: Build native crypto test library
run: cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
- name: Flutter tests
run: flutter test
- name: Configure Gradle
run: |
mkdir -p ~/.gradle
@@ -66,8 +85,8 @@ jobs:
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
if [ -z "$KEYSTORE_BASE64" ]; then
echo "KEYSTORE_BASE64 secret not set — release will be debug-signed."
exit 0
echo "Release signing secrets are required."
exit 1
fi
echo "$KEYSTORE_BASE64" | base64 -d > android/app/qlyra-release.jks
{
@@ -84,6 +103,12 @@ jobs:
- name: Build Split APKs
run: flutter build apk --release --split-per-abi --flavor oneme --obfuscate --split-debug-info=build/symbols
- name: Verify APK release certificates
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: bash scripts/verify_android_signing.sh
- name: Upload Universal APK
uses: actions/upload-artifact@v4
with:
@@ -119,6 +144,12 @@ jobs:
- name: Build App Bundle
run: flutter build appbundle --release --flavor oneme --obfuscate --split-debug-info=build/symbols
- name: Verify App Bundle release certificate
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: bash scripts/verify_android_signing.sh
- name: Upload App Bundle artifact
uses: actions/upload-artifact@v4
with:
+165
View File
@@ -0,0 +1,165 @@
name: Build Android (Google Play)
on:
workflow_dispatch:
jobs:
build-android:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
cache: 'gradle'
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
flutter-version: '3.44.3'
channel: 'stable'
cache: true
- name: Setup Rust
uses: ./.github/actions/setup-rust
with:
targets: aarch64-linux-android,armv7-linux-androideabi,x86_64-linux-android
- name: Get dependencies
run: flutter pub get
- name: Verify formatting
run: dart format --output=none --set-exit-if-changed lib test
- name: Flutter analyze
run: flutter analyze --no-fatal-infos lib test
- name: Install native plugin build dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libclang-dev
- name: Prepare native plugin runtime for tests
run: dart run tool/prepare_plugin_runtime.dart
- name: Build native crypto test library
run: cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
- name: Flutter tests
run: flutter test
- name: Configure Gradle
run: |
mkdir -p ~/.gradle
echo "org.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=1024m" >> ~/.gradle/gradle.properties
echo "kotlin.daemon.jvmargs=-Xmx1536m" >> ~/.gradle/gradle.properties
echo "org.gradle.caching=true" >> ~/.gradle/gradle.properties
echo "org.gradle.parallel=true" >> ~/.gradle/gradle.properties
echo "org.gradle.configureondemand=true" >> ~/.gradle/gradle.properties
- name: Setup release signing
env:
KEYSTORE_BASE64: ${{ secrets.PLAY_KEYSTORE_BASE64 || secrets.KEYSTORE_BASE64 }}
KEYSTORE_PASSWORD: ${{ secrets.PLAY_KEYSTORE_PASSWORD || secrets.KEYSTORE_PASSWORD }}
KEY_PASSWORD: ${{ secrets.PLAY_KEY_PASSWORD || secrets.KEY_PASSWORD }}
KEY_ALIAS: ${{ secrets.PLAY_KEY_ALIAS || secrets.KEY_ALIAS }}
run: |
if [ -z "$KEYSTORE_BASE64" ]; then
echo "Release signing secrets are required."
exit 1
fi
echo "$KEYSTORE_BASE64" | base64 -d > android/app/qlyra-release.jks
{
echo "storePassword=$KEYSTORE_PASSWORD"
echo "keyPassword=$KEY_PASSWORD"
echo "keyAlias=$KEY_ALIAS"
echo "storeFile=qlyra-release.jks"
} > android/key.properties
echo "Release signing configured."
- name: Build Universal APK
run: flutter build apk --release --flavor store --obfuscate --split-debug-info=build/symbols
- name: Verify store manifest
shell: bash
run: |
set -euo pipefail
manifest=$(find build/app/intermediates -path '*storeRelease*' -path '*merged_manifests*' -name AndroidManifest.xml -print -quit)
test -n "$manifest"
if grep -Eq 'REQUEST_INSTALL_PACKAGES|android:host="(www\.)?max\.ru"|firebaseinitprovider' "$manifest"; then
echo '::error::Store manifest contains forbidden entries'
exit 1
fi
- name: Build Split APKs
run: flutter build apk --release --split-per-abi --flavor store --obfuscate --split-debug-info=build/symbols
- name: Verify APK release certificates
env:
KEYSTORE_PASSWORD: ${{ secrets.PLAY_KEYSTORE_PASSWORD || secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.PLAY_KEY_ALIAS || secrets.KEY_ALIAS }}
run: bash scripts/verify_android_signing.sh
- name: Upload Universal APK
uses: actions/upload-artifact@v4
with:
name: qlyra-play-universal
path: build/app/outputs/flutter-apk/app-store-release.apk
if-no-files-found: error
retention-days: 30
- name: Upload arm64-v8a APK
uses: actions/upload-artifact@v4
with:
name: qlyra-play-arm64-v8a
path: build/app/outputs/flutter-apk/app-arm64-v8a-store-release.apk
if-no-files-found: error
retention-days: 30
- name: Upload armeabi-v7a APK
uses: actions/upload-artifact@v4
with:
name: qlyra-play-armeabi-v7a
path: build/app/outputs/flutter-apk/app-armeabi-v7a-store-release.apk
if-no-files-found: error
retention-days: 30
- name: Upload x86_64 APK
uses: actions/upload-artifact@v4
with:
name: qlyra-play-x86_64
path: build/app/outputs/flutter-apk/app-x86_64-store-release.apk
if-no-files-found: error
retention-days: 30
- name: Build App Bundle
run: flutter build appbundle --release --flavor store --obfuscate --split-debug-info=build/symbols
- name: Verify App Bundle release certificate
env:
KEYSTORE_PASSWORD: ${{ secrets.PLAY_KEYSTORE_PASSWORD || secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.PLAY_KEY_ALIAS || secrets.KEY_ALIAS }}
run: bash scripts/verify_android_signing.sh
- name: Upload App Bundle artifact
uses: actions/upload-artifact@v4
with:
name: qlyra-play-aab
path: build/app/outputs/bundle/storeRelease/app-store-release.aab
if-no-files-found: error
retention-days: 30
- name: Upload debug symbols
uses: actions/upload-artifact@v4
with:
name: qlyra-play-symbols
path: build/symbols
if-no-files-found: error
retention-days: 90
+39 -8
View File
@@ -10,12 +10,10 @@ on:
- 'lib/**'
- 'android/**'
- 'pubspec.yaml'
- '.github/workflows/build-android.yml'
pull_request:
paths:
- 'lib/**'
- 'android/**'
- 'pubspec.yaml'
- 'pubspec.lock'
- 'native/**'
- 'third_party/**'
- 'scripts/verify_android_signing.sh'
- '.github/workflows/build-android.yml'
jobs:
@@ -49,6 +47,27 @@ jobs:
- name: Get dependencies
run: flutter pub get
- name: Verify formatting
run: dart format --output=none --set-exit-if-changed lib test
- name: Flutter analyze
run: flutter analyze --no-fatal-infos lib test
- name: Install native plugin build dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libclang-dev
- name: Prepare native plugin runtime for tests
run: dart run tool/prepare_plugin_runtime.dart
- name: Build native crypto test library
run: cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
- name: Flutter tests
run: flutter test
- name: Configure Gradle
run: |
mkdir -p ~/.gradle
@@ -66,8 +85,8 @@ jobs:
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
if [ -z "$KEYSTORE_BASE64" ]; then
echo "KEYSTORE_BASE64 secret not set — release will be debug-signed."
exit 0
echo "Release signing secrets are required."
exit 1
fi
echo "$KEYSTORE_BASE64" | base64 -d > android/app/qlyra-release.jks
{
@@ -84,6 +103,12 @@ jobs:
- name: Build Split APKs
run: flutter build apk --release --split-per-abi --flavor qlyra --obfuscate --split-debug-info=build/symbols
- name: Verify APK release certificates
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: bash scripts/verify_android_signing.sh
- name: Upload Universal APK
uses: actions/upload-artifact@v4
with:
@@ -119,6 +144,12 @@ jobs:
- name: Build App Bundle
run: flutter build appbundle --release --flavor qlyra --obfuscate --split-debug-info=build/symbols
- name: Verify App Bundle release certificate
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: bash scripts/verify_android_signing.sh
- name: Upload App Bundle artifact
uses: actions/upload-artifact@v4
with:
+46 -23
View File
@@ -37,8 +37,33 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Verify formatting
run: dart format --output=none --set-exit-if-changed lib test
- name: Flutter analyze
run: flutter analyze
run: flutter analyze --no-fatal-infos lib test
- name: Install native plugin build dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libclang-dev
- name: Prepare native plugin runtime for tests
run: dart run tool/prepare_plugin_runtime.dart
- name: Build native crypto test library
run: cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
- name: Flutter tests with coverage
run: flutter test --coverage
- name: Upload coverage
uses: actions/upload-artifact@v4
with:
name: flutter-dev-coverage
path: coverage/lcov.info
if-no-files-found: error
- name: Configure Gradle
run: |
@@ -49,28 +74,8 @@ jobs:
echo "org.gradle.parallel=true" >> ~/.gradle/gradle.properties
echo "org.gradle.configureondemand=true" >> ~/.gradle/gradle.properties
- name: Setup release signing
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
if [ -z "$KEYSTORE_BASE64" ]; then
echo "KEYSTORE_BASE64 secret not set — release will be debug-signed."
exit 0
fi
echo "$KEYSTORE_BASE64" | base64 -d > android/app/qlyra-release.jks
{
echo "storePassword=$KEYSTORE_PASSWORD"
echo "keyPassword=$KEY_PASSWORD"
echo "keyAlias=$KEY_ALIAS"
echo "storeFile=qlyra-release.jks"
} > android/key.properties
echo "Release signing configured."
- name: Build Android APK
run: flutter build apk --release --flavor qlyra
- name: Build debug APK
run: flutter build apk --debug --flavor qlyra
build-ios:
runs-on: macos-latest
@@ -96,6 +101,24 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Verify formatting
run: dart format --output=none --set-exit-if-changed lib test
- name: Install native plugin build dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libclang-dev
- name: Prepare native plugin runtime for tests
run: dart run tool/prepare_plugin_runtime.dart
- name: Build native crypto test library
run: cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
- name: Flutter tests
run: flutter test
- name: Build iOS (no codesign)
run: |
flutter config --no-enable-swift-package-manager
+28 -23
View File
@@ -36,8 +36,33 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Verify formatting
run: dart format --output=none --set-exit-if-changed lib test
- name: Flutter analyze
run: flutter analyze
run: flutter analyze --no-fatal-infos lib test
- name: Install native plugin build dependencies
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libclang-dev
- name: Prepare native plugin runtime for tests
run: dart run tool/prepare_plugin_runtime.dart
- name: Build native crypto test library
run: cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
- name: Flutter tests with coverage
run: flutter test --coverage
- name: Upload coverage
uses: actions/upload-artifact@v4
with:
name: flutter-main-coverage
path: coverage/lcov.info
if-no-files-found: error
- name: Configure Gradle
run: |
@@ -48,28 +73,8 @@ jobs:
echo "org.gradle.parallel=true" >> ~/.gradle/gradle.properties
echo "org.gradle.configureondemand=true" >> ~/.gradle/gradle.properties
- name: Setup release signing
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
if [ -z "$KEYSTORE_BASE64" ]; then
echo "KEYSTORE_BASE64 secret not set — release will be debug-signed."
exit 0
fi
echo "$KEYSTORE_BASE64" | base64 -d > android/app/qlyra-release.jks
{
echo "storePassword=$KEYSTORE_PASSWORD"
echo "keyPassword=$KEY_PASSWORD"
echo "keyAlias=$KEY_ALIAS"
echo "storeFile=qlyra-release.jks"
} > android/key.properties
echo "Release signing configured."
- name: Build Android APK
run: flutter build apk --release --flavor qlyra
- name: Build debug APK
run: flutter build apk --debug --flavor qlyra
linux:
runs-on: ubuntu-latest
+22
View File
@@ -0,0 +1,22 @@
name: Native crypto
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
jobs:
native-crypto:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: subosito/flutter-action@v2
with:
flutter-version: '3.44.3'
cache: true
- uses: dtolnay/rust-toolchain@stable
- run: flutter pub get
- run: cargo test --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
- run: cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
- run: flutter test --no-pub test/chat_crypto_roundtrip_test.dart test/outbox_queue_test.dart test/message_persistence_test.dart
+25
View File
@@ -0,0 +1,25 @@
name: Dependency Vulnerability Scan
on:
pull_request:
branches:
- main
- 'dev/**'
merge_group:
branches:
- main
schedule:
- cron: '30 2 * * 1'
workflow_dispatch:
permissions:
actions: read
contents: read
security-events: write
jobs:
scan:
uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@v2.5.0
with:
scan-args: |-
--lockfile=./pubspec.lock
+14 -2
View File
@@ -50,6 +50,12 @@ jobs:
- name: Get dependencies
run: flutter pub get
- name: Verify native crypto and message delivery
run: |
cargo test --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
flutter test --no-pub test/chat_crypto_roundtrip_test.dart test/outbox_queue_test.dart test/message_persistence_test.dart test/messages_delivery_test.dart
- name: Configure Gradle
run: |
mkdir -p ~/.gradle
@@ -67,8 +73,8 @@ jobs:
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
if [ -z "$KEYSTORE_BASE64" ]; then
echo "KEYSTORE_BASE64 secret not set — release will be debug-signed."
exit 0
echo "Release signing secrets are required."
exit 1
fi
echo "$KEYSTORE_BASE64" | base64 -d > android/app/qlyra-release.jks
{
@@ -96,6 +102,12 @@ jobs:
cp build/app/outputs/bundle/${F}Release/app-$F-release.aab dist/Qlyra-android-$F.aab
tar -czf dist/Qlyra-android-$F-symbols.tar.gz -C build/symbols .
- name: Verify APK release certificates
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: bash scripts/verify_android_signing.sh
- name: Upload Android artifacts (${{ matrix.flavor }})
uses: actions/upload-artifact@v4
with:
+14 -2
View File
@@ -45,6 +45,12 @@ jobs:
- name: Get dependencies
run: flutter pub get
- name: Verify native crypto and message delivery
run: |
cargo test --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
flutter test --no-pub test/chat_crypto_roundtrip_test.dart test/outbox_queue_test.dart test/message_persistence_test.dart test/messages_delivery_test.dart
- name: Configure Gradle
run: |
mkdir -p ~/.gradle
@@ -62,8 +68,8 @@ jobs:
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
if [ -z "$KEYSTORE_BASE64" ]; then
echo "KEYSTORE_BASE64 secret not set — release will be debug-signed."
exit 0
echo "Release signing secrets are required."
exit 1
fi
echo "$KEYSTORE_BASE64" | base64 -d > android/app/qlyra-release.jks
{
@@ -91,6 +97,12 @@ jobs:
cp build/app/outputs/bundle/${F}Release/app-$F-release.aab dist/Qlyra-android-$F.aab
tar -czf dist/Qlyra-android-$F-symbols.tar.gz -C build/symbols .
- name: Verify APK release certificates
env:
KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: bash scripts/verify_android_signing.sh
- name: Upload Android artifacts (${{ matrix.flavor }})
uses: actions/upload-artifact@v4
with:
+2
View File
@@ -151,3 +151,5 @@ test/live_server_probe_test.dart
pubspec_overrides.yaml
.cargo/
**/target/
.codex-temp/
+26
View File
@@ -0,0 +1,26 @@
# Android permission matrix
The machine-readable source of truth is [`tool/android_permissions.json`](tool/android_permissions.json). CI tests require every permission in the main Android manifest to have one owner, feature and trigger.
Triggers have these meanings:
- `user_action`: Android permission or settings UI may be requested only after a related tap, toggle or confirmed WebView prompt.
- `feature_enabled`: background behavior may start only after the user enables the feature.
- `active_feature`: the permission is used only while the related feature is active.
- `system`: install-time capability without a runtime prompt.
| Area | Permissions | User-visible entry point |
| --- | --- | --- |
| Transport | `INTERNET`, `ACCESS_NETWORK_STATE` | Login and normal messaging |
| Updates | `REQUEST_INSTALL_PACKAGES` | Confirmed update installation |
| Camera and audio | `CAMERA`, `RECORD_AUDIO`, `MODIFY_AUDIO_SETTINGS` | Attachment camera, voice/video note, QR scanner or call |
| Location | `ACCESS_FINE_LOCATION`, `ACCESS_COARSE_LOCATION` | Location attachment; legacy BLE contact exchange |
| Bluetooth and NFC | `BLUETOOTH*`, `NFC` | Contact exchange sheet |
| Notifications | `POST_NOTIFICATIONS`, `VIBRATE`, `WAKE_LOCK` | Notification settings or active notification feature |
| Foreground services | `FOREGROUND_SERVICE*` | Enabled FKM, active call, screen sharing, or audio playback started by the user |
| Background startup | `RECEIVE_BOOT_COMPLETED` | Previously enabled FKM only |
| Special settings | `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`, `USE_FULL_SCREEN_INTENT` | Separate confirmation in notification settings |
| Media library | `READ_EXTERNAL_STORAGE`, `READ_MEDIA_*` | Attachment picker or explicit save action |
| Contacts | `READ_CONTACTS` | Optional phonebook-name feature |
WebView camera, microphone and location requests additionally require an HTTPS allowlisted origin and a per-request confirmation dialog.
-101
View File
@@ -1,101 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project
Qlyra is a cross-platform Flutter messaging client (Android, iOS, macOS, Windows, Linux, Web) that communicates via a custom packet-based protocol with MessagePack serialization and Zstd compression.
## Commands
```bash
flutter pub get # install dependencies
flutter analyze # lint / static analysis
flutter run # run on connected device (default: qlyra flavor)
flutter run --flavor oneme -t lib/main.dart # run oneme flavor (FCM)
# Android builds (release builds use obfuscation; keep symbols to de-obfuscate crashes)
flutter build apk --release --flavor qlyra --obfuscate --split-debug-info=build/symbols
flutter build apk --release --split-per-abi --flavor qlyra --obfuscate --split-debug-info=build/symbols
flutter build appbundle --release --flavor qlyra --obfuscate --split-debug-info=build/symbols
# Other platforms
flutter build ios --release --no-codesign
flutter build macos --release
flutter build web --release
flutter build linux --release
flutter build windows --release
```
Android builds require **Java 17**. Gradle memory is configured to `-Xmx4096m`.
**Never run APK/AAB builds yourself** (`flutter build apk`, `flutter build appbundle`, gradle assemble tasks) — they are slow and the user builds them. Verify changes with `flutter analyze`; the build commands above are documentation only.
## Build Flavors
| Flavor | App ID | Notes |
|--------|--------|-------|
| `qlyra` | `ru.qlyra.app` | Default, no FCM |
| `oneme` | `ru.oneme.app` | FCM push notifications via Firebase |
Flavor-specific Android resources live in `android/app/src/qlyra/` and `android/app/src/oneme/`.
## Architecture
The codebase follows a strict layered architecture:
```
core/transport/ — raw socket I/O: connection, sender, receiver, dispatcher, proxy
core/protocol/ — Packet struct, opcode map, MessagePack + Zstd serialization
core/storage/ — SQLite (sqflite), secure token storage, spoofing service
core/push/ — FCM integration (oneme flavor only)
core/config/ — app config, proxy config, device presets, countries list
backend/api.dart — session lifecycle: connect, handshake, ping, auto-reconnect
backend/modules/ — feature modules: account, messages, chats, contacts, calls, folders
state/ — ChangeNotifier state classes consumed by the UI
models/ — plain data classes (User, Chat, Message, Call, Attachment, Session)
frontend/screens/ — full-page widgets grouped by feature (auth/, chats/, contacts/, calls/, profile/)
frontend/widgets/ — reusable components (message_bubble, chat_tile, avatar, etc.)
```
Data flow: UI → backend module → `api.dart` → transport layer → server.
Incoming packets: transport → dispatcher → backend module → state → UI rebuild.
## Key Conventions (from AGENTS.md)
- **No comments in code.** Write self-documenting code instead.
- **Use `showCustomNotification(context, 'text')`** for all user-facing notifications — never use SnackBars.
- When a fix can be done quickly with a hack or properly with a rewrite, **choose the proper rewrite**.
- Quality over quantity.
- **Never leave real data in test files**, including existing message contents or real IDs captured from requests. Use synthetic fixtures instead.
- **A button whose icon toggles between plain and slashed** (flash on/off, mic muted, sound, notifications) **must animate with a Lottie icon** — never swap two `Icon`s instantly. See *Animated icons* below.
## Animated icons
Everything in `assets/lottie/` is generated from the Material Symbols font by `tool/make_morph_icons.py` (stdlib-only Python, no deps). Never hand-edit the JSON — add a spec and re-run `python3 tool/make_morph_icons.py`.
| Kind | Spec list | Widget |
|------|-----------|--------|
| Morph between two glyphs | `SPECS` | `ComposerMorphIcon` |
| Plain ↔ slashed toggle | `SLASH_SPECS` | `LottieSlashIcon` |
A slash spec takes the plain and slashed codepoints; the generator lays both glyphs out as static layers and sweeps a mask across the diagonal, so the slash looks drawn on top of the icon. Pass `fill=1.0` when the button renders `Icon(..., fill: 1)` — contours are then taken from the `FILL=1` instance of the variable font.
`LottieSlashIcon` plays the asset forward when `slashed` turns true and backward when it turns false, so a single asset covers both directions. The older `AnimatedSlashIcon` (clip wipe over two glyphs) stays where it is already used; new buttons use the Lottie one.
## Localization
Two locales supported: English (`lib/l10n/app_en.arb`) and Russian (`lib/l10n/app_ru.arb`).
Generated code is in `lib/l10n/` (produced by `flutter gen-l10n` via `l10n.yaml`).
## CI/CD
Four GitHub Actions workflows in `.github/workflows/`:
- `flutter-dev.yml` — PR lint + Android build for dev branch
- `flutter-main.yml` — PR lint + all-platform builds for main branch
- `build-android.yml` — production APKs + AAB (`qlyra` flavor), triggered on push to main
- `build-android-fcm.yml` — production APKs + AAB (`oneme` flavor with FCM), triggered on push to main
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+36
View File
@@ -10,7 +10,43 @@
## Сборка из исходного кода
Используйте Flutter 3.44.3, Rust и Java 17 для Android. Перед запуском тестов
соберите нативную библиотеку шифрования:
```console
flutter pub get
cargo build --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
cargo test --locked --manifest-path native/qlyra_crypto/rust/Cargo.toml
flutter test --no-pub
flutter analyze --no-pub --no-fatal-infos lib test
```
Криптотесты требуют библиотеку для текущей ОС в
`native/qlyra_crypto/rust/target/debug`. Другой путь задаётся переменной
`QLYRA_CRYPTO_LIBRARY`. Отсутствие библиотеки считается ошибкой проверки.
Для release-сборки Android обязателен локальный `android/key.properties`
с полями `storeFile`, `storePassword`, `keyAlias`, `keyPassword`.
Используйте тот же ключ, которым подписана установленная версия.
Без ключа release-сборка останавливается. Для разработки доступна
`flutter build apk --debug --flavor qlyra`.
Release-варианты подключают Flutter JNI через Android Components API.
Перед удалением отладочных символов задача `verifyQlyraReleaseFlutterJni`
(или `verifyOnemeReleaseFlutterJni`) сверяет SHA-256 скомпилированных и
объединённых библиотек и останавливает упаковку при несовпадении.
```console
$ flutter build [windows|linux] [--release]
$ flutter build apk --release --flavor qlyra
```
Отправка текста проходит через `OutgoingText` и `OutboxQueue`: в БД сохраняются
подготовленный текст, постоянный `cid` и срок повторной попытки. При включённом
шифровании в очереди находится шифротекст. Подтверждение заменяет временную
запись одной транзакцией. Старые pending-записи без метаданных подготовки
получают статус ошибки и автоматически не отправляются.
`cid` сохраняется при повторе; серверная дедупликация зависит от реализации
сервера MAX. Локальные тесты моделируют потерю ответа и не заменяют проверку
этого поведения на сервере.
+2
View File
@@ -16,6 +16,8 @@ analyzer:
- windows/**
- macos/**
- linux/**
- native/**
- third_party/**
include: package:flutter_lints/flutter.yaml
linter:
+95 -4
View File
@@ -1,5 +1,12 @@
import java.util.Properties
import java.io.FileInputStream
import java.security.MessageDigest
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import javax.inject.Inject
plugins {
id("com.android.application")
@@ -10,12 +17,24 @@ plugins {
}
val keystoreProperties = Properties()
val keystorePropertiesFile = rootProject.file("key.properties")
val keystorePropertiesFile = rootProject.file(
providers.gradleProperty("releaseSigningProperties").getOrElse("key.properties")
)
val hasReleaseSigning = keystorePropertiesFile.exists()
if (hasReleaseSigning) {
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
}
gradle.taskGraph.whenReady {
if (allTasks.any { it.project == project && it.name.contains("Release", ignoreCase = true) }) {
check(hasReleaseSigning) { "Release signing requires android/key.properties" }
for (key in listOf("keyAlias", "keyPassword", "storeFile", "storePassword")) {
check(!keystoreProperties.getProperty(key).isNullOrBlank()) { "Missing release signing property: $key" }
}
check(file(keystoreProperties.getProperty("storeFile")).isFile) { "Release keystore does not exist" }
}
}
android {
namespace = "ru.qlyra.app"
compileSdk = flutter.compileSdkVersion
@@ -59,6 +78,10 @@ android {
isDefault = true
applicationId = "ru.qlyra.app"
}
create("store") {
dimension = "distribution"
applicationId = "ru.qlyra.app"
}
create("oneme") {
dimension = "distribution"
applicationId = "ru.oneme.app"
@@ -80,9 +103,7 @@ android {
release {
signingConfig = if (hasReleaseSigning) {
signingConfigs.getByName("release")
} else {
signingConfigs.getByName("debug")
}
} else null
}
}
@@ -97,6 +118,76 @@ flutter {
source = "../.."
}
abstract class StageFlutterJni : DefaultTask() {
@get:InputDirectory
abstract val inputDirectory: DirectoryProperty
@get:OutputDirectory
abstract val outputDirectory: DirectoryProperty
@get:Inject
abstract val fileSystem: FileSystemOperations
@TaskAction
fun stage() {
fileSystem.sync {
from(inputDirectory)
into(outputDirectory)
}
}
}
androidComponents {
onVariants(selector().withBuildType("release")) { variant ->
val variantName = variant.name
val capitalized = variantName.replaceFirstChar { it.uppercase() }
val stage = tasks.register<StageFlutterJni>("stage${capitalized}FlutterJni") {
dependsOn("copyJniLibsflutterBuild$capitalized")
inputDirectory.set(layout.buildDirectory.dir("intermediates/flutter/$variantName/jniLibs"))
outputDirectory.set(layout.buildDirectory.dir("intermediates/qlyra_flutter_jni/$variantName"))
}
variant.sources.jniLibs?.addGeneratedSourceDirectory(stage) { it.outputDirectory }
}
}
android.applicationVariants.all {
if (buildType.name == "release") {
val variantName = name
val capitalized = variantName.replaceFirstChar { it.uppercase() }
val generated = layout.buildDirectory.dir("intermediates/flutter/$variantName/jniLibs")
val merged = layout.buildDirectory.dir(
"intermediates/merged_native_libs/$variantName/merge${capitalized}NativeLibs/out/lib"
)
val verifyJni = tasks.register("verify${capitalized}FlutterJni") {
dependsOn("merge${capitalized}NativeLibs", "copyJniLibsflutterBuild$capitalized")
doLast {
val root = generated.get().asFile
val libraries = root.walkTopDown().filter { it.isFile && it.extension == "so" }.toList()
check(libraries.any { it.name == "libapp.so" }) { "Compiled Flutter library is missing" }
for (appLibrary in libraries.filter { it.name == "libapp.so" }) {
val abi = appLibrary.parentFile.name
val runtime = merged.get().asFile.resolve("$abi/libfjs.so")
check(runtime.isFile && runtime.length() > 0) {
"Plugin runtime is missing for $abi; inspect the fjs/cargokit build log"
}
}
for (library in libraries) {
val relative = library.relativeTo(root)
val packaged = merged.get().asFile.resolve(relative)
check(packaged.isFile) { "Flutter library was not merged: $relative" }
val expected = MessageDigest.getInstance("SHA-256").digest(library.readBytes())
val actual = MessageDigest.getInstance("SHA-256").digest(packaged.readBytes())
check(expected.contentEquals(actual)) { "Stale Flutter library in package: $relative" }
}
logger.lifecycle("Verified fresh Flutter JNI for $variantName (${libraries.size} libraries)")
}
}
tasks.matching { it.name == "strip${capitalized}DebugSymbols" }.configureEach {
dependsOn(verifyJni)
}
}
}
dependencies {
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
implementation("androidx.media3:media3-transformer:1.9.3")
+20 -12
View File
@@ -13,6 +13,7 @@
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION"/>
@@ -34,7 +35,7 @@
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
<application
android:label="Qlyra"
android:name="${applicationName}"
android:name="ru.qlyra.app.QlyraApplication"
android:enableOnBackInvokedCallback="true"
android:icon="@mipmap/ic_launcher">
<activity
@@ -60,21 +61,11 @@
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="https" android:host="max.ru"/>
<data android:scheme="https" android:host="www.max.ru"/>
<data android:scheme="http" android:host="max.ru"/>
<data android:scheme="http" android:host="www.max.ru"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="qlyra"/>
<data android:scheme="max"/>
</intent-filter>
<intent-filter android:label="@string/share_target_label">
<action android:name="android.intent.action.SEND"/>
@@ -112,6 +103,23 @@
android:name=".UploadForegroundService"
android:foregroundServiceType="dataSync"
android:exported="false" />
<service
android:name="com.ryanheise.audioservice.AudioService"
android:foregroundServiceType="mediaPlayback"
android:exported="true"
tools:ignore="Instantiatable">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
<receiver
android:name="com.ryanheise.audioservice.MediaButtonReceiver"
android:exported="true"
tools:ignore="Instantiatable">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
<service
android:name=".NfcHostApduService"
android:exported="true"
@@ -143,7 +151,7 @@
android:exported="false">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Maintains the app's own persistent connection to the messaging server so that message notifications are delivered on builds without Google Play Services" />
android:value="User-enabled option that keeps the app's own authenticated connection to the messaging service open solely to deliver incoming message and call notifications. Firebase Cloud Messaging cannot be used for this app: push delivery is operated by the third-party messaging service, which sends pushes only to its own FCM sender, so the app cannot receive them. The service is off by default, is started only after the user turns it on, carries a persistent notification, and can be stopped from that notification at any time." />
</service>
<receiver
android:name=".FkmDisableReceiver"
@@ -0,0 +1,202 @@
package ru.qlyra.app
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.OpenableColumns
import android.util.Log
import android.webkit.MimeTypeMap
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicLong
object ClipboardMedia {
private const val TAG = "ClipboardMedia"
private const val CHANNEL = "ru.qlyra.app/clipboard"
private const val CACHE_DIR = "clipboard_in"
private const val MAX_ITEMS = 20
private const val RETENTION_MS = 24L * 60L * 60L * 1000L
private const val MAX_NAME = 96
private val textualTypes = setOf(
ClipDescription.MIMETYPE_TEXT_PLAIN,
ClipDescription.MIMETYPE_TEXT_HTML,
ClipDescription.MIMETYPE_TEXT_URILIST,
ClipDescription.MIMETYPE_TEXT_INTENT,
)
private val executor = Executors.newSingleThreadExecutor()
private val handler = Handler(Looper.getMainLooper())
private val seq = AtomicLong(0L)
fun attach(engine: FlutterEngine, context: Context) {
val app = context.applicationContext
MethodChannel(engine.dartExecutor.binaryMessenger, CHANNEL)
.setMethodCallHandler { call, result ->
when (call.method) {
"hasMedia" -> result.success(hasMedia(app))
"read" -> read(app, result)
else -> result.notImplemented()
}
}
}
private fun clipboard(context: Context): ClipboardManager? =
context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
private fun hasMedia(context: Context): Boolean {
val description = try {
clipboard(context)?.primaryClipDescription
} catch (e: Exception) {
Log.w(TAG, "clipboard description unavailable: $e")
null
} ?: return false
for (index in 0 until description.mimeTypeCount) {
if (description.getMimeType(index) !in textualTypes) return true
}
return false
}
private fun read(context: Context, result: MethodChannel.Result) {
val clip = try {
clipboard(context)?.primaryClip
} catch (e: Exception) {
Log.w(TAG, "clipboard unavailable: $e")
null
}
if (clip == null || clip.itemCount == 0) {
result.success(null)
return
}
val uris = ArrayList<Uri>(clip.itemCount)
for (index in 0 until minOf(clip.itemCount, MAX_ITEMS)) {
val uri = clip.getItemAt(index).uri ?: continue
if (uri.scheme != ContentResolver.SCHEME_CONTENT &&
uri.scheme != ContentResolver.SCHEME_FILE
) {
continue
}
uris.add(uri)
}
if (uris.isEmpty()) {
result.success(null)
return
}
val declaredMime = clip.description?.getMimeType(0)
executor.execute {
val paths = materialize(context, uris, declaredMime)
handler.post { result.success(if (paths.isEmpty()) null else mapOf("files" to paths)) }
}
}
private fun materialize(context: Context, uris: List<Uri>, declaredMime: String?): List<String> {
val root = File(context.cacheDir, CACHE_DIR)
prune(root)
val paths = ArrayList<String>(uris.size)
for (uri in uris) {
val copied = copyToCache(context, root, uri, declaredMime) ?: continue
paths.add(copied)
}
return paths
}
private fun copyToCache(
context: Context,
root: File,
uri: Uri,
declaredMime: String?,
): String? {
val resolver = context.contentResolver
val dir = File(root, "${System.currentTimeMillis()}_${seq.incrementAndGet()}")
return try {
val mime = resolveMime(resolver, uri, declaredMime)
dir.mkdirs()
val target = File(dir, fileName(resolver, uri, mime))
resolver.openInputStream(uri).use { input ->
if (input == null) {
dir.deleteRecursively()
return null
}
target.outputStream().use { output -> input.copyTo(output) }
}
if (target.length() <= 0L) {
dir.deleteRecursively()
null
} else {
target.absolutePath
}
} catch (e: Exception) {
Log.w(TAG, "cannot read $uri: $e")
dir.deleteRecursively()
null
}
}
private fun resolveMime(resolver: ContentResolver, uri: Uri, declaredMime: String?): String {
val fromResolver = resolver.getType(uri)
if (!fromResolver.isNullOrBlank() && fromResolver != "*/*") return fromResolver
val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
if (!extension.isNullOrBlank()) {
val guessed = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.lowercase())
if (!guessed.isNullOrBlank()) return guessed
}
if (!declaredMime.isNullOrBlank() && declaredMime != "*/*") return declaredMime
return "application/octet-stream"
}
private fun fileName(resolver: ContentResolver, uri: Uri, mime: String): String {
val declared = queryDisplayName(resolver, uri)
?: uri.lastPathSegment?.substringAfterLast('/')
val base = sanitize(declared.orEmpty())
.ifEmpty { "paste_${System.currentTimeMillis()}" }
val current = base.substringAfterLast('.', "")
if (current.length in 1..5 && current.all { it.isLetterOrDigit() }) return base
val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime)
return if (extension.isNullOrBlank()) "$base.bin" else "$base.$extension"
}
private fun queryDisplayName(resolver: ContentResolver, uri: Uri): String? {
if (uri.scheme == ContentResolver.SCHEME_FILE) return uri.lastPathSegment
return try {
resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
if (index >= 0 && cursor.moveToFirst()) cursor.getString(index) else null
}
} catch (e: Exception) {
Log.w(TAG, "display name for $uri: $e")
null
}
}
private fun sanitize(name: String): String {
val cleaned = name
.replace(Regex("[\\\\/:*?\"<>|\\x00-\\x1F]"), "_")
.trim()
.trimStart('.')
return if (cleaned.length <= MAX_NAME) cleaned else cleaned.takeLast(MAX_NAME)
}
private fun prune(root: File) {
try {
if (!root.isDirectory) {
root.mkdirs()
return
}
val cutoff = System.currentTimeMillis() - RETENTION_MS
root.listFiles()?.forEach { entry ->
if (entry.lastModified() < cutoff) entry.deleteRecursively()
}
} catch (e: Exception) {
Log.w(TAG, "cache cleanup failed: $e")
}
}
}
@@ -23,9 +23,8 @@ import android.view.WindowManager
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import io.flutter.embedding.android.FlutterActivity
import com.ryanheise.audioservice.AudioServiceActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
@@ -49,8 +48,9 @@ import java.net.NetworkInterface
import java.util.Collections
import java.util.Random
import java.util.concurrent.atomic.AtomicBoolean
import java.security.MessageDigest
class MainActivity : FlutterActivity() {
class MainActivity : AudioServiceActivity() {
private val channelName = "ru.qlyra.app/vpn_bypass"
private val iconPackage = MainActivity::class.java.name.substringBeforeLast('.')
@@ -89,7 +89,6 @@ class MainActivity : FlutterActivity() {
const val LOG_TAG = "VpnBypass"
const val SHARE_TAG = "ShareIntake"
const val NFC_TAG = "NfcExchange"
const val KEEP_ENGINE_ID = "qlyra_keep_engine"
const val NFC_PHASE_MIN_MS = 350L
const val NFC_PHASE_JITTER_MS = 400
const val BLE_PERMS_REQUEST = 7711
@@ -121,9 +120,27 @@ class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
ClipboardMedia.attach(flutterEngine, applicationContext)
nfcAdapter = NfcAdapter.getDefaultAdapter(this)
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"ru.qlyra.app/update_integrity",
).setMethodCallHandler { call, result ->
when (call.method) {
"verifyApkSigner" -> {
val path = call.argument<String>("path")
if (path == null) {
result.error("INVALID_PATH", "APK path is required", null)
} else {
result.success(apkSignerMatchesInstalled(path))
}
}
else -> result.notImplemented()
}
}
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
"ru.qlyra.app/nfc",
@@ -515,6 +532,38 @@ class MainActivity : FlutterActivity() {
FkmChannel.attach(flutterEngine, this)
}
@Suppress("DEPRECATION")
private fun apkSignerMatchesInstalled(path: String): Boolean {
return try {
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
PackageManager.GET_SIGNING_CERTIFICATES
} else {
PackageManager.GET_SIGNATURES
}
val archive = packageManager.getPackageArchiveInfo(path, flags) ?: return false
if (archive.packageName != packageName) return false
val installed = packageManager.getPackageInfo(packageName, flags)
val archiveSigners = signerDigests(archive)
archiveSigners.isNotEmpty() && archiveSigners == signerDigests(installed)
} catch (_: Exception) {
false
}
}
@Suppress("DEPRECATION")
private fun signerDigests(info: android.content.pm.PackageInfo): Set<String> {
val signatures = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
info.signingInfo?.apkContentsSigners.orEmpty()
} else {
info.signatures.orEmpty()
}
return signatures.map { signature ->
MessageDigest.getInstance("SHA-256")
.digest(signature.toByteArray())
.joinToString("") { byte -> "%02x".format(byte) }
}.toSet()
}
override fun onCreate(savedInstanceState: Bundle?) {
if (intent?.hasExtra(CallConst.EXTRA_CALL) == true) applyCallWindowFlags()
super.onCreate(savedInstanceState)
@@ -941,33 +990,21 @@ class MainActivity : FlutterActivity() {
// в обоих случаях в фоне должно жить то же соединение, что и в UI.
private fun keepEngineAlive(): Boolean = CallState.inCall || FkmState.enabled
override fun provideFlutterEngine(context: Context): FlutterEngine? {
val cache = FlutterEngineCache.getInstance()
val cached = cache.get(KEEP_ENGINE_ID)
if (cached != null) {
if (keepEngineAlive()) return cached
cache.remove(KEEP_ENGINE_ID)
cached.destroy()
}
return super.provideFlutterEngine(context)
}
override fun shouldDestroyEngineWithHost(): Boolean = !keepEngineAlive()
// Движок общий с audio_service (AudioServiceActivity.provideFlutterEngine), и
// уничтожает его AudioServicePlugin.disposeFlutterEngine, когда останавливается
// медиа-сервис. Активити не должна рвать его из-под сервиса.
override fun shouldDestroyEngineWithHost(): Boolean = false
override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
if (!keepEngineAlive()) {
FlutterEngineCache.getInstance().remove(KEEP_ENGINE_ID)
FkmChannel.detach()
ChatNotifications.activeChatId = 0L
}
super.cleanUpFlutterEngine(flutterEngine)
}
override fun onDestroy() {
shareExecutor.shutdown()
if (keepEngineAlive() && isFinishing) {
Log.d("QlyraFcm", "task removed, caching engine (call=${CallState.inCall} fkm=${FkmState.enabled})")
flutterEngine?.let { FlutterEngineCache.getInstance().put(KEEP_ENGINE_ID, it) }
}
super.onDestroy()
}
@@ -0,0 +1,20 @@
package ru.qlyra.app
import android.app.Application
import com.ryanheise.audioservice.AudioServicePlugin
// id движка audio_service обязан быть выставлен до создания первого FlutterEngine.
// Создаёт его не только активити: AudioService поднимает движок сам, когда система
// стартует сервис по кнопке на гарнитуре. Выставленный позже id даёт второй движок —
// второй изолят со своим соединением и своей сессией БД.
class QlyraApplication : Application() {
override fun onCreate() {
super.onCreate()
AudioServicePlugin.setFlutterEngineId(ENGINE_ID)
}
companion object {
const val ENGINE_ID = "qlyra_keep_engine"
}
}
+15
View File
@@ -0,0 +1,15 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="https" android:host="max.ru"/>
<data android:scheme="https" android:host="www.max.ru"/>
<data android:scheme="http" android:host="max.ru"/>
<data android:scheme="http" android:host="www.max.ru"/>
</intent-filter>
</activity>
</application>
</manifest>
+11
View File
@@ -18,5 +18,16 @@
<receiver
android:name="io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingReceiver"
tools:node="remove" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="https" android:host="max.ru"/>
<data android:scheme="https" android:host="www.max.ru"/>
<data android:scheme="http" android:host="max.ru"/>
<data android:scheme="http" android:host="www.max.ru"/>
</intent-filter>
</activity>
</application>
</manifest>
+23
View File
@@ -0,0 +1,23 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" tools:node="remove"/>
<application>
<provider
android:name="com.google.firebase.provider.FirebaseInitProvider"
android:authorities="${applicationId}.firebaseinitprovider"
tools:node="remove" />
<provider
android:name="io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingInitProvider"
android:authorities="${applicationId}.flutterfirebasemessaginginitprovider"
tools:node="remove" />
<service
android:name="com.google.firebase.messaging.FirebaseMessagingService"
tools:node="remove" />
<service
android:name="io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingService"
tools:node="remove" />
<receiver
android:name="io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingReceiver"
tools:node="remove" />
</application>
</manifest>
@@ -0,0 +1,29 @@
{
"project_info": {
"project_number": "659634599081",
"project_id": "max-messenger-app",
"storage_bucket": "max-messenger-app.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:659634599081:android:00000000000000000000ab",
"android_client_info": {
"package_name": "ru.qlyra.app"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyABuDYeeDXIOrKTXLkUj30Ii143ofPe63Q"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
],
"configuration_version": "1"
}
+29
View File
@@ -0,0 +1,29 @@
import { chat, contact, runtime, ui } from 'komet:api';
function date(value) {
if (!Number.isInteger(value) || value <= 0) return '—';
return new Date(value).toLocaleString();
}
export async function info() {
if (!(await runtime.isOnline())) {
await ui.notify('Нет соединения');
return;
}
const id = await chat.sendText('сбор данных...');
const peer = await contact.getPeer();
if (!peer) {
await chat.editText(id, 'Команда доступна только в диалоге');
return;
}
const summary = [
`Никнейм: ${peer.displayName || '—'}`,
`Дата регистрации: ${date(peer.registrationTime)}`,
`Дата последнего изменения профиля: ${date(peer.updateTime)}`,
`id: ${peer.id}`,
`Регион: ${peer.country || '—'}`,
`Флаги: ${peer.options.length ? peer.options.join(', ') : '—'}`,
'ip: not fetched'
].join('\n');
await chat.editText(id, summary);
}
+14
View File
@@ -0,0 +1,14 @@
{
"schemaVersion": 1,
"id": "pw.qlyra.info",
"name": "Qlyra Info",
"version": "1.0.0",
"apiVersion": 1,
"description": "Сводка данных о собеседнике",
"author": "Qlyra",
"main": "main.js",
"permissions": ["chat.write", "chat.edit", "ui.notify", "contact.read"],
"commands": [
{"name": "/info", "description": "сводка данных о человеке", "handler": "info"}
]
}
+1
View File
@@ -0,0 +1 @@
+33
View File
@@ -0,0 +1,33 @@
import { chat, network, ui } from 'komet:api';
export async function nekogirl() {
const response = await network.fetch('https://api.nekosapi.com/v4/images/random?rating=safe', {
headers: { Accept: 'application/json' }
});
if (response.status !== 200) {
await ui.notify(`Nekogirl вернул HTTP ${response.status}`);
return;
}
let data;
try {
data = JSON.parse(response.body);
} catch (_) {
await ui.notify('Nekogirl вернул некорректный ответ');
return;
}
if (typeof data[0].url !== 'string' || !data[0].url.startsWith('https://')) {
await ui.notify('Nekogirl не вернул ссылку на изображение');
return;
}
const filename = data[0].url.split('/').pop() || 'nekogirl.jpg';
const source = data[0].url;
await chat.sendPhoto({
url: data[0].url,
filename,
caption: `Случайная кошкодевочкa`
});
}
+1
View File
@@ -0,0 +1 @@
{"schemaVersion":1,"id":"pw.qlyra.nekos","name":"Qlyra Nekos","version":"1.0.0","apiVersion":1,"description":"Случайные картинки кошкодевочек через nekosapi.com","author":"nyakokitsu","main":"main.js","permissions":["network","chat.photo","chat.write","ui.notify"],"commands":[{"name":"/nekogirl","description":"отправить случайную картинку кошкодевочки","handler":"nekogirl"}]}
+63
View File
@@ -0,0 +1,63 @@
import { chat, network, ui } from 'komet:api';
function value(source, key, fallback = '—') {
const result = source?.[key];
return result === undefined || result === null || result === '' ? fallback : String(result);
}
function description(source) {
return source?.weatherDesc?.[0]?.value || '—';
}
function dayLabel(date, index) {
if (index === 0) return 'Сегодня';
if (index === 1) return 'Завтра';
return date || `День ${index + 1}`;
}
export async function weather(context) {
const city = context.arguments.city.trim();
const url = `https://wttr.in/${encodeURIComponent(city)}?format=j1&lang=ru`;
const response = await network.fetch(url, {
headers: { Accept: 'application/json' }
});
if (response.status !== 200) {
await ui.notify(`wttr.in вернул HTTP ${response.status}`);
return;
}
let data;
try {
data = JSON.parse(response.body);
} catch (_) {
await ui.notify('wttr.in вернул некорректный ответ');
return;
}
const current = data.current_condition?.[0];
const area = data.nearest_area?.[0];
if (!current) {
await ui.notify('Погода для этого города не найдена');
return;
}
const place = area?.areaName?.[0]?.value || city;
const country = area?.country?.[0]?.value;
const lines = [
`Погода: ${place}${country ? `, ${country}` : ''}`,
`${description(current)}, ${value(current, 'temp_C')} °C`,
`Ощущается как ${value(current, 'FeelsLikeC')} °C`,
`Влажность ${value(current, 'humidity')}% · ветер ${value(current, 'windspeedKmph')} км/ч`,
'',
'Прогноз:'
];
for (const [index, day] of (data.weather || []).slice(0, 3).entries()) {
const noon = day.hourly?.find(item => item.time === '1200') || day.hourly?.[4] || day.hourly?.[0];
lines.push(
`${dayLabel(day.date, index)}: ${description(noon)}, ${value(day, 'mintempC')}${value(day, 'maxtempC')} °C`
);
}
await chat.sendText(lines.join('\n'));
}
+21
View File
@@ -0,0 +1,21 @@
{
"schemaVersion": 1,
"id": "pw.qlyra.weather",
"name": "Qlyra Weather",
"version": "1.0.0",
"apiVersion": 1,
"description": "Текущая погода и прогноз через wttr.in",
"author": "Qlyra",
"main": "main.js",
"permissions": ["chat.write", "ui.notify", "network"],
"commands": [
{
"name": "/weather",
"description": "погода и прогноз для города",
"handler": "weather",
"arguments": [
{"name": "city", "description": "название города", "rest": true}
]
}
]
}
+4
View File
@@ -15,6 +15,7 @@
AA11BB22CC33DD44EE550101 /* QlyraVideo.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA11BB22CC33DD44EE550001 /* QlyraVideo.swift */; };
AA11BB22CC33DD44EE550102 /* QlyraVideoNote.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA11BB22CC33DD44EE550002 /* QlyraVideoNote.swift */; };
AA11BB22CC33DD44EE550103 /* QlyraNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA11BB22CC33DD44EE550003 /* QlyraNotifications.swift */; };
AA11BB22CC33DD44EE550105 /* QlyraClipboard.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA11BB22CC33DD44EE550005 /* QlyraClipboard.swift */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
@@ -62,6 +63,7 @@
AA11BB22CC33DD44EE550001 /* QlyraVideo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QlyraVideo.swift; sourceTree = "<group>"; };
AA11BB22CC33DD44EE550002 /* QlyraVideoNote.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QlyraVideoNote.swift; sourceTree = "<group>"; };
AA11BB22CC33DD44EE550003 /* QlyraNotifications.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QlyraNotifications.swift; sourceTree = "<group>"; };
AA11BB22CC33DD44EE550005 /* QlyraClipboard.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QlyraClipboard.swift; sourceTree = "<group>"; };
AA11BB22CC33DD44EE550004 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; };
782E66FE4E292DCFD0D1B7D2 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = "<group>"; };
789A1AEF2F4FF7DEED202476 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -167,6 +169,7 @@
AA11BB22CC33DD44EE550001 /* QlyraVideo.swift */,
AA11BB22CC33DD44EE550002 /* QlyraVideoNote.swift */,
AA11BB22CC33DD44EE550003 /* QlyraNotifications.swift */,
AA11BB22CC33DD44EE550005 /* QlyraClipboard.swift */,
AA11BB22CC33DD44EE550004 /* Runner.entitlements */,
);
path = Runner;
@@ -410,6 +413,7 @@
AA11BB22CC33DD44EE550101 /* QlyraVideo.swift in Sources */,
AA11BB22CC33DD44EE550102 /* QlyraVideoNote.swift in Sources */,
AA11BB22CC33DD44EE550103 /* QlyraNotifications.swift in Sources */,
AA11BB22CC33DD44EE550105 /* QlyraClipboard.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
+7
View File
@@ -43,6 +43,7 @@ final class QlyraStreamHandler: NSObject, FlutterStreamHandler {
registerVideoNote(messenger)
registerNotifications(messenger)
registerScreen(messenger)
registerClipboard(messenger)
}
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
@@ -166,6 +167,12 @@ final class QlyraStreamHandler: NSObject, FlutterStreamHandler {
}
}
private func registerClipboard(_ messenger: FlutterBinaryMessenger) {
method("ru.qlyra.app/clipboard", messenger) { call, result in
QlyraClipboard.handle(call, result: result)
}
}
private func registerNotifications(_ messenger: FlutterBinaryMessenger) {
method("ru.qlyra.app/notifications", messenger) { call, result in
QlyraNotifications.shared.handle(call, result: result)
+115
View File
@@ -0,0 +1,115 @@
import Flutter
import UIKit
enum QlyraClipboard {
private static let cacheDirectory = "clipboard_in"
private static let retention: TimeInterval = 24 * 60 * 60
private static let recodeQuality: CGFloat = 0.95
private static let passthrough: [(type: String, ext: String)] = [
("public.png", "png"),
("public.jpeg", "jpg"),
("com.compuserve.gif", "gif"),
("org.webmproject.webp", "webp"),
]
static func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "hasMedia":
result(UIPasteboard.general.hasImages)
case "read":
read(result)
default:
result(FlutterMethodNotImplemented)
}
}
private static func read(_ result: @escaping FlutterResult) {
let pasteboard = UIPasteboard.general
guard pasteboard.hasImages else {
result(nil)
return
}
let items = pasteboard.items
DispatchQueue.global(qos: .userInitiated).async {
let images = items.compactMap(image(in:))
let paths = images.isEmpty ? [] : store(images)
DispatchQueue.main.async {
result(paths.isEmpty ? nil : ["files": paths])
}
}
}
private static func image(in item: [String: Any]) -> (data: Data, ext: String)? {
for entry in passthrough {
guard let data = item[entry.type] as? Data, !data.isEmpty else { continue }
return (data, entry.ext)
}
for value in item.values {
if let image = value as? UIImage, let jpeg = recoded(image) {
return (jpeg, "jpg")
}
if let data = value as? Data,
let image = UIImage(data: data),
let jpeg = recoded(image) {
return (jpeg, "jpg")
}
}
return nil
}
private static func recoded(_ image: UIImage) -> Data? {
guard let jpeg = image.jpegData(compressionQuality: recodeQuality), !jpeg.isEmpty else {
return nil
}
return jpeg
}
private static func store(_ images: [(data: Data, ext: String)]) -> [String] {
guard let root = cacheRoot() else { return [] }
prune(root)
let stamp = Int(Date().timeIntervalSince1970 * 1000)
var paths: [String] = []
for (index, payload) in images.enumerated() {
let file = root.appendingPathComponent("paste_\(stamp)_\(index).\(payload.ext)")
do {
try payload.data.write(to: file, options: .atomic)
paths.append(file.path)
} catch {
NSLog("QlyraClipboard: cannot store a pasted image: \(error)")
}
}
return paths
}
private static func cacheRoot() -> URL? {
let manager = FileManager.default
guard let caches = manager.urls(for: .cachesDirectory, in: .userDomainMask).first else {
return nil
}
let root = caches.appendingPathComponent(cacheDirectory, isDirectory: true)
do {
try manager.createDirectory(at: root, withIntermediateDirectories: true)
} catch {
NSLog("QlyraClipboard: cannot create the paste cache: \(error)")
return nil
}
return root
}
private static func prune(_ root: URL) {
let manager = FileManager.default
let cutoff = Date().addingTimeInterval(-retention)
guard let entries = try? manager.contentsOfDirectory(
at: root,
includingPropertiesForKeys: [.contentModificationDateKey]
) else { return }
for entry in entries {
let values = try? entry.resourceValues(forKeys: [.contentModificationDateKey])
if let modified = values?.contentModificationDate, modified > cutoff { continue }
try? manager.removeItem(at: entry)
}
}
}
+97 -54
View File
@@ -1,8 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:kusoft/kusoft.dart';
import 'package:timezone/data/latest_all.dart' as tz;
@@ -10,6 +8,7 @@ import 'package:timezone/data/latest_all.dart' as tz;
import '../core/cache/self_presence.dart';
import '../core/config/config.dart';
import '../core/config/countries.dart';
import '../core/config/device_profile.dart';
import '../core/config/qlyra_settings.dart';
import '../core/config/proxy_config.dart';
import '../core/protocol/opcode_map.dart';
@@ -20,25 +19,24 @@ import '../core/transport/dispatcher.dart';
import '../core/transport/tls_config.dart';
import '../core/transport/traffic_monitor.dart';
import '../core/transport/vpn_bypass.dart';
import '../core/utils/app_foreground.dart';
import '../core/utils/debug_session_log.dart';
import '../core/utils/device_locale.dart';
import '../core/utils/logger.dart';
// #***! состояния сеськи
enum SessionState { disconnected, connecting, connected, online }
/// Клиент API.
///
/// Тонкий адаптер над Rust-ядром [KusoftSession] (пакет kusoft): подключение,
/// хэндшейк, пинг и реконнект живут в ядре, здесь — оркестрация жизненного цикла
/// и сохранение прежнего интерфейса для модулей (Packet/пуши/стримы).
// #***! весь жизненный цикл соединения
/// Клиент API
class Api {
KusoftSession? _session;
/// Роутер пушей (ответы на запросы ядро матчит само, диспетчер держим только
/// ради registerHandler/pushStream).
final PacketDispatcher _dispatcher = PacketDispatcher();
StreamSubscription<(int, Map<String, dynamic>)>? _pushSub;
StreamSubscription<WireLogEvent>? _wireLogSub;
// #***! текущее состояние плюс четыре стрима наружу на которые юишка подписана
SessionState _sessionState = SessionState.disconnected;
final _stateController = StreamController<SessionState>.broadcast();
final _sessionExpiredController =
@@ -49,6 +47,7 @@ class Api {
Map<dynamic, dynamic>? _userAgent;
Map<dynamic, dynamic>? get userAgent => _userAgent;
// #***! полезные данные после логина кому то нужные
int? _callsSeed;
String? _deviceId;
String? _callsDevice;
@@ -59,7 +58,7 @@ class Api {
String? get callsDevice => _callsDevice;
String? get callsOsVersion => _callsOsVersion;
/// Сырой доступ к сессии ядра — для медиа-загрузок (data-plane).
/// Сырой доступ к сессии для медиа загрузок
KusoftSession? get session => _session;
String? spoofScope;
@@ -79,39 +78,49 @@ class Api {
Stream<String> get errorStream => _errorController.stream;
SessionState get state => _sessionState;
// #***! таймеры и счётчики автореконнекта
Timer? _livenessTimer;
Timer? _reconnectTimer;
Timer? _connectWatchdog;
// #***! поколение попытки конекта
int _connectGen = 0;
int _reconnectAttempts = 0;
bool _autoReconnect = false;
int _sessionEpoch = 0;
bool? _lastInteractive;
// #***! тайминги
static const Duration _connectWatchdogTimeout = Duration(seconds: 75);
static const Duration _shouldArmTimeout = Duration(seconds: 5);
static const Duration _endpointTimeout = Duration(seconds: 5);
static const Duration _livenessInterval = Duration(seconds: 5);
static const int _foregroundReconnectCapSec = 15;
static const int _backgroundReconnectCapSec = 60;
int get sessionEpoch => _sessionEpoch;
// Публичное API
/// Подключается к серверу, шлёт хэндшейк, запускает пинг.
// #***!сокет, хэндшейк, пинг, автологин
/// Подключается к серверу и хендшейк шлет
Future<void> connect() async {
if (_sessionState != SessionState.disconnected) {
logger.i('connect пропущен: состояние ${_sessionState.name}');
return;
}
_autoReconnect = true;
// #***! номер поколения
final gen = ++_connectGen;
_setSessionState(SessionState.connecting);
logger.i('connect: старт (поколение $gen)');
// #***! Сторож если конект залип на всякий
_armConnectWatchdog(gen);
KusoftSession? built;
try {
bool useBypass;
try {
// #***! Если обход впн подвиснет нахуй пойдет
useBypass = await VpnBypassService.instance.shouldArm().timeout(
_shouldArmTimeout,
);
@@ -137,6 +146,7 @@ class Api {
setTrustMincifryCa(enabled: endpoint.trustMincifryCa);
final (session, wireLog) = await _buildSessionOptions(endpoint);
built = session;
if (gen != _connectGen) return;
logger.i(
@@ -152,9 +162,9 @@ class Api {
}
_session = session;
// Подписываемся на wire-лог ядра ДО connect(), чтобы поймать пакеты
// SESSION_INIT-хендшейка (иначе они уходят до listen и теряются).
_wireLogSub?.cancel();
_wireLogSub = wireLog.listen(_onWireLog);
_pushSub?.cancel();
_pushSub = session.pushesMap().listen(_onPush);
TrafficMonitor.instance.recordEvent(
'connect',
@@ -164,6 +174,7 @@ class Api {
_setSessionState(SessionState.connected);
_reconnectAttempts = 0;
// #***! Сервер отвечает кто мы для него💔
HandshakeInfo info;
try {
logger.i('connect: сокет готов, отправляю хэндшейк');
@@ -188,6 +199,7 @@ class Api {
_cancelConnectWatchdog();
_startLiveness();
logger.i('Сессия онлайн, хэндшейк ок');
// #***! автологин токеном
if (_onReconnectCallback != null) {
try {
await _onReconnectCallback!();
@@ -202,9 +214,13 @@ class Api {
} catch (e, st) {
logger.e('connect: непредвиденная ошибка: $e\n$st');
if (gen == _connectGen) await _resetStuckConnect(gen);
} finally {
// #***! на случай если несколько раз подключиться решили
if (built != null && !identical(_session, built)) _releaseSession(built);
}
}
// #***! сторож коннекта
void _armConnectWatchdog(int gen) {
_connectWatchdog?.cancel();
_connectWatchdog = Timer(_connectWatchdogTimeout, () {
@@ -226,6 +242,7 @@ class Api {
_connectWatchdog = null;
}
// #***! принудительный сброс
Future<void> _resetStuckConnect(int gen) async {
if (gen != _connectGen) return;
_connectGen++;
@@ -248,6 +265,7 @@ class Api {
}
}
// #***! ручное отключение
/// Отключается без автореконнекта.
Future<void> disconnect() async {
_autoReconnect = false;
@@ -257,6 +275,7 @@ class Api {
_setSessionState(SessionState.disconnected);
}
// #***! вернулись с свертывания если оффлайн коннектимся, если онлайн проверяем живость
void wakeUp() {
if (!_autoReconnect) return;
switch (_sessionState) {
@@ -272,7 +291,6 @@ class Api {
}
}
/// Отправляет запрос и ждёт ответ от сервера.
Future<Packet> sendRequest(
int opcode,
Map<dynamic, dynamic> payload, {
@@ -282,8 +300,7 @@ class Api {
if (session == null) {
throw StateError('Нет соединения (${Opcode.name(opcode)})');
}
// Лог запроса/ответа ведётся из wire-лога ядра (_onWireLog) по настоящему
// проводному seq, поэтому здесь ничего не пишем.
final KusoftResponse resp = await session
.requestMapFull(opcode, Map<String, dynamic>.from(payload))
.timeout(
@@ -298,6 +315,7 @@ class Api {
payload: resp.payload,
);
// #***! единственное место где протухший токен уезжает в sessionExpiredStream
if (packet.isError) {
if (isSessionExpiredPayload(packet.payload)) {
final ex = SessionExpiredException(
@@ -340,19 +358,21 @@ class Api {
return response;
}
/// Вешает обработчик на пуши с указанным опкодом.
// #***! модули бэкенда подписываются на свои пуши
/// Вешается😘 обработчик на пуши с указанным опкодом
void registerPushHandler(int opcode, void Function(Packet) handler) {
_dispatcher.registerHandler(opcode, handler);
}
/// Снимает обработчик пушей с указанного опкода.
/// Снимает обработчик пушей с опкода
void unregisterPushHandler(int opcode) {
_dispatcher.unregisterHandler(opcode);
}
/// Стрим всех входящих пушей от сервера.
/// Стрим всех входящих пушей
Stream<Packet> get pushStream => _dispatcher.pushStream;
// #***! закрытие всего
Future<void> dispose() async {
_autoReconnect = false;
_reconnectTimer?.cancel();
@@ -366,58 +386,40 @@ class Api {
// Внутрянка
/// Строит устройство-поля и создаёт сессию ядра. Заодно заполняет
/// [_userAgent] и [_deviceId] для геттеров.
// #***! сборка полей устройства для хэндшейка и создание сессии ядра. СПУФ <------
Future<(KusoftSession, Stream<WireLogEvent>)> _buildSessionOptions(
({String host, int port, bool trustMincifryCa}) endpoint,
) async {
final deviceInfo = DeviceInfoPlugin();
final device = await DeviceProfile.load();
String deviceType = 'ANDROID';
String osVersion = '';
String deviceName = 'Unknown';
String osVersion = device.osVersion;
String deviceName = device.deviceName;
String architecture = 'arm64-v8a';
String appVersion = SpoofingService.hardcodedAppVersion;
int buildNumber = SpoofingService.hardcodedBuildNumber;
String screen = '420dpi 420dpi 1080x2340';
// #***! таймзона инициалализацириуется один раз
if (!_tzInitialized) {
tz.initializeTimeZones();
_tzInitialized = true;
}
final timeZoneName = await FlutterTimezone.getLocalTimezone();
String timezone = timeZoneName.identifier;
String locale = 'ru';
String deviceLocale = Platform.localeName.substring(0, 2);
String locale = defaultLanguageCode;
String deviceLocale = deviceLanguageCode();
String deviceId = await DeviceIdentity.deviceId();
String pushDeviceType = 'GCM';
String instanceId = await DeviceIdentity.instanceId();
int clientSessionId = DeviceIdentity.clientSessionId;
String? androidManufacturer;
String? androidModel;
int? androidSdkInt;
if (Platform.isLinux) {
final linuxInfo = await deviceInfo.linuxInfo;
osVersion = linuxInfo.name;
} else if (Platform.isIOS) {
final iosInfo = await deviceInfo.iosInfo;
osVersion = iosInfo.systemVersion;
deviceName = iosInfo.utsname.machine;
} else if (Platform.isAndroid) {
final androidInfo = await deviceInfo.androidInfo;
osVersion = 'Android ${androidInfo.version.release}';
deviceName = '${androidInfo.manufacturer} ${androidInfo.model}';
androidManufacturer = androidInfo.manufacturer;
androidModel = androidInfo.model;
androidSdkInt = androidInfo.version.sdkInt;
} else if (Platform.isWindows) {
final windowsInfo = await deviceInfo.windowsInfo;
osVersion = windowsInfo.productName;
}
final androidManufacturer = device.manufacturer;
final androidModel = device.model;
final androidSdkInt = device.sdkInt;
String? spoofUserAgent;
// #***! включена подмена, накрываем реальные значения спуфом
final spoofed = await SpoofingService.getSpoofedSessionData(
scope: spoofScope,
);
@@ -464,6 +466,7 @@ class Api {
if (sClientSession is int) clientSessionId = sClientSession;
}
// #***! звонкам нужен формат производитель/модель и номер SDK
_callsDevice = _resolveCallsDevice(
spoofed: spoofed != null,
deviceName: deviceName,
@@ -477,6 +480,7 @@ class Api {
sdkInt: androidSdkInt,
);
// #***! то же самое мапом для отладочного экрана
_userAgent = {
'deviceType': deviceType,
'appVersion': appVersion,
@@ -495,6 +499,7 @@ class Api {
final insecureTls = await TlsConfig.isInsecureAllowed();
final proxy = await _buildProxyUrl();
// #***! тут реально открывается сокет в расте
return openSessionWithWireLog(
host: endpoint.host,
port: endpoint.port,
@@ -520,6 +525,7 @@ class Api {
);
}
// #***! звонкам нужен вид Samsung/SM-G991B, при спуфе собираем из подменённого
static String? _resolveCallsDevice({
required bool spoofed,
required String deviceName,
@@ -544,6 +550,7 @@ class Api {
'${_modelFromUserAgent(spoofUserAgent) ?? fallbackModel}';
}
// #***! модель телефона выдираем из юзерагента регуляркой
static String? _modelFromUserAgent(String? userAgent) {
if (userAgent == null || userAgent.isEmpty) return null;
final match = RegExp(r'Android\s+[\d.]+;\s*([^;)]+)').firstMatch(userAgent);
@@ -554,6 +561,7 @@ class Api {
return model == null || model.isEmpty ? null : model;
}
// #***! звонки хотят номер SDK а не Android 14
static String _resolveCallsOsVersion({
required bool spoofed,
required String osVersion,
@@ -566,6 +574,7 @@ class Api {
return '${_androidSdkForRelease(int.tryParse(release ?? ''))}';
}
// #***! таблица релиз -> уровень API
static int _androidSdkForRelease(int? release) => switch (release) {
null => 34,
<= 9 => 28,
@@ -578,6 +587,7 @@ class Api {
_ => 36,
};
// #***! прокси в строку socks5h://user:pass@host:port
static Future<String?> _buildProxyUrl() async {
final p = await ProxyConfig.load();
if (!p.isEnabled) return null;
@@ -589,6 +599,7 @@ class Api {
return '$scheme://$auth${p.host}:${p.port}';
}
// #***! пуш из ядра заворачиваем в Packet и в диспетчер
void _onPush((int, Map<String, dynamic>) event) {
final packet = Packet(
cmd: CmdType.push,
@@ -599,11 +610,14 @@ class Api {
_dispatcher.dispatch(packet);
}
// #***! весь лог трафика отсюда, ядро отдаёт обе стороны с настоящим seq
/// Единый источник лога трафика: ядро отдаёт сюда каждый пакет обеих сторон —
/// включая SESSION_INIT-хендшейк и пинги — с настоящим проводным seq. Раньше
/// лог вёлся вручную из [sendRequest] по локальному счётчику, из-за чего
/// хендшейк/пинги в дамп не попадали, а seq был смещён относительно провода.
void _onWireLog(WireLogEvent e) {
// #***! в фоне и без монитора не тратим время на разбор
if (!AppForeground.value && !TrafficMonitor.instance.enabled) return;
final payload = _decodeWireJson(e.json);
final cmd = _wireCmdCode(e.cmd);
if (e.direction == 'out') {
@@ -642,6 +656,7 @@ class Api {
}
}
// #***! смена состояния с оповещением
void _setSessionState(SessionState state) {
if (_sessionState == state) return;
_sessionState = state;
@@ -649,6 +664,7 @@ class Api {
logger.i('Сессия: ${state.name}');
}
// #***! разрыв, чистимся и планируем реконнект
void _onDisconnected() {
_connectGen++;
_cleanup();
@@ -656,6 +672,7 @@ class Api {
if (_autoReconnect) _scheduleReconnect();
}
// #***! проверка живости настоящим пингом
/// Пробный запрос-пинг: если не ответил — форсируем реконнект.
Future<void> _probeLiveness() async {
if (_sessionState != SessionState.online) return;
@@ -677,6 +694,7 @@ class Api {
}
}
// #***! реконнект прямо сейчас, знаем что связь мертва
Future<void> _forceReconnect() async {
_connectGen++;
_cleanup();
@@ -686,6 +704,7 @@ class Api {
if (_autoReconnect) unawaited(connect());
}
// #***! общая уборка, таймеры подписки сессия
void _cleanup() {
_cancelConnectWatchdog();
_livenessTimer?.cancel();
@@ -697,25 +716,37 @@ class Api {
_lastInteractive = null;
final session = _session;
_session = null;
if (session != null) {
try {
session.disconnect();
} catch (_) {}
}
if (session != null) _releaseSession(session);
_dispatcher.clearPending();
_handshakeSuccessController.add('disconnected');
}
// #***! раст освобождаем руками, иначе рантаймы копятся всю ночь
/// Рвёт соединение и сразу освобождает Rust-объект: иначе tokio-рантайм
/// сессии (поток на ядро) живёт до сборки мусора Dart, а в фоне она может не
/// случиться часами — за ночь реконнектов набегает десяток живых рантаймов.
static void _releaseSession(KusoftSession session) {
if (session.isDisposed) return;
try {
session.disconnect();
} catch (_) {}
try {
session.dispose();
} catch (_) {}
}
Future<void> reconnectAndLogin() async {
await connect();
}
// #***! колбэк автологина ставит аккаунт, api про токены не знает
Future<void> Function()? _onReconnectCallback;
void setReconnectCallback(Future<void> Function() callback) {
_onReconnectCallback = callback;
}
// #***! у ядра нет стрима состояний, опрашиваем сами раз в 5 сек
/// Поллит состояние ядра (стрима состояний нет) — детект разрыва, плюс
/// синхронизация interactive-флага пинга и присутствия.
void _startLiveness() {
@@ -724,6 +755,7 @@ class Api {
_livenessTimer = Timer.periodic(_livenessInterval, (_) => _tickLiveness());
}
// #***! заодно синхроним невидимку
void _tickLiveness() {
final session = _session;
if (session == null || _sessionState != SessionState.online) return;
@@ -747,6 +779,7 @@ class Api {
}
}
// #***! ручная смена невидимки из настроек
void sendPing({required bool interactive}) {
final session = _session;
if (session != null && _sessionState == SessionState.online) {
@@ -762,6 +795,7 @@ class Api {
}
}
// #***! текст ошибки который не стыдно показать
static String? _serverErrorText(dynamic payload) {
if (payload is! Map) return null;
for (final key in ['localizedMessage', 'title']) {
@@ -771,6 +805,7 @@ class Api {
return null;
}
// #***! сервер шлёт свой список стран, он важнее нашего
static List<CountryName>? _parseRegistrationCountries(dynamic payload) {
if (payload is! Map) return null;
final raw = payload['reg-country-code'];
@@ -783,6 +818,7 @@ class Api {
var list = countriesInServerOrder(codes);
if (list.isEmpty) return null;
// #***! страну по геолокации наверх списка
final loc = payload['location'];
if (loc is String && loc.length == 2) {
final home = countriesByCode[loc.toUpperCase()];
@@ -793,8 +829,15 @@ class Api {
return list;
}
// #***! задержка реконнекта 2 4 8, в фоне потолок выше чтоб батарею не жрать
void _scheduleReconnect() {
final delaySec = (2 * (1 << _reconnectAttempts.clamp(0, 3))).clamp(2, 15);
final capSec = AppForeground.value
? _foregroundReconnectCapSec
: _backgroundReconnectCapSec;
final delaySec = (2 * (1 << _reconnectAttempts.clamp(0, 6))).clamp(
2,
capSec,
);
_reconnectAttempts++;
logger.i('Реконнект через $delaySecс (попытка $_reconnectAttempts)');
+111 -3
View File
@@ -7,7 +7,9 @@ import '../../core/config/qlyra_settings.dart';
import '../../core/protocol/chat_cache_fingerprint.dart';
import '../../core/protocol/opcode_map.dart';
import '../../core/protocol/packet.dart';
import '../../core/media/media_playback.dart';
import '../../core/storage/app_database.dart';
import '../../core/storage/profile_deletion_store.dart';
import '../../core/storage/spoofing_service.dart';
import '../../core/storage/token_storage.dart';
import '../../core/utils/logger.dart';
@@ -27,16 +29,19 @@ import 'account/sessions_module.dart';
import 'account/two_factor_module.dart';
export 'account/account_models.dart';
// #***! номер к виду который ждёт сервер
String _normalizeAuthPhone(String phone) {
final digits = phone.replaceAll(RegExp(r'\D'), '');
return '+$digits';
}
// #***! маскируем номер, в логе ему делать нечего
String _maskPhone(String phone) {
if (phone.length <= 5) return '***';
return '${phone.substring(0, 3)}***${phone.substring(phone.length - 2)}';
}
// #***! аккаунт целиком, вход регистрация мультиаккаунт
class AccountModule {
final Api _api;
late final SessionsModule _sessions = SessionsModule(_api);
@@ -47,7 +52,9 @@ class AccountModule {
final _loginStatusController = StreamController<LoginStatus>.broadcast();
final _noticeController = StreamController<AccountNotice>.broadcast();
bool _loggedIn = false;
int? _loginEpoch;
// #***! тяжёлое в подмодулях, тут только оркестрация
AccountModule(this._api) {
_api.stateStream.listen((state) {
if (state != SessionState.online) _loggedIn = false;
@@ -60,8 +67,12 @@ class AccountModule {
/// `true`, только когда сервер считает сессию ONLINE — после успешного
/// login (opcode 19), а не просто после хэндшейка (opcode 6).
bool get isLoggedIn => _loggedIn;
bool get isLoggedIn =>
_loggedIn &&
_loginEpoch == _api.sessionEpoch &&
_api.state == SessionState.online;
// #***! дальше обёртки над подмодулями, единая точка для юишки
Future<PrivacyConfig> getPrivacyConfig() => _privacy.getPrivacyConfig();
Future<List<BlockedContact>> getBlockedContacts() =>
@@ -70,6 +81,8 @@ class AccountModule {
Future<PrivacyConfig> updatePrivacyConfig(Map<String, dynamic> settings) =>
_privacy.updatePrivacyConfig(settings);
Future<PrivacyConfig> setSafeMode(bool value) => _privacy.setSafeMode(value);
Future<PrivacyConfig> setChatsPushNotification(bool value) =>
_privacy.setChatsPushNotification(value);
@@ -156,6 +169,7 @@ class AccountModule {
Future<ProfileData> remove2fa(String trackId) =>
_twoFactor.remove2fa(trackId);
// #***! запрос кода, первый и повторный отличаются типом
Future<RequestCodeResult> requestCode(
String phone, {
String language = 'ru',
@@ -166,6 +180,7 @@ class AccountModule {
String language = 'ru',
}) => _requestCodeInternal(phone, AuthRequestType.resend, language);
// #***! проверка кода, дальше вход регистрация или 2FA
Future<VerifyCodeResult> verifyCode(String code, String token) async {
_ensureOnline();
@@ -183,10 +198,11 @@ class AccountModule {
final result = VerifyCodeResult(payload: data.cast<dynamic, dynamic>());
final sessionToken = result.loginToken ?? result.registerToken;
final sessionToken = result.loginToken;
final verifiedProfile = _profileFromVerifyPayload(result.payload);
final accountId = result.accountId ?? verifiedProfile?.id;
// #***! токен сохраняем сразу и переносим спуф профиль
if (sessionToken != null && accountId != null) {
if (result.loginToken != null && verifiedProfile != null) {
await AppDatabase.saveProfile(verifiedProfile, isActive: true);
@@ -205,6 +221,7 @@ class AccountModule {
return ProfileData.fromServerProfile(profileMap.cast<dynamic, dynamic>());
}
// #***! регистрация после кода
Future<int> completeRegistration({
required String token,
required String firstName,
@@ -232,6 +249,18 @@ class AccountModule {
final data = _requireMapPayload(packet, 'completeRegistration');
final loginToken = data['token'];
if (loginToken is! String || loginToken.trim().isEmpty) {
throw const FormatException(
'completeRegistration: отсутствует токен входа в ответе сервера',
);
}
if (data['tokenType'] != null && data['tokenType'] != 'LOGIN') {
throw const FormatException(
'completeRegistration: сервер не выдал токен типа LOGIN',
);
}
final profileMap = data['profile'];
if (profileMap is! Map) {
throw Exception('completeRegistration: отсутствует profile в ответе');
@@ -248,6 +277,7 @@ class AccountModule {
final profile = ProfileData.fromServerProfile(
profileMap.cast<dynamic, dynamic>(),
);
await TokenStorage.saveToken(loginToken, accountId);
await AppDatabase.saveProfile(profile, isActive: true);
await TokenStorage.setActiveAccount(accountId);
await SpoofingService.commitPendingSpoof(accountId);
@@ -256,6 +286,7 @@ class AccountModule {
return accountId;
}
// #***! основной вход, syncParams говорят серверу что у нас есть
Future<LoginResult> login({
int? accountId,
String? token,
@@ -277,8 +308,14 @@ class AccountModule {
}
}
if (authToken.trim().isEmpty) {
throw StateError('login: пустой токен входа');
}
final requestPayload = buildLoginPayload(authToken, sync: syncParams);
final loginEpoch = _api.sessionEpoch;
_loggedIn = false;
_loginStatusController.add(LoginStatus.loading);
try {
final packet = await _api.sendRequest(Opcode.login, requestPayload);
@@ -287,6 +324,7 @@ class AccountModule {
final dataMap = data.cast<dynamic, dynamic>();
// #***! вошли по чужому токену, id узнаём из ответа
if (resolvedAccountId == null) {
resolvedAccountId = extractAccountId(dataMap);
if (resolvedAccountId == null) {
@@ -303,6 +341,11 @@ class AccountModule {
}
final result = await _processLoginResponse(dataMap, resolvedAccountId);
if (_api.sessionEpoch != loginEpoch ||
_api.state != SessionState.online) {
throw StateError('Session changed during login');
}
_loginEpoch = loginEpoch;
_loggedIn = true;
_loginStatusController.add(LoginStatus.success);
return result;
@@ -319,6 +362,7 @@ class AccountModule {
Future<void> authorizeWebQrLogin(String qrLink) =>
_sessions.authorizeWebQrLogin(qrLink);
// #***! второй аккаунт, рвём сессию чистим кэши готовим спуф
Future<void> beginAddAccount() async {
final existing = await AppDatabase.loadAllProfiles();
await SpoofingService.prepareNewAccountSpoof(
@@ -341,6 +385,7 @@ class AccountModule {
logger.i('Добавление аккаунта: сессия сброшена, активный аккаунт очищен');
}
// #***! вход по чужому токену из дев меню
Future<LoginResult> loginWithToken(String token) async {
await TokenStorage.clearActiveAccount();
try {
@@ -363,7 +408,9 @@ class AccountModule {
return login(token: token);
}
// #***! переключение аккаунта, реконнект с другим спуфом
Future<ProfileData> switchAccount(int accountId) async {
MediaPlayback.instance.closeAudioFile();
final profile = await AppDatabase.loadProfile(accountId);
if (profile == null) {
throw StateError('switchAccount: аккаунт $accountId не найден в базе');
@@ -411,14 +458,51 @@ class AccountModule {
return AppDatabase.loadAllProfiles();
}
// #***! удаляем локально, база токен спуф и заявка
Future<void> removeAccount(int accountId) async {
await AppDatabase.deleteAccount(accountId);
await TokenStorage.deleteAccount(accountId);
await SpoofingService.clearAccountSpoof(accountId);
await ProfileDeletionStore.clear(accountId);
logger.i('Аккаунт $accountId удалён локально');
}
Future<DateTime?> profileDeletionScheduledAt() async {
final accountId = await TokenStorage.getActiveAccountId();
if (accountId == null) return null;
return ProfileDeletionStore.scheduledAt(accountId);
}
// #***! заявка на удаление профиля, сервер вернёт дату
Future<DateTime?> setProfileDeletion(bool delete) async {
_ensureOnline();
final packet = await _api.sendRequest(Opcode.profileDelete, {
'delete': delete,
'type': 0,
});
final data = _requireMapPayload(packet, 'setProfileDeletion');
final raw = data['timestamp'];
final millis = raw is int ? raw : 0;
final accountId = await TokenStorage.getActiveAccountId();
if (accountId != null) {
await ProfileDeletionStore.save(accountId, millis);
}
logger.i(
'Профиль: заявка на удаление '
'${delete ? 'создана' : 'отменена'} (timestamp=$millis)',
);
if (millis <= 0) return null;
return DateTime.fromMillisecondsSinceEpoch(millis);
}
// #***! выход, сначала сервер потом чистка
Future<void> logout() async {
MediaPlayback.instance.closeAudioFile();
final accountId = await TokenStorage.getActiveAccountId();
try {
await _logoutOnServer(accountId);
@@ -445,6 +529,7 @@ class AccountModule {
await _api.sendRequestOrThrow(Opcode.logout, <dynamic, dynamic>{});
}
// #***! чтоб выйти нужна живая сессия, при чём логинимся заново
Future<void> _ensureLogoutSession(int? accountId) async {
if (_api.state == SessionState.disconnected) {
await _api.connect();
@@ -467,6 +552,7 @@ class AccountModule {
_loggedIn = true;
}
// #***! второй шаг входа при 2FA
Future<TwoFactorResult> checkPassword({
required String password,
required String trackId,
@@ -527,6 +613,7 @@ class AccountModule {
return TwoFactorResult(loginToken: loginToken, accountId: accountId);
}
// #***! тело login, токен невидимка и маркеры синхры
Map<dynamic, dynamic> buildLoginPayload(
String token, {
LoginSyncParams? sync,
@@ -535,6 +622,7 @@ class AccountModule {
final payload = <dynamic, dynamic>{
'token': token,
'interactive': interactive ?? !QlyraSettings.ghostMode.value,
// #***! exp это экспериментальные фичи которые просим
'exp': {
'chatsCountGroups': Uint8List.fromList([0x0b, 0x32]),
},
@@ -542,6 +630,7 @@ class AccountModule {
final callsSeed = _api.callsSeed;
final deviceId = _api.deviceId;
// #***! без отпечатка сборки сервер не отдаст кэш чатов
if (callsSeed != null && deviceId != null) {
payload['chatCacheFingerprint'] = ChatCacheFingerprint.compute(
callsSeed,
@@ -557,7 +646,10 @@ class AccountModule {
payload['draftsSync'] = sync.draftsSync;
payload['bannersSync'] = sync.bannersSync;
payload['lastLogin'] = sync.lastLogin;
if (sync.configHash != null) payload['configHash'] = sync.configHash;
if (sync.serverConfigSeen && sync.configHash != null) {
payload['configHash'] = sync.configHash;
}
// #***! нет маркеров, просим всё с нуля
} else {
payload['presenceSync'] = -1;
payload['chatsSync'] = -1;
@@ -566,6 +658,7 @@ class AccountModule {
return payload;
}
// #***! разбор login, профиль чаты контакты папки баннеры
Future<LoginResult> _processLoginResponse(
Map<dynamic, dynamic> data,
int accountId,
@@ -580,6 +673,7 @@ class AccountModule {
ProfileData profile;
final profileMap = data['profile'];
// #***! берсерк ломает профиль специально чтоб проверить восстановление
if (!DebugTest.berserk &&
profileMap is Map &&
profileMap['contact'] is Map) {
@@ -595,8 +689,10 @@ class AccountModule {
await _saveSyncState(data, serverTime, profile.id);
await ContactsModule.syncFromLoginPayload(data, profile.id);
await chats.syncFromLoginPayload(data, profile.id, profile.id);
// #***! остальные страницы чатов в фоне, вход не ждёт
unawaited(chats.paginateChats(_api, profile.id, profile.id, data));
// #***! каждый блок в try, упавший кусок не должен ронять вход
try {
await ContactsModule.syncFromServer(_api, profile.id);
} catch (e) {
@@ -642,6 +738,7 @@ class AccountModule {
);
}
// #***! профиля нет нигде, тянем через контакт иначе заглушка
Future<ProfileData> _resurrectProfile(int accountId) async {
if (DebugTest.berserk) {
await AppDatabase.deleteAccount(accountId);
@@ -673,6 +770,7 @@ class AccountModule {
return ProfileData.stub(accountId);
}
// #***! маркеры синхры, считаем что знаем всё до serverTime
Future<void> _saveSyncState(
Map<dynamic, dynamic> data,
int serverTime,
@@ -699,10 +797,17 @@ class AccountModule {
}
}
// #***! сводка login для отладочного экрана
Future<void> _saveLoginInfo(Map<dynamic, dynamic> data, int accountId) async {
final config = data['config'] as Map?;
final serverConfig = config?['server'] as Map?;
if (serverConfig != null) {
await AppDatabase.setSyncValue(accountId, SyncKey.serverConfigSeen, '1');
await AppDatabase.setSyncValue(
accountId,
SyncKey.profileInviteLink,
serverConfig['invite-link']?.toString().trim() ?? '',
);
await _persistEntryBannerApps(accountId, serverConfig);
}
final info = LoginInfo.fromPayload(data);
@@ -710,6 +815,7 @@ class AccountModule {
await AppDatabase.saveLoginInfo(accountId, jsonEncode(info));
}
// #***! id мини аппок ловим по имени иконки в конфиге
Future<void> _persistEntryBannerApps(int accountId, Map serverConfig) async {
final banners = serverConfig['settings-entry-banners'];
if (banners is! List) return;
@@ -738,6 +844,7 @@ class AccountModule {
}
}
// #***! общий запрос кода
Future<RequestCodeResult> _requestCodeInternal(
String phone,
AuthRequestType type,
@@ -776,6 +883,7 @@ class AccountModule {
return RequestCodeResult(token: token);
}
// #***! дальше три помощника
void _ensureOnline() {
if (_api.state != SessionState.online) {
throw StateError(
@@ -2,6 +2,7 @@ import 'dart:convert';
import '../../../core/storage/app_database.dart';
// #***! модели аккаунта, авторизация приватность сессии
int? _coerceAccountId(dynamic value) {
if (value is int) return value;
if (value is double) return value.toInt();
@@ -9,6 +10,7 @@ int? _coerceAccountId(dynamic value) {
return null;
}
// #***! id аккаунта лежит в разных местах, ищем во всех
int? extractAccountId(dynamic response) {
if (response is! Map) return null;
@@ -48,6 +50,7 @@ int? extractAccountId(dynamic response) {
_coerceAccountId(response['account_id']);
}
// #***! описание формы ответа для лога когда id не нашли
String describeResponseShape(dynamic response) {
if (response is! Map) return 'не-Map (${response.runtimeType})';
final sb = StringBuffer('keys=${response.keys.toList()}');
@@ -66,6 +69,7 @@ String describeResponseShape(dynamic response) {
return sb.toString();
}
// #***! приватность одним объектом, ключи как у сервера капсом
class PrivacyConfig {
final String searchByPhone;
final String incomingCall;
@@ -119,6 +123,7 @@ class PrivacyConfig {
required this.hash,
});
// #***! незнакомое игнорим, пустое берём дефолтом
factory PrivacyConfig.fromMap(Map<dynamic, dynamic> map) {
return PrivacyConfig(
searchByPhone: map['SEARCH_BY_PHONE']?.toString() ?? 'ALL',
@@ -149,6 +154,7 @@ class PrivacyConfig {
);
}
// #***! в базу строкой джейсона
String toJson() => jsonEncode({
'SEARCH_BY_PHONE': searchByPhone,
'INCOMING_CALL': incomingCall,
@@ -185,6 +191,7 @@ class PrivacyConfig {
}
}
// #***! пустой конфиг до ответа сервера
static PrivacyConfig empty() {
return const PrivacyConfig(
searchByPhone: 'ALL',
@@ -214,6 +221,7 @@ class PrivacyConfig {
}
}
// #***! заблокированный контакт для настроек
class BlockedContact {
final int id;
final String? firstName;
@@ -262,6 +270,7 @@ class BlockedContact {
}
}
// #***! состояние 2FA
class TwoFactorDetails {
final bool enabled;
final String? email;
@@ -270,6 +279,7 @@ class TwoFactorDetails {
const TwoFactorDetails({required this.enabled, this.email, this.hint});
}
// #***! тип запроса кода
enum AuthRequestType {
startAuth('START_AUTH'),
resend('RESEND'),
@@ -284,6 +294,7 @@ enum LoginStatus { idle, loading, success, error }
enum AccountNotice { resurrectingProfile }
// #***! протухший токен FCM, надо перевыпустить
class WrongDeviceTokenException implements Exception {
const WrongDeviceTokenException();
@override
@@ -296,6 +307,7 @@ class WrongPasswordException implements Exception {
String toString() => 'WrongPasswordException';
}
// #***! временный токен сценария авторизации
class RequestCodeResult {
final String token;
@@ -316,17 +328,20 @@ class PresetAvatarCategory {
const PresetAvatarCategory({required this.name, required this.avatars});
}
// #***! ответ на код, тут же решается вход это или регистрация
class VerifyCodeResult {
final Map<dynamic, dynamic> payload;
const VerifyCodeResult({required this.payload});
// #***! токены вложенно в tokenAttrs
String? get loginToken => _nestedToken('LOGIN');
String? get registerToken => _nestedToken('REGISTER');
bool get isRegistration => registerToken != null && loginToken == null;
// #***! при регистрации сервер даёт готовые аватарки
List<PresetAvatarCategory> get presetAvatars {
final raw = payload['presetAvatars'];
if (raw is! List) return const [];
@@ -356,6 +371,7 @@ class VerifyCodeResult {
return categories;
}
// #***! аккаунт с 2FA, дальше пароль
bool get requiresPassword => payload['passwordChallenge'] != null;
Map<dynamic, dynamic>? get passwordChallenge {
@@ -374,7 +390,8 @@ class VerifyCodeResult {
if (attrs is! Map) return null;
final entry = attrs[key];
if (entry is! Map) return null;
return entry['token'] as String?;
final token = entry['token'];
return token is String && token.trim().isNotEmpty ? token : null;
}
}
@@ -385,6 +402,7 @@ class TwoFactorResult {
const TwoFactorResult({required this.loginToken, required this.accountId});
}
// #***! маркеры синхры для login, докуда мы уже знаем
class LoginSyncParams {
final int chatsSync;
final int contactsSync;
@@ -395,6 +413,7 @@ class LoginSyncParams {
final int lastLogin;
final String? configHash;
final String? chatCacheFingerprint;
final bool serverConfigSeen;
const LoginSyncParams({
required this.chatsSync,
@@ -406,8 +425,10 @@ class LoginSyncParams {
required this.lastLogin,
this.configHash,
this.chatCacheFingerprint,
this.serverConfigSeen = false,
});
// #***! нет lastLogin значит первый вход
static Future<LoginSyncParams?> fromDatabase(int accountId) async {
final values = await AppDatabase.getAllSyncValues(accountId);
final lastLogin = values[SyncKey.lastLogin];
@@ -423,10 +444,12 @@ class LoginSyncParams {
lastLogin: int.tryParse(lastLogin) ?? 0,
configHash: values[SyncKey.configHash],
chatCacheFingerprint: values[SyncKey.chatCacheFingerprint],
serverConfigSeen: values[SyncKey.serverConfigSeen] == '1',
);
}
}
// #***! активная сессия на другом устройстве
class SessionInfo {
final int? id;
final String client;
@@ -457,6 +480,7 @@ class SessionInfo {
);
}
// #***! сервер не всегда даёт id, ключ собираем из всех полей
int get uniqueId => Object.hash(id, client, time, info);
@override
@@ -475,6 +499,7 @@ class SessionInfo {
int get hashCode => Object.hash(id, client, location, current, time, info);
}
// #***! итог успешного входа
class LoginResult {
final ProfileData profile;
final String? updatedToken;
@@ -6,11 +6,13 @@ import '../../../core/storage/token_storage.dart';
import 'account_base.dart';
import 'account_models.dart';
// #***! приватность и уведомления
class PrivacyModule extends AccountApiBase {
PrivacyModule(super.api);
static const String _defaultPushSound = 'oki.aiff';
// #***! приватность из базы, приходит в login и живёт локально
Future<PrivacyConfig> getPrivacyConfig() async {
final accountId = await TokenStorage.getActiveAccountId();
if (accountId != null) {
@@ -20,6 +22,7 @@ class PrivacyModule extends AccountApiBase {
return PrivacyConfig.empty();
}
// #***! список заблокированных
Future<List<BlockedContact>> getBlockedContacts() async {
ensureOnline();
final packet = await api.sendRequest(Opcode.contactList, {
@@ -36,6 +39,7 @@ class PrivacyModule extends AccountApiBase {
.toList();
}
// #***! обновление одним config, ответ в базу
Future<PrivacyConfig> updatePrivacyConfig(
Map<String, dynamic> settings,
) async {
@@ -57,6 +61,21 @@ class PrivacyModule extends AccountApiBase {
return config;
}
// #***! безопасный режим это пачка настроек разом
Future<PrivacyConfig> setSafeMode(bool value) => updatePrivacyConfig(
value
? {
'INCOMING_CALL': 'CONTACTS',
'SEARCH_BY_PHONE': 'CONTACTS',
'SAFE_MODE_NO_PIN': true,
'CONTENT_LEVEL_ACCESS': true,
'CHATS_INVITE': 'CONTACTS',
'SAFE_MODE': true,
}
: {'SAFE_MODE_NO_PIN': false, 'SAFE_MODE': false},
);
// #***! дальше по методу на каждый переключатель
Future<PrivacyConfig> setChatsPushNotification(bool value) =>
updatePrivacyConfig({'CHATS_PUSH_NOTIFICATION': value ? 'ON' : 'OFF'});
@@ -75,6 +94,7 @@ class PrivacyModule extends AccountApiBase {
Future<PrivacyConfig> setNewContacts(bool value) =>
updatePrivacyConfig({'PUSH_NEW_CONTACTS': value});
// #***! регистрация push токена, ловим протухший FCM
Future<void> registerPushToken(String pushToken) async {
ensureOnline();
final packet = await api.sendRequest(Opcode.config, <dynamic, dynamic>{
@@ -1,4 +1,5 @@
import '../../../core/protocol/opcode_map.dart';
import '../../../core/storage/token_storage.dart';
import 'account_base.dart';
import 'account_models.dart';
@@ -21,6 +22,17 @@ class SessionsModule extends AccountApiBase {
ensureOnline();
final packet = await api.sendRequest(Opcode.sessionsClose, {});
checkPacketError(packet, 'terminateOtherSessions');
final data = packet.payload;
final token = data is Map ? data['token'] : null;
if (token is String && token.isNotEmpty) {
final accountId = await TokenStorage.getActiveAccountId();
if (accountId == null) {
throw StateError(
'terminateOtherSessions: нет активного аккаунта для нового токена',
);
}
await TokenStorage.saveToken(token, accountId);
}
}
Future<void> authorizeWebQrLogin(String qrLink) async {
+9 -6
View File
@@ -102,6 +102,7 @@ class ContactsModule {
Api api,
String phone, {
bool silent = false,
bool strict = false,
}) async {
final normalized = _normalizePhone(phone);
if (normalized == null) return null;
@@ -110,14 +111,19 @@ class ContactsModule {
packet = await api.sendRequest(Opcode.contactInfoByPhone, {
'phone': normalized,
}, silent: silent);
} on PacketError {
} on PacketError catch (e) {
if (strict && e.errorKey != 'user.not.found') rethrow;
return null;
}
if (packet.isError) {
if (strict) throw StateError('Contact lookup failed');
return null;
}
if (packet.isError) return null;
final contact = (packet.payload as Map?)?['contact'];
if (contact is! Map) return null;
final id = contact['id'];
if (id is! int) return null;
if (((contact['accountStatus'] as int?) ?? 0) != 0) return null;
primeContactCache(contact);
@@ -219,10 +225,7 @@ class ContactsModule {
'lastName': lastName,
}, silent: true);
} on PacketError catch (e) {
final key = e.errorKey ?? '';
final notFound =
key == 'user.not.found' ||
e.message.toLowerCase().contains('not found');
final notFound = e.errorKey == 'user.not.found';
return AddContactResult(
notFound ? AddContactStatus.notFound : AddContactStatus.error,
);
+15
View File
@@ -192,6 +192,21 @@ class FoldersModule {
return true;
}
static List<CachedChat> chatsForFolder(
Iterable<CachedChat> chats,
ChatFolder folder, {
required int myId,
required Set<int> contactIds,
required Set<int> archivedIds,
}) => chats
.where(
(chat) =>
(!archivedIds.contains(chat.id) ||
folder.include.contains(chat.id)) &&
chatMatchesFolder(chat, folder, myId: myId, contactIds: contactIds),
)
.toList();
static List<ChatFolder> _parseFolderList(dynamic raw) {
if (raw is! List) return [];
return raw
+5 -2
View File
@@ -422,7 +422,9 @@ class ReplyInfo {
case AttachmentType.audio:
return 'Голосовое сообщение';
case AttachmentType.file:
return 'Файл';
final file = a.first;
final name = file is FileAttachment ? file.name?.trim() : null;
return name == null || name.isEmpty ? 'Файл' : name;
case AttachmentType.sticker:
return 'Стикер';
case AttachmentType.contact:
@@ -864,6 +866,7 @@ class MessagesModule {
int accountId,
int chatId,
String text, {
int? clientId,
bool notify = true,
int? scheduledTime,
int? replyToMessageId,
@@ -872,7 +875,7 @@ class MessagesModule {
}) async {
final message = <String, dynamic>{
'text': text,
'cid': DateTime.now().millisecondsSinceEpoch * -1,
'cid': clientId ?? DateTime.now().millisecondsSinceEpoch * -1,
'elements': elements,
'attaches': [],
};
+71 -129
View File
@@ -1,156 +1,98 @@
import 'dart:async';
import '../../core/protocol/packet.dart';
import '../../core/crypto/message_decryption_cache.dart';
import '../../core/storage/app_database.dart';
import '../../core/storage/token_storage.dart';
import '../../core/utils/logger.dart';
import '../api.dart';
import 'chats.dart';
import 'messages.dart';
import 'outbox_queue.dart';
import 'outgoing_text.dart';
class OutboxService {
OutboxService._();
static final OutboxService instance = OutboxService._();
OutboxQueue? _queue;
StreamSubscription<SessionState>? _subscription;
final Map<String, CachedMessage> _latest = {};
Api? _api;
MessagesModule? _messages;
bool _flushing = false;
void init(Api api, MessagesModule messages) {
if (_api != null) return;
_api = api;
_messages = messages;
api.stateStream.listen((state) {
void init(
Api api,
MessagesModule messages, {
required bool Function() isAuthenticated,
}) {
if (_queue != null) {
unawaited(flush());
return;
}
_queue = OutboxQueue(
activeAccount: TokenStorage.getActiveAccountId,
isOnline: () => api.state == SessionState.online && isAuthenticated(),
sessionEpoch: () => api.sessionEpoch,
load: (accountId) async => (await AppDatabase.loadPendingMessages(
accountId,
)).map(CachedMessage.fromDbRow).toList(),
save: (message) => AppDatabase.saveMessages([message.toDbRow()]),
replace: (before, after) =>
AppDatabase.replaceMessage(after.toDbRow(), removeId: before.id),
send: (message, cid) => messages.sendMessage(
message.accountId,
message.chatId,
message.text!,
clientId: cid,
replyToMessageId: OutgoingText.replyId(message),
replySourceChatId: OutgoingText.replyChatId(message),
elements: OutgoingText.elements(message),
),
onChanged: (before, after) {
_latest[before.id] = after;
if (_latest.length > 256) _latest.remove(_latest.keys.first);
MessageDecryptionCache.instance.adopt(before.id, after.id);
chats.emitMessageSent(after.chatId, before.id, after);
unawaited(_updatePreview(after));
},
onError: (error, stack) => logger.w('Outbox: $error'),
);
_subscription = api.stateStream.listen((state) {
if (state == SessionState.online) unawaited(flush());
});
if (api.state == SessionState.online) unawaited(flush());
unawaited(flush());
}
Future<void> flush() async {
if (_flushing) return;
final api = _api;
final messages = _messages;
if (api == null || messages == null) return;
if (api.state != SessionState.online) return;
Future<CachedMessage> enqueue(CachedMessage message) async {
final queue = _queue;
if (queue == null) throw StateError('Outbox is not initialized');
await queue.enqueue(message);
await _updatePreview(message);
return _latest.remove(message.id) ?? message;
}
_flushing = true;
Future<void> _updatePreview(CachedMessage message) async {
try {
final accountId = await TokenStorage.getActiveAccountId();
if (accountId == null) return;
final rows = await AppDatabase.loadPendingMessages(accountId);
for (final row in rows) {
if (api.state != SessionState.online) break;
final pending = CachedMessage.fromDbRow(row);
final text = pending.text;
if (text == null || text.isEmpty) continue;
final payload = pending.payload;
final replyToMessageId = _replyIdFromPayload(payload);
final replySourceChatId = _replySourceChatIdFromPayload(payload);
final elements = _elementsFromPayload(payload);
try {
final actualId = await messages.sendMessage(
accountId,
pending.chatId,
text,
replyToMessageId: replyToMessageId,
replySourceChatId: replySourceChatId,
elements: elements,
);
final sent = CachedMessage(
id: actualId.isNotEmpty ? actualId : pending.id,
accountId: accountId,
chatId: pending.chatId,
senderId: accountId,
text: text,
time: pending.time,
status: 'sent',
payload: payload,
);
await AppDatabase.saveMessages([sent.toDbRow()]);
if (sent.id != pending.id) {
await AppDatabase.deleteMessage(
accountId,
pending.chatId,
pending.id,
);
}
chats.emitMessageSent(pending.chatId, pending.id, sent);
await chats.applyOutgoing(
accountId,
pending.chatId,
messageId: sent.id,
time: sent.time,
text: text,
status: 'sent',
elements: elements.isEmpty ? null : elements,
);
} catch (e) {
if (!isPermanentSendFailure(e)) {
logger.w('Outbox: отправка ${pending.id} не удалась: $e');
continue;
}
logger.w('Outbox: ${pending.id} отклонено сервером: $e');
final failed = pending.copyWith(status: 'error');
await AppDatabase.saveMessages([failed.toDbRow()]);
chats.emitMessageSent(pending.chatId, pending.id, failed);
await chats.applyOutgoing(
accountId,
pending.chatId,
messageId: failed.id,
time: failed.time,
text: text,
status: 'error',
elements: elements.isEmpty ? null : elements,
);
}
}
} catch (e) {
logger.e('Outbox flush: $e');
} finally {
_flushing = false;
await chats.applyOutgoing(
message.accountId,
message.chatId,
messageId: message.id,
time: message.time,
text: message.text ?? '',
status: message.status!,
elements: OutgoingText.elements(message),
);
} catch (error) {
logger.w('Outbox preview: $error');
}
}
int? _replyIdFromPayload(Map<String, dynamic>? payload) {
if (payload == null) return null;
final link = payload['link'];
if (link is! Map) return null;
if ((link['type'] as String?)?.toUpperCase() != 'REPLY') return null;
final msg = link['message'];
if (msg is Map) {
final id = msg['id'];
if (id is int) return id;
if (id != null) return int.tryParse(id.toString());
}
final mid = link['messageId'];
if (mid is int) return mid;
if (mid != null) return int.tryParse(mid.toString());
return null;
}
Future<void> flush() => _queue?.flush() ?? Future.value();
int? _replySourceChatIdFromPayload(Map<String, dynamic>? payload) {
if (payload == null) return null;
final link = payload['link'];
if (link is! Map) return null;
if ((link['type'] as String?)?.toUpperCase() != 'REPLY') return null;
final chatId = link['chatId'];
if (chatId is int) return chatId;
if (chatId != null) return int.tryParse(chatId.toString());
return null;
}
String resolveMessageId(String id) => _latest[id]?.id ?? id;
List<Map<String, dynamic>> _elementsFromPayload(
Map<String, dynamic>? payload,
) {
final raw = payload?['elements'];
if (raw is! List) return const [];
return raw
.whereType<Map>()
.map((e) => Map<String, dynamic>.from(e))
.toList();
Future<void> dispose() async {
_queue?.dispose();
_queue = null;
await _subscription?.cancel();
_subscription = null;
}
}
+182
View File
@@ -0,0 +1,182 @@
import 'dart:async';
import '../../core/protocol/packet.dart';
import 'messages.dart';
import 'outgoing_text.dart';
class OutboxQueue {
OutboxQueue({
required this.activeAccount,
required this.isOnline,
required this.sessionEpoch,
required this.load,
required this.save,
required this.replace,
required this.send,
required this.onChanged,
required this.onError,
DateTime Function()? now,
this.retryBase = const Duration(seconds: 2),
}) : now = now ?? DateTime.now;
final Future<int?> Function() activeAccount;
final bool Function() isOnline;
final int Function() sessionEpoch;
final Future<List<CachedMessage>> Function(int) load;
final Future<void> Function(CachedMessage) save;
final Future<void> Function(CachedMessage, CachedMessage) replace;
final Future<String> Function(CachedMessage, int) send;
final void Function(CachedMessage, CachedMessage) onChanged;
final void Function(Object, StackTrace) onError;
final DateTime Function() now;
final Duration retryBase;
final Map<String, CachedMessage> _receipts = {};
Timer? _timer;
Future<void>? _running;
bool _wakeAgain = false;
bool _disposed = false;
Future<void> enqueue(CachedMessage message) async {
if (OutgoingText.metadata(message) == null) {
throw ArgumentError('Only prepared outgoing text may be queued');
}
await save(message);
}
Future<void> flush() {
if (_disposed) return Future.value();
final running = _running;
if (running != null) {
_wakeAgain = true;
return running;
}
_timer?.cancel();
return _running = _flush().whenComplete(() {
_running = null;
if (_wakeAgain && !_disposed) {
_wakeAgain = false;
unawaited(flush());
}
});
}
Future<bool> _validSession(int accountId, int epoch) async {
final active = await activeAccount();
return !_disposed &&
active == accountId &&
isOnline() &&
sessionEpoch() == epoch;
}
Future<void> _flush() async {
if (!isOnline()) return;
final epoch = sessionEpoch();
try {
final accountId = await activeAccount();
if (accountId == null || !await _validSession(accountId, epoch)) return;
final rows = await load(accountId);
final blockedChats = <int>{};
for (final pending in rows) {
if (!await _validSession(accountId, epoch)) break;
if (pending.accountId != accountId ||
pending.deleted ||
blockedChats.contains(pending.chatId)) {
continue;
}
final meta = OutgoingText.metadata(pending);
if (meta == null || pending.text == null || pending.text!.isEmpty) {
final failed = pending.copyWith(status: 'error');
await save(failed);
_notify(pending, failed);
continue;
}
final retryAt = meta['retryAt'] as int? ?? 0;
final remaining = retryAt - now().millisecondsSinceEpoch;
if (remaining > 0) {
blockedChats.add(pending.chatId);
_schedule(Duration(milliseconds: remaining));
continue;
}
final receiptKey =
'${pending.accountId}/${pending.chatId}/${pending.id}';
try {
var sent = _receipts[receiptKey];
if (sent == null) {
final id = await send(pending, meta['cid'] as int);
if (id.isEmpty) throw StateError('Missing server message ID');
sent = CachedMessage(
id: id,
accountId: pending.accountId,
chatId: pending.chatId,
senderId: pending.senderId,
text: pending.text,
time: pending.time,
status: 'sent',
payload: pending.payload,
);
_receipts[receiptKey] = sent;
}
await replace(pending, sent);
_receipts.remove(receiptKey);
_notify(pending, sent);
} catch (error, stack) {
onError(error, stack);
if (isPermanentSendFailure(error)) {
final failed = pending.copyWith(status: 'error');
await save(failed);
_notify(pending, failed);
continue;
}
final attempts = ((meta['attempts'] as int? ?? 0) + 1).clamp(1, 30);
final delay = Duration(
milliseconds:
(retryBase.inMilliseconds * (1 << (attempts - 1).clamp(0, 5)))
.clamp(1, 60000),
);
final queued = pending.copyWith(
status: 'pending',
payload: {
...?pending.payload,
'_outbox': {
...meta,
'attempts': attempts,
'retryAt': now().add(delay).millisecondsSinceEpoch,
},
},
);
await save(queued);
_notify(pending, queued);
blockedChats.add(pending.chatId);
_schedule(delay);
}
}
} catch (error, stack) {
onError(error, stack);
_schedule(retryBase);
}
}
void _notify(CachedMessage before, CachedMessage after) {
try {
onChanged(before, after);
} catch (error, stack) {
onError(error, stack);
}
}
DateTime? _scheduledAt;
void _schedule(Duration delay) {
if (_disposed) return;
final at = now().add(delay);
if (_timer?.isActive == true && _scheduledAt!.isBefore(at)) return;
_timer?.cancel();
_scheduledAt = at;
_timer = Timer(delay, () => unawaited(flush()));
}
void dispose() {
_disposed = true;
_timer?.cancel();
}
}
+76
View File
@@ -0,0 +1,76 @@
import 'messages.dart';
class OutgoingText {
static int _lastCid = 0;
static int nextCid() {
final now = DateTime.now().microsecondsSinceEpoch;
_lastCid = now > _lastCid ? now : _lastCid + 1;
return -_lastCid;
}
static CachedMessage prepare({
required int accountId,
required int chatId,
required String wireText,
required bool encrypted,
Map<String, dynamic>? payload,
}) {
if (accountId == 0 || wireText.isEmpty) {
throw ArgumentError('An account and prepared text are required');
}
final cid = nextCid();
return CachedMessage(
id: 'temp_outbox_${-cid}',
accountId: accountId,
chatId: chatId,
senderId: accountId,
text: wireText,
time: DateTime.now().millisecondsSinceEpoch,
status: 'pending',
payload: {
...?payload,
'_outbox': {
'version': 1,
'cid': cid,
'encrypted': encrypted,
'attempts': 0,
'retryAt': 0,
},
},
);
}
static Map<String, dynamic>? metadata(CachedMessage message) {
final raw = message.payload?['_outbox'];
if (raw is! Map ||
raw['version'] != 1 ||
raw['cid'] is! int ||
(raw['cid'] as int) >= 0 ||
raw['encrypted'] is! bool) {
return null;
}
return Map<String, dynamic>.from(raw);
}
static List<Map<String, dynamic>> elements(CachedMessage message) =>
(message.payload?['elements'] as List? ?? const [])
.whereType<Map>()
.map((e) => Map<String, dynamic>.from(e))
.toList();
static int? replyId(CachedMessage message) {
final link = message.payload?['link'];
if (link is! Map || link['type'] != 'REPLY') return null;
final original = link['message'];
return _int(original is Map ? original['id'] : link['messageId']);
}
static int? replyChatId(CachedMessage message) {
final link = message.payload?['link'];
return link is Map && link['type'] == 'REPLY' ? _int(link['chatId']) : null;
}
static int? _int(Object? value) =>
value is int ? value : int.tryParse(value?.toString() ?? '');
}
+22
View File
@@ -0,0 +1,22 @@
import 'package:flutter/services.dart' show appFlavor;
// #***! что включено в сборке, всё считается на компиляции из flavor
abstract final class BuildProfile {
static const String storeFlavor = 'store';
// #***! store сборка урезана, без самообновления дев инструментов и спуфа
static const bool isStore = appFlavor == storeFlavor;
static const bool selfUpdate = !isStore;
static const bool firebasePush = appFlavor == 'oneme';
static const bool spoofUi = !isStore;
static const bool tokenLogin = !isStore;
static const bool devTools = !isStore;
static const bool insecureTransport = !isStore;
static const bool trafficCapture = !isStore;
static const bool pranks = !isStore;
static const bool hiddenContentViewers = !isStore;
static const bool digitalId = !isStore;
static const bool ipGeoLookup = !isStore;
static const bool sessionCityLookup = !isStore;
}
+6 -2
View File
@@ -1,5 +1,8 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'build_profile.dart';
// #***! адрес сервера и тайминги
abstract class ServerConfig {
static const String defaultHost = 'api2.oneme.ru';
static const int defaultPort = 443;
@@ -11,11 +14,12 @@ abstract class ServerConfig {
static const Duration requestTimeout = Duration(seconds: 30);
static const int maxReconnectAttempts = 50;
// #***! в dev адрес можно переопределить, в релизе всегда дефолтный
static Future<({String host, int port, bool trustMincifryCa})>
loadEndpoint() async {
final prefs = await SharedPreferences.getInstance();
final rawHost = prefs.getString(prefHostKey);
final rawPort = prefs.getInt(prefPortKey);
final rawHost = BuildProfile.devTools ? prefs.getString(prefHostKey) : null;
final rawPort = BuildProfile.devTools ? prefs.getInt(prefPortKey) : null;
final host = (rawHost != null && rawHost.trim().isNotEmpty)
? rawHost.trim()
: defaultHost;
+64
View File
@@ -0,0 +1,64 @@
import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
// #***! реальные данные устройства для юзерагента
/// Данные устройства для user-agent, неизменные за время жизни процесса.
/// Читаются с платформы один раз: на каждый реконнект их запрашивать незачем.
class DeviceProfile {
const DeviceProfile({
this.osVersion = '',
this.deviceName = 'Unknown',
this.manufacturer,
this.model,
this.sdkInt,
});
final String osVersion;
final String deviceName;
final String? manufacturer;
final String? model;
final int? sdkInt;
// #***! читаем один раз за процесс, на каждый реконнект незачем
static DeviceProfile? _cached;
static Future<DeviceProfile> load() async {
final cached = _cached;
if (cached != null) return cached;
final profile = await _read();
_cached = profile;
return profile;
}
// #***! у каждой платформы свой источник, на незнакомой пусто
static Future<DeviceProfile> _read() async {
final deviceInfo = DeviceInfoPlugin();
if (Platform.isAndroid) {
final info = await deviceInfo.androidInfo;
return DeviceProfile(
osVersion: 'Android ${info.version.release}',
deviceName: '${info.manufacturer} ${info.model}',
manufacturer: info.manufacturer,
model: info.model,
sdkInt: info.version.sdkInt,
);
}
if (Platform.isIOS) {
final info = await deviceInfo.iosInfo;
return DeviceProfile(
osVersion: info.systemVersion,
deviceName: info.utsname.machine,
);
}
if (Platform.isLinux) {
final info = await deviceInfo.linuxInfo;
return DeviceProfile(osVersion: info.name);
}
if (Platform.isWindows) {
final info = await deviceInfo.windowsInfo;
return DeviceProfile(osVersion: info.productName);
}
return const DeviceProfile();
}
}
+14
View File
@@ -0,0 +1,14 @@
enum ContactPresence { unknown, online, recently, longAgo }
ContactPresence contactPresence(Map<String, dynamic>? presence, DateTime now) {
if (presence == null) return ContactPresence.unknown;
final status = presence['status'];
if (status == 1) return ContactPresence.online;
if (status == 2 || status == 3) return ContactPresence.recently;
final seen = presence['seen'];
if (seen is! int || seen <= 0) return ContactPresence.unknown;
final elapsed = now.millisecondsSinceEpoch ~/ 1000 - seen;
return elapsed <= const Duration(days: 3).inSeconds
? ContactPresence.recently
: ContactPresence.longAgo;
}
+30
View File
@@ -0,0 +1,30 @@
import '../../backend/modules/contacts.dart';
class ContactSearch {
static List<CachedContact> filter(
List<CachedContact> contacts,
String query,
) {
final text = _normalizeName(query);
if (text.isEmpty) return List.of(contacts);
final isPhone = RegExp(r'^[+\d\s().-]+$').hasMatch(text);
var digits = isPhone ? text.replaceAll(RegExp(r'\D'), '') : '';
if (digits.length == 11 && digits.startsWith('8')) {
digits = '7${digits.substring(1)}';
}
final words = text.split(' ');
return contacts.where((contact) {
final name = _normalizeName(
'${contact.firstName} ${contact.lastName ?? ''}',
);
return words.every(name.contains) ||
(digits.isNotEmpty && contact.phone.toString().contains(digits));
}).toList();
}
static String _normalizeName(String value) => value
.trim()
.toLowerCase()
.replaceAll('ё', 'е')
.replaceAll(RegExp(r'\s+'), ' ');
}
+28 -3
View File
@@ -13,6 +13,8 @@ class DeviceContactsService {
static const _deniedKey = 'phonebook_denied';
static final Map<String, String> _byLast10 = {};
static final Map<String, String> _phonebook = {};
static Map<String, String> get phonebook => Map.unmodifiable(_phonebook);
static bool _loaded = false;
static bool get _supported => Platform.isAndroid || Platform.isIOS;
@@ -55,9 +57,12 @@ class DeviceContactsService {
await _readBook();
}
static Future<bool> ensureLoadedInteractive({bool force = false}) async {
static Future<bool> ensureLoadedInteractive({
bool force = false,
bool forContacts = false,
}) async {
if (!_supported) return false;
if (!AppPhonebookNames.current.value) return false;
if (!forContacts && !AppPhonebookNames.current.value) return false;
if (_loaded && !force) return false;
if (await hasPermission()) {
@@ -80,6 +85,7 @@ class DeviceContactsService {
static Future<bool> reload() async {
_loaded = false;
_byLast10.clear();
_phonebook.clear();
return ensureLoadedInteractive(force: true);
}
@@ -89,14 +95,24 @@ class DeviceContactsService {
}
static Future<bool> _readBook() async {
_loaded = false;
_byLast10.clear();
_phonebook.clear();
try {
FlutterContacts.config.includeNonVisibleOnAndroid = true;
final contacts = await FlutterContacts.getContacts(withProperties: true);
_byLast10.clear();
_phonebook.clear();
for (final contact in contacts) {
final name = contact.displayName.trim();
if (name.isEmpty) continue;
for (final phone in contact.phones) {
final normalized = normalizePhone(phone.number);
if (normalized != null) {
_phonebook.putIfAbsent(
normalized,
() => name.isEmpty ? normalized : name,
);
}
final key = _last10(phone.number);
if (key != null) {
_byLast10.putIfAbsent(key, () => name);
@@ -114,4 +130,13 @@ class DeviceContactsService {
return false;
}
}
static String? normalizePhone(String raw) {
var digits = raw.replaceAll(RegExp(r'[^\d]'), '');
if (digits.length == 11 && digits.startsWith('8')) {
digits = '7${digits.substring(1)}';
}
if (digits.length < 11 || digits.length > 15) return null;
return '+$digits';
}
}
@@ -0,0 +1,44 @@
import '../../backend/modules/contacts.dart';
import 'device_contacts_service.dart';
class PhonebookMaxContacts {
static Future<List<CachedContact>> resolve({
required Map<String, String> phonebook,
required List<CachedContact> cached,
required int accountId,
required Future<PhoneLookupResult?> Function(String) lookup,
bool Function()? isCancelled,
}) async {
final known = <String, CachedContact>{};
for (final contact in cached) {
final phone = DeviceContactsService.normalizePhone('${contact.phone}');
if (phone != null) known[phone] = contact;
}
final result = <int, CachedContact>{};
for (final entry in phonebook.entries) {
if (isCancelled?.call() == true) break;
final phone = DeviceContactsService.normalizePhone(entry.key);
if (phone == null) continue;
final existing = known[phone];
final found = await lookup(phone);
if (isCancelled?.call() == true) break;
if (found == null) continue;
final id = found.id;
result.putIfAbsent(
id,
() => CachedContact(
id: id,
accountId: accountId,
firstName: entry.value,
phone: int.parse(phone.substring(1)),
baseUrl: found.avatarUrl,
updateTime: 0,
options: existing?.id == id ? existing!.options : const {},
),
);
}
return result.values.toList()..sort(
(a, b) => a.firstName.toLowerCase().compareTo(b.firstName.toLowerCase()),
);
}
}
+1 -2
View File
@@ -216,8 +216,7 @@ class DeepLinkService {
bool _isLogExportLink(Uri uri) {
final scheme = uri.scheme.toLowerCase();
final segments = <String>[
if (scheme == 'qlyra' && uri.host.isNotEmpty)
uri.host,
if (scheme == 'qlyra' && uri.host.isNotEmpty) uri.host,
...uri.pathSegments,
].where((s) => s.isNotEmpty).toList();
+35
View File
@@ -0,0 +1,35 @@
import '../cache/info_cache.dart';
import '../storage/app_database.dart';
const String _host = 'https://max.ru';
// #***! ссылка на профиль из имени или готового адреса
String? profileLinkOf(String? rawLink) {
final link = rawLink?.trim();
if (link == null || link.isEmpty) return null;
if (!link.contains('://')) {
final name = link.startsWith('@') ? link.substring(1) : link;
return name.isEmpty ? null : '$_host/$name';
}
final path = Uri.tryParse(link)?.path.replaceAll('/', '') ?? '';
return path.isEmpty ? null : link;
}
// #***! своя ссылка, сначала конфиг потом кэш потом сервер
Future<String?> ownProfileLink() async {
final profile = await AppDatabase.loadActiveProfile();
final id = profile?.id ?? 0;
if (id == 0) return null;
final invite = profileLinkOf(
await AppDatabase.getSyncValue(id, SyncKey.profileInviteLink),
);
if (invite != null) return invite;
final cached = await ContactInfoFetch.get(id);
final short = profileLinkOf(cached?.raw['link'] as String?);
if (short != null) return short;
final fresh = await ContactInfoFetch.get(id, forceRefresh: true);
return profileLinkOf(fresh?.raw['link'] as String?);
}
+22
View File
@@ -0,0 +1,22 @@
// #***! аудиофайл в плеере плюс откуда он взялся
class AudioFileTrack {
const AudioFileTrack({
required this.cacheName,
required this.path,
required this.name,
required this.sourceName,
this.chatId,
this.messageId,
this.messageTime,
this.thumbnailUrl,
});
final String cacheName;
final String path;
final String name;
final String sourceName;
final int? chatId;
final String? messageId;
final int? messageTime;
final String? thumbnailUrl;
}
@@ -0,0 +1,156 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:audio_session/audio_session.dart';
import 'package:flutter/foundation.dart';
import 'package:just_audio_media_kit/just_audio_media_kit.dart';
import '../calls/active_call.dart';
import 'audio_file_track.dart';
import 'background_audio_handler.dart';
// #***! плеер музыки с управлением из шторки
class AudioPlaybackController {
AudioPlaybackController._(this._handler) {
_subscriptions.add(
_handler.playbackState.listen((state) {
playing.value = state.playing;
processingState.value = state.processingState;
bufferedPosition.value = state.bufferedPosition;
}),
);
_subscriptions.add(
_handler.mediaItem.listen((item) {
duration.value = item?.duration ?? Duration.zero;
}),
);
_subscriptions.add(
_handler.positionStream.listen((value) => position.value = value),
);
_subscriptions.add(
_handler.bufferedPositionStream.listen(
(value) => bufferedPosition.value = value,
),
);
_subscriptions.add(
_handler.errors.stream.listen((value) => error.value = value),
);
ActiveCall.instance.current.addListener(_onActiveCallChanged);
}
// #***! синглтон с ленивой инициализацией, audio_service поднимать дорого
static AudioPlaybackController? _instance;
static Future<AudioPlaybackController>? _pending;
static AudioPlaybackController get instance {
final value = _instance;
if (value == null) throw StateError('Audio playback is not initialized');
return value;
}
static bool get isInitialized => _instance != null;
static final ValueNotifier<String?> error = ValueNotifier(null);
static Future<AudioPlaybackController> ensureInitialized(
String notificationChannelName,
) async {
final ready = _instance;
if (ready != null) return ready;
final pending = _pending ??= _create(notificationChannelName);
try {
return await pending;
} catch (_) {
_pending = null;
rethrow;
}
}
static Future<AudioPlaybackController> _create(String channelName) async {
JustAudioMediaKit.ensureInitialized(linux: true, windows: true);
final handler = switch (defaultTargetPlatform) {
TargetPlatform.windows ||
TargetPlatform.linux => BackgroundAudioHandler(),
_ => await AudioService.init(
builder: BackgroundAudioHandler.new,
config: AudioServiceConfig(
androidNotificationChannelId: 'qlyra.audio.playback',
androidNotificationChannelName: channelName,
androidNotificationOngoing: false,
androidStopForegroundOnPause: true,
),
),
};
final session = await AudioSession.instance;
await session.configure(const AudioSessionConfiguration.music());
return _instance = AudioPlaybackController._(handler);
}
final BackgroundAudioHandler _handler;
final List<StreamSubscription<dynamic>> _subscriptions = [];
bool _pausedByCall = false;
// #***! состояние отдельными notifier, плашки плеера подписаны
final ValueNotifier<bool> playing = ValueNotifier(false);
final ValueNotifier<Duration> position = ValueNotifier(Duration.zero);
final ValueNotifier<Duration> bufferedPosition = ValueNotifier(Duration.zero);
final ValueNotifier<Duration> duration = ValueNotifier(Duration.zero);
final ValueNotifier<AudioProcessingState> processingState = ValueNotifier(
AudioProcessingState.idle,
);
// #***! запуск трека
Future<void> playTrack(AudioFileTrack track) async {
error.value = null;
_pausedByCall = false;
position.value = Duration.zero;
bufferedPosition.value = Duration.zero;
duration.value = Duration.zero;
await _handler.load(track);
await _handler.play();
}
Future<void> toggle() {
_pausedByCall = false;
return playing.value ? _handler.pause() : _handler.play();
}
Future<void> seek(Duration value) => _handler.seek(value);
Future<void> stop() {
_pausedByCall = false;
return _handler.stop();
}
Future<void> dispose() async {
ActiveCall.instance.current.removeListener(_onActiveCallChanged);
for (final subscription in _subscriptions) {
await subscription.cancel();
}
_subscriptions.clear();
await _handler.dispose();
playing.dispose();
position.dispose();
bufferedPosition.dispose();
duration.dispose();
processingState.dispose();
if (identical(_instance, this)) {
_instance = null;
_pending = null;
}
}
// #***! на звонок ставим на паузу потом возвращаем
void _onActiveCallChanged() {
if (ActiveCall.instance.current.value != null) {
if (!playing.value) return;
_pausedByCall = true;
unawaited(_handler.pause());
return;
}
if (!_pausedByCall) return;
_pausedByCall = false;
if (processingState.value == AudioProcessingState.idle) return;
unawaited(_handler.play());
}
}
@@ -0,0 +1,118 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:just_audio/just_audio.dart';
import 'audio_file_track.dart';
// #***! обвязка audio_service, рисует уведомление и ловит кнопки наушников
class BackgroundAudioHandler extends BaseAudioHandler with SeekHandler {
BackgroundAudioHandler() {
_subscriptions.add(
_player.playbackEventStream.listen((_) => _broadcastState()),
);
_subscriptions.add(
_player.errorStream.listen((error) => errors.add(error.message ?? '')),
);
_subscriptions.add(_player.durationStream.listen(_updateDuration));
}
final AudioPlayer _player = AudioPlayer();
final StreamController<String> errors = StreamController.broadcast();
final List<StreamSubscription<dynamic>> _subscriptions = [];
Stream<Duration> get positionStream => _player.positionStream;
Stream<Duration> get bufferedPositionStream => _player.bufferedPositionStream;
// #***! загрузка трека с метаданными для шторки
Future<void> load(AudioFileTrack track) async {
final item = MediaItem(
id: track.cacheName,
title: track.name,
album: track.sourceName.isEmpty ? null : track.sourceName,
artUri: _artUri(track.thumbnailUrl),
extras: {
'path': track.path,
'chatId': track.chatId,
'messageId': track.messageId,
'messageTime': track.messageTime,
},
);
mediaItem.add(item);
final duration = await _player.setFilePath(track.path);
if (duration != null) mediaItem.add(item.copyWith(duration: duration));
_broadcastState();
}
Uri? _artUri(String? value) {
if (value == null || value.isEmpty) return null;
final uri = Uri.tryParse(value);
if (uri == null || !const {'http', 'https', 'file'}.contains(uri.scheme)) {
return null;
}
return uri;
}
void _updateDuration(Duration? duration) {
final item = mediaItem.value;
if (item == null || duration == null || item.duration == duration) return;
mediaItem.add(item.copyWith(duration: duration));
}
@override
Future<void> play() async {
if (_player.processingState == ProcessingState.completed) {
await _player.seek(Duration.zero);
}
await _player.play();
}
@override
Future<void> pause() => _player.pause();
@override
Future<void> seek(Duration position) => _player.seek(position);
@override
Future<void> stop() async {
await _player.stop();
await super.stop();
}
Future<void> dispose() async {
for (final subscription in _subscriptions) {
await subscription.cancel();
}
_subscriptions.clear();
await _player.dispose();
await errors.close();
}
// #***! состояние транслируем системе чтоб уведомление совпадало с плеером
void _broadcastState() {
playbackState.add(
playbackState.value.copyWith(
controls: [
if (_player.playing) MediaControl.pause else MediaControl.play,
MediaControl.stop,
],
androidCompactActionIndices: const [0],
processingState: _processingState(_player.processingState),
playing: _player.playing,
updatePosition: _player.position,
bufferedPosition: _player.bufferedPosition,
speed: _player.speed,
),
);
}
AudioProcessingState _processingState(ProcessingState state) {
return switch (state) {
ProcessingState.idle => AudioProcessingState.idle,
ProcessingState.loading => AudioProcessingState.loading,
ProcessingState.buffering => AudioProcessingState.buffering,
ProcessingState.ready => AudioProcessingState.ready,
ProcessingState.completed => AudioProcessingState.completed,
};
}
}
@@ -0,0 +1,53 @@
import 'package:flutter/services.dart';
import 'raw_clipboard_media.dart';
// #***! мост к нативному буферу, ошибки канала это пусто
class ClipboardChannel {
const ClipboardChannel._();
static const MethodChannel _channel = MethodChannel('ru.qlyra.app/clipboard');
static Future<bool> hasMedia() async {
try {
return await _channel.invokeMethod<bool>('hasMedia') ?? false;
} catch (_) {
return false;
}
}
// #***! приоритет у файлов, есть пути картинку не разбираем
static Future<RawClipboardMedia?> read() async {
Map<Object?, Object?>? raw;
try {
raw = await _channel.invokeMapMethod<Object?, Object?>('read');
} catch (_) {
return null;
}
if (raw == null) return null;
final paths = (raw['files'] as List<Object?>?)?.whereType<String>().toList(
growable: false,
);
if (paths != null && paths.isNotEmpty) {
return RawClipboardMedia(paths: paths);
}
final image = raw['image'];
if (image is Uint8List && image.isNotEmpty) {
return RawClipboardMedia(
png: image,
imageExtension: _extension(raw['imageExtension']),
);
}
return null;
}
static String? _extension(Object? value) {
if (value is! String) return null;
final trimmed = value.startsWith('.') ? value.substring(1) : value;
if (trimmed.isEmpty || trimmed.length > 5) return null;
if (!RegExp(r'^[A-Za-z0-9]+$').hasMatch(trimmed)) return null;
return '.${trimmed.toLowerCase()}';
}
}
@@ -0,0 +1,4 @@
// #***! на вебе буфера нет, заглушка
export 'clipboard_media_stub.dart'
if (dart.library.io) 'clipboard_media_io.dart';
export 'clipboard_media_types.dart';
@@ -0,0 +1,90 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'clipboard_channel.dart';
import 'clipboard_media_types.dart';
import 'dib_image.dart';
import 'raw_clipboard_media.dart';
import 'win32_clipboard.dart';
// #***! вставка файлов и картинок из буфера
class ClipboardMedia {
const ClipboardMedia._();
// #***! на винде WinAPI, на остальных нативный канал
static bool get supported {
if (Platform.isWindows) return Win32Clipboard.instance != null;
return Platform.isMacOS ||
Platform.isLinux ||
Platform.isAndroid ||
Platform.isIOS;
}
static Future<bool> hasMedia() async {
if (Platform.isWindows) {
return Win32Clipboard.instance?.hasMedia ?? false;
}
if (!supported) return false;
return ClipboardChannel.hasMedia();
}
// #***! сначала файлы, потом PNG, потом виндовый DIB
static Future<ClipboardMediaPayload?> read() async {
final raw = await _readRaw();
if (raw == null || raw.isEmpty) return null;
if (raw.paths.isNotEmpty) {
final files = <ClipboardFileRef>[];
for (final path in raw.paths) {
final file = File(path);
if (!file.existsSync()) continue;
files.add(
ClipboardFileRef(
path: path,
name: _basename(path),
size: file.lengthSync(),
),
);
}
if (files.isNotEmpty) return ClipboardMediaPayload(files: files);
}
final png = raw.png;
if (png != null && png.isNotEmpty) {
return ClipboardMediaPayload(
image: ClipboardImageData(
bytes: png,
extension: raw.imageExtension ?? '.png',
),
);
}
// #***! DIB в PNG в отдельном изоляте
final dib = raw.dib;
if (dib != null && dib.isNotEmpty) {
final decoded = await compute(dibToPng, dib);
if (decoded != null && decoded.isNotEmpty) {
return ClipboardMediaPayload(
image: ClipboardImageData(bytes: decoded, extension: '.png'),
);
}
}
return null;
}
static Future<RawClipboardMedia?> _readRaw() {
if (Platform.isWindows) {
final clipboard = Win32Clipboard.instance;
if (clipboard == null) return Future.value();
return clipboard.read();
}
if (!supported) return Future.value();
return ClipboardChannel.read();
}
}
String _basename(String path) {
final separator = path.lastIndexOf(RegExp(r'[\\/]'));
return separator < 0 ? path : path.substring(separator + 1);
}
@@ -0,0 +1,12 @@
import 'clipboard_media_types.dart';
// #***! заглушка, буфер всегда пуст
class ClipboardMedia {
const ClipboardMedia._();
static bool get supported => false;
static Future<bool> hasMedia() async => false;
static Future<ClipboardMediaPayload?> read() async => null;
}
@@ -0,0 +1,35 @@
import 'dart:typed_data';
// #***! файл из буфера
class ClipboardFileRef {
const ClipboardFileRef({
required this.path,
required this.name,
required this.size,
});
final String path;
final String name;
final int size;
}
// #***! картинка из буфера с расширением
class ClipboardImageData {
const ClipboardImageData({required this.bytes, required this.extension});
final Uint8List bytes;
final String extension;
}
// #***! что реально достали из буфера
class ClipboardMediaPayload {
const ClipboardMediaPayload({
this.files = const <ClipboardFileRef>[],
this.image,
});
final List<ClipboardFileRef> files;
final ClipboardImageData? image;
bool get isEmpty => files.isEmpty && image == null;
}
+68
View File
@@ -0,0 +1,68 @@
import 'dart:typed_data';
import 'package:image/image.dart' as img;
// #***! константы BMP
const int _biBitfields = 3;
const int _biAlphaBitfields = 6;
const int _fileHeaderSize = 14;
const int _coreHeaderSize = 12;
const int _infoHeaderSize = 40;
// #***! винда отдаёт картинку как DIB, это BMP без файлового заголовка
Uint8List? dibToPng(Uint8List dib) {
final bmp = _wrapDibAsBmp(dib);
if (bmp == null) return null;
try {
final decoded = img.decodeBmp(bmp);
if (decoded == null) return null;
return img.encodePng(decoded);
} catch (_) {
return null;
}
}
// #***! дописываем 14 байт заголовка, смещение пикселей считаем по палитре и маскам
Uint8List? _wrapDibAsBmp(Uint8List dib) {
if (dib.length < _coreHeaderSize) return null;
final source = ByteData.sublistView(dib);
final headerSize = source.getUint32(0, Endian.little);
if (headerSize != _coreHeaderSize && headerSize < _infoHeaderSize) {
return null;
}
if (dib.length < headerSize) return null;
final int bitCount;
final int compression;
final int paletteEntries;
if (headerSize == _coreHeaderSize) {
bitCount = source.getUint16(10, Endian.little);
compression = 0;
paletteEntries = bitCount <= 8 ? 1 << bitCount : 0;
} else {
bitCount = source.getUint16(14, Endian.little);
compression = source.getUint32(16, Endian.little);
final declared = source.getUint32(32, Endian.little);
paletteEntries = bitCount <= 8
? (declared != 0 ? declared : 1 << bitCount)
: declared;
}
var extra = paletteEntries * (headerSize == _coreHeaderSize ? 3 : 4);
if (headerSize == _infoHeaderSize) {
if (compression == _biBitfields) extra += 12;
if (compression == _biAlphaBitfields) extra += 16;
}
final pixelOffset = _fileHeaderSize + headerSize + extra;
if (pixelOffset >= _fileHeaderSize + dib.length) return null;
final bmp = Uint8List(_fileHeaderSize + dib.length);
final header = ByteData.sublistView(bmp, 0, _fileHeaderSize);
header.setUint8(0, 0x42);
header.setUint8(1, 0x4D);
header.setUint32(2, bmp.length, Endian.little);
header.setUint32(10, pixelOffset, Endian.little);
bmp.setRange(_fileHeaderSize, bmp.length, dib);
return bmp;
}
@@ -0,0 +1,112 @@
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import '../gallery_source.dart';
import 'clipboard_media.dart';
// #***! вставленные картинки лежат сутки
const Duration _pasteRetention = Duration(hours: 24);
// #***! как показать вставленное
enum PastedAttachmentKind { image, video, file }
// #***! файл из буфера готовый к отправке
class PastedAttachment {
const PastedAttachment({
required this.file,
required this.name,
required this.size,
required this.kind,
});
final File file;
final String name;
final int size;
final PastedAttachmentKind kind;
bool get isMedia => kind != PastedAttachmentKind.file;
}
// #***! содержимое буфера в файлы на диске
Future<List<PastedAttachment>> materializeClipboardMedia(
ClipboardMediaPayload payload,
) async {
final result = <PastedAttachment>[];
final image = payload.image;
if (image != null) {
final stored = await storePastedImage(image);
if (stored != null) result.add(stored);
}
for (final ref in payload.files) {
final file = File(ref.path);
if (!await file.exists()) continue;
result.add(
PastedAttachment(
file: file,
name: ref.name,
size: ref.size,
kind: _kindOf(ref.path),
),
);
}
return result;
}
// #***! картинку сначала сохраняем иначе её не отправить
Future<PastedAttachment?> storePastedImage(ClipboardImageData image) async {
try {
final dir = Directory(
'${(await getTemporaryDirectory()).path}/qlyra_paste',
);
await dir.create(recursive: true);
await _prune(dir);
final name =
'paste_${DateTime.now().millisecondsSinceEpoch}'
'${image.extension}';
final file = File('${dir.path}/$name');
await file.writeAsBytes(image.bytes, flush: true);
return PastedAttachment(
file: file,
name: name,
size: image.bytes.length,
kind: PastedAttachmentKind.image,
);
} catch (_) {
return null;
}
}
const Map<String, String> _imageExtensions = {
'image/png': '.png',
'image/jpeg': '.jpg',
'image/jpg': '.jpg',
'image/gif': '.gif',
'image/webp': '.webp',
'image/heic': '.heic',
'image/bmp': '.bmp',
};
// #***! клавиатура отдаёт mime, файлу нужно расширение
String pastedImageExtension(String mimeType) =>
_imageExtensions[mimeType.toLowerCase()] ?? '.png';
// #***! тип по расширению
PastedAttachmentKind _kindOf(String path) {
if (isVideoPath(path)) return PastedAttachmentKind.video;
if (isImagePath(path)) return PastedAttachmentKind.image;
return PastedAttachmentKind.file;
}
// #***! старые вставки чистим иначе папка растёт
Future<void> _prune(Directory dir) async {
final cutoff = DateTime.now().subtract(_pasteRetention);
try {
await for (final entry in dir.list()) {
if (entry is! File) continue;
if ((await entry.stat()).modified.isBefore(cutoff)) await entry.delete();
}
} catch (_) {}
}
@@ -0,0 +1,18 @@
import 'dart:typed_data';
// #***! сырой ответ натива, пути или байты картинки
class RawClipboardMedia {
const RawClipboardMedia({
this.paths = const <String>[],
this.png,
this.dib,
this.imageExtension,
});
final List<String> paths;
final Uint8List? png;
final Uint8List? dib;
final String? imageExtension;
bool get isEmpty => paths.isEmpty && png == null && dib == null;
}
@@ -0,0 +1,196 @@
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'raw_clipboard_media.dart';
const int _cfDib = 8;
const int _cfUnicodeText = 13;
const int _cfHdrop = 15;
const int _cfDibV5 = 17;
const int _pathBufferChars = 32768;
const int _maxFiles = 20;
const int _openAttempts = 8;
// #***! буфер может быть занят другим приложением, повторяем
const Duration _openRetryDelay = Duration(milliseconds: 25);
// #***! сигнатуры WinAPI для FFI
typedef _OpenClipboardC = Int32 Function(IntPtr);
typedef _OpenClipboardDart = int Function(int);
typedef _CloseClipboardC = Int32 Function();
typedef _CloseClipboardDart = int Function();
typedef _FormatAvailableC = Int32 Function(Uint32);
typedef _FormatAvailableDart = int Function(int);
typedef _GetClipboardDataC = IntPtr Function(Uint32);
typedef _GetClipboardDataDart = int Function(int);
typedef _RegisterFormatC = Uint32 Function(Pointer<Utf16>);
typedef _RegisterFormatDart = int Function(Pointer<Utf16>);
typedef _GlobalLockC = Pointer<Uint8> Function(IntPtr);
typedef _GlobalLockDart = Pointer<Uint8> Function(int);
typedef _GlobalUnlockC = Int32 Function(IntPtr);
typedef _GlobalUnlockDart = int Function(int);
typedef _GlobalSizeC = IntPtr Function(IntPtr);
typedef _GlobalSizeDart = int Function(int);
typedef _DragQueryFileC =
Uint32 Function(IntPtr, Uint32, Pointer<Utf16>, Uint32);
typedef _DragQueryFileDart = int Function(int, int, Pointer<Utf16>, int);
// #***! буфер винды напрямую через WinAPI, флаттер файлы оттуда не отдаёт
class Win32Clipboard {
Win32Clipboard._() {
final user32 = DynamicLibrary.open('user32.dll');
final kernel32 = DynamicLibrary.open('kernel32.dll');
final shell32 = DynamicLibrary.open('shell32.dll');
_open = user32.lookupFunction<_OpenClipboardC, _OpenClipboardDart>(
'OpenClipboard',
);
_close = user32.lookupFunction<_CloseClipboardC, _CloseClipboardDart>(
'CloseClipboard',
);
_formatAvailable = user32
.lookupFunction<_FormatAvailableC, _FormatAvailableDart>(
'IsClipboardFormatAvailable',
);
_getData = user32.lookupFunction<_GetClipboardDataC, _GetClipboardDataDart>(
'GetClipboardData',
);
_registerFormat = user32
.lookupFunction<_RegisterFormatC, _RegisterFormatDart>(
'RegisterClipboardFormatW',
);
_globalLock = kernel32.lookupFunction<_GlobalLockC, _GlobalLockDart>(
'GlobalLock',
);
_globalUnlock = kernel32.lookupFunction<_GlobalUnlockC, _GlobalUnlockDart>(
'GlobalUnlock',
);
_globalSize = kernel32.lookupFunction<_GlobalSizeC, _GlobalSizeDart>(
'GlobalSize',
);
_dragQueryFile = shell32
.lookupFunction<_DragQueryFileC, _DragQueryFileDart>('DragQueryFileW');
_pngFormat = _registerNamedFormat('PNG');
}
// #***! инстанс один раз, функции не нашлись значит фича выключена
static Win32Clipboard? _instance;
static bool _resolved = false;
static Win32Clipboard? get instance {
if (!Platform.isWindows) return null;
if (!_resolved) {
_resolved = true;
try {
_instance = Win32Clipboard._();
} catch (_) {
_instance = null;
}
}
return _instance;
}
late final _OpenClipboardDart _open;
late final _CloseClipboardDart _close;
late final _FormatAvailableDart _formatAvailable;
late final _GetClipboardDataDart _getData;
late final _RegisterFormatDart _registerFormat;
late final _GlobalLockDart _globalLock;
late final _GlobalUnlockDart _globalUnlock;
late final _GlobalSizeDart _globalSize;
late final _DragQueryFileDart _dragQueryFile;
late final int _pngFormat;
// #***! в буфере или файлы или картинка
bool get hasMedia => _has(_cfHdrop) || _hasImage;
bool get _hasImage =>
!_has(_cfUnicodeText) &&
(_has(_pngFormat) || _has(_cfDibV5) || _has(_cfDib));
// #***! чтение с ретраями, буфер надо открыть забрать и обязательно закрыть
Future<RawClipboardMedia?> read() async {
if (!hasMedia) return null;
for (var attempt = 0; attempt < _openAttempts; attempt++) {
if (_open(0) != 0) {
try {
final raw = _readOpened();
return raw == null || raw.isEmpty ? null : raw;
} finally {
_close();
}
}
await Future<void>.delayed(_openRetryDelay);
}
return null;
}
// #***! формат PNG не стандартный, регистрируем по имени
int _registerNamedFormat(String name) {
final native = name.toNativeUtf16();
try {
return _registerFormat(native);
} finally {
calloc.free(native);
}
}
bool _has(int format) => format != 0 && _formatAvailable(format) != 0;
RawClipboardMedia? _readOpened() {
if (_has(_cfHdrop)) {
final paths = _readPaths();
if (paths.isNotEmpty) return RawClipboardMedia(paths: paths);
}
if (!_hasImage) return null;
if (_has(_pngFormat)) {
final png = _copyGlobal(_getData(_pngFormat));
if (png != null) return RawClipboardMedia(png: png);
}
for (final format in const [_cfDibV5, _cfDib]) {
if (!_has(format)) continue;
final dib = _copyGlobal(_getData(format));
if (dib != null) return RawClipboardMedia(dib: dib);
}
return null;
}
// #***! пути достаём через DragQueryFile
List<String> _readPaths() {
final handle = _getData(_cfHdrop);
if (handle == 0) return const [];
final total = _dragQueryFile(handle, 0xFFFFFFFF, nullptr, 0);
if (total == 0) return const [];
final limit = total > _maxFiles ? _maxFiles : total;
final buffer = calloc<Uint16>(_pathBufferChars);
try {
final target = buffer.cast<Utf16>();
final paths = <String>[];
for (var i = 0; i < limit; i++) {
if (_dragQueryFile(handle, i, target, _pathBufferChars) == 0) continue;
final path = target.toDartString();
if (path.isNotEmpty) paths.add(path);
}
return paths;
} finally {
calloc.free(buffer);
}
}
// #***! данные надо залочить скопировать и разлочить
Uint8List? _copyGlobal(int handle) {
if (handle == 0) return null;
final size = _globalSize(handle);
if (size <= 0) return null;
final block = _globalLock(handle);
if (block == nullptr) return null;
try {
return Uint8List.fromList(block.asTypedList(size));
} finally {
_globalUnlock(handle);
}
}
}
+33 -16
View File
@@ -7,8 +7,10 @@ import 'package:photo_manager/photo_manager.dart';
import 'desktop_video_probe.dart';
// #***! доступ к галерее, полный частичный или запрещён
enum GalleryPermission { granted, limited, denied }
// #***! элемент галереи, за ним системный ассет или просто файл
abstract class GalleryItem {
String get id;
bool get isVideo;
@@ -25,6 +27,7 @@ abstract class GalleryItem {
static GalleryItem fromFile(File file) => _FileGalleryItem(file);
}
// #***! страница выдачи
class GalleryPage {
const GalleryPage({required this.items, required this.hasMore});
@@ -34,6 +37,7 @@ class GalleryPage {
final bool hasMore;
}
// #***! выбранное фото плюс результат редактирования
class PickedPhoto {
final GalleryItem item;
final File? editedFile;
@@ -41,6 +45,7 @@ class PickedPhoto {
const PickedPhoto({required this.item, this.editedFile});
}
// #***! размеры картинки без полного декодирования
Future<(int, int)?> imageFileDimensions(File file) async {
ui.ImmutableBuffer? buffer;
ui.ImageDescriptor? descriptor;
@@ -57,14 +62,34 @@ Future<(int, int)?> imageFileDimensions(File file) async {
}
}
// #***! галерея, на мобилках photo_manager на десктопе обход папок
abstract class GallerySource {
// #***! по 120 штук, столько влезает в несколько экранов сетки
static const int pageSize = 120;
static const Duration maxInt32Duration = Duration(milliseconds: 0x7fffffff);
// #***! фильтр без ограничений, иначе часть видео пропадает
static FilterOptionGroup mediaFilter() => FilterOptionGroup(
imageOption: const FilterOption(
sizeConstraint: SizeConstraint(ignoreSize: true),
),
videoOption: const FilterOption(
sizeConstraint: SizeConstraint(ignoreSize: true),
durationConstraint: DurationConstraint(
max: maxInt32Duration,
allowNullable: true,
),
),
createTimeCond: DateTimeCond.def().copyWith(ignore: true),
orders: const [OrderOption(type: OrderOptionType.createDate, asc: false)],
);
Future<GalleryPermission> ensurePermission();
Future<GalleryPage> load({int offset, int limit});
Future<void> openSettings();
Future<void> manageAccess();
// #***! альбом все спрашиваем один раз, дальше листаем диапазонами
factory GallerySource.create() {
if (Platform.isAndroid || Platform.isIOS) {
return _PhotoManagerSource();
@@ -85,21 +110,6 @@ class _PhotoManagerSource implements GallerySource {
AssetPathEntity? _album;
int _total = 0;
static FilterOptionGroup _filter() => FilterOptionGroup(
imageOption: const FilterOption(
sizeConstraint: SizeConstraint(ignoreSize: true),
),
videoOption: const FilterOption(
sizeConstraint: SizeConstraint(ignoreSize: true),
durationConstraint: DurationConstraint(
max: Duration(days: 365),
allowNullable: true,
),
),
createTimeCond: DateTimeCond.def().copyWith(ignore: true),
orders: const [OrderOption(type: OrderOptionType.createDate, asc: false)],
);
@override
Future<GalleryPage> load({
int offset = 0,
@@ -109,7 +119,7 @@ class _PhotoManagerSource implements GallerySource {
final paths = await PhotoManager.getAssetPathList(
type: RequestType.common,
onlyAll: true,
filterOption: _filter(),
filterOption: GallerySource.mediaFilter(),
);
if (paths.isEmpty) {
_album = null;
@@ -136,6 +146,7 @@ class _PhotoManagerSource implements GallerySource {
Future<void> manageAccess() => PhotoManager.presentLimited();
}
// #***! обёртка над системным ассетом
class _AssetGalleryItem implements GalleryItem {
final AssetEntity asset;
@@ -200,6 +211,7 @@ const Set<String> kGalleryVideoExtensions = {
'.3gp',
};
// #***! тип по расширению
String _fileExtension(String path) {
final dot = path.lastIndexOf('.');
if (dot < 0) return '';
@@ -209,6 +221,10 @@ String _fileExtension(String path) {
bool isVideoPath(String path) =>
kGalleryVideoExtensions.contains(_fileExtension(path));
bool isImagePath(String path) =>
kGalleryImageExtensions.contains(_fileExtension(path));
// #***! на десктопе галереи нет, сканируем стандартные папки
class _DesktopGallerySource implements GallerySource {
@override
Future<GalleryPermission> ensurePermission() async =>
@@ -283,6 +299,7 @@ class _DesktopGallerySource implements GallerySource {
}
}
// #***! обёртка над обычным файлом
class _FileGalleryItem implements GalleryItem {
final File file;
Duration? _duration;
+80 -1
View File
@@ -1,10 +1,17 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:flutter/foundation.dart';
import 'package:video_player/video_player.dart';
import 'audio_file_track.dart';
import 'audio_playback_controller.dart';
import 'voice_audio_controller.dart';
enum PlaybackKind { voice, videoNote }
// #***! что играет сейчас, голосовое кружок или музыка
enum PlaybackKind { voice, videoNote, audioFile }
// #***! играющее голосовое плюс сообщение откуда оно
class VoiceTrack {
const VoiceTrack({
required this.cacheName,
@@ -25,6 +32,7 @@ class VoiceTrack {
final VoiceAudioController audio;
}
// #***! играющий кружок
class VideoNoteTrack {
const VideoNoteTrack({
required this.cacheName,
@@ -47,15 +55,21 @@ class VideoNoteTrack {
final Uint8List? preview;
}
// #***! единый диспетчер, одновременно играет только что то одно
class MediaPlayback {
MediaPlayback._();
static final MediaPlayback instance = MediaPlayback._();
// #***! скорости которые перебирает кнопка
static const List<double> speeds = [1.0, 1.5, 2.0];
// #***! primary говорит юишке какую плашку рисовать
final ValueNotifier<PlaybackKind?> primary = ValueNotifier(null);
final ValueNotifier<AudioFileTrack?> audioFile = ValueNotifier(null);
bool _audioCompletionListenerAttached = false;
// #***! ушли из чата, играет дальше но плашка меняется
final ValueNotifier<int?> visibleChatId = ValueNotifier(null);
void enterChat(int chatId) => visibleChatId.value = chatId;
@@ -67,6 +81,7 @@ class MediaPlayback {
final ValueNotifier<VoiceTrack?> voice = ValueNotifier(null);
final ValueNotifier<double> voiceSpeed = ValueNotifier(speeds.first);
// #***! держатели не дают освободить контроллер пока его рисует виджет
final Set<VoiceAudioController> _heldVoice = {};
VoiceAudioController acquireVoice({
@@ -93,7 +108,9 @@ class MediaPlayback {
_disposeVoiceIfIdle(audio);
}
// #***! включили голосовое, кружок и музыка гаснут
void activateVoice(VoiceTrack track) {
_clearAudioFile();
_clearVideoNote();
final previous = voice.value;
if (previous != null && previous.audio != track.audio) {
@@ -106,6 +123,7 @@ class MediaPlayback {
track.audio.setSpeed(voiceSpeed.value);
}
// #***! перебор скорости по кругу
void cycleVoiceSpeed() {
final next = speeds[(speeds.indexOf(voiceSpeed.value) + 1) % speeds.length];
voiceSpeed.value = next;
@@ -126,12 +144,14 @@ class MediaPlayback {
return true;
}
// #***! освобождаем только когда никто не держит и он не активен
void _disposeVoiceIfIdle(VoiceAudioController audio) {
if (_heldVoice.contains(audio)) return;
if (voice.value?.audio == audio) return;
audio.dispose();
}
// #***! то же для кружков
final ValueNotifier<VideoNoteTrack?> videoNote = ValueNotifier(null);
final ValueNotifier<double> videoNoteSpeed = ValueNotifier(speeds.first);
@@ -156,6 +176,7 @@ class MediaPlayback {
}
void activateVideoNote(VideoNoteTrack track) {
_clearAudioFile();
_clearVoice();
final previous = videoNote.value;
if (previous != null && previous.controller != track.controller) {
@@ -195,4 +216,62 @@ class MediaPlayback {
if (videoNote.value?.controller == controller) return;
controller.dispose();
}
Future<void> activateAudioFile(
AudioFileTrack track, {
required String notificationChannelName,
}) async {
final audio = await AudioPlaybackController.ensureInitialized(
notificationChannelName,
);
_attachAudioCompletionListener(audio);
final current = audioFile.value;
if (current?.cacheName == track.cacheName) {
await audio.toggle();
return;
}
_clearVoice();
_clearVideoNote();
audioFile.value = track;
primary.value = PlaybackKind.audioFile;
try {
await audio.playTrack(track);
} catch (_) {
audioFile.value = null;
primary.value = null;
rethrow;
}
}
void closeAudioFile() {
if (!_clearAudioFile()) return;
primary.value = voice.value != null
? PlaybackKind.voice
: videoNote.value != null
? PlaybackKind.videoNote
: null;
}
bool _clearAudioFile() {
if (audioFile.value == null) return false;
audioFile.value = null;
if (AudioPlaybackController.isInitialized) {
unawaited(AudioPlaybackController.instance.stop());
}
return true;
}
void _attachAudioCompletionListener(AudioPlaybackController audio) {
if (_audioCompletionListenerAttached) return;
_audioCompletionListenerAttached = true;
audio.processingState.addListener(_onAudioProcessingStateChanged);
}
void _onAudioProcessingStateChanged() {
if (AudioPlaybackController.instance.processingState.value !=
AudioProcessingState.completed) {
return;
}
closeAudioFile();
}
}
+37 -10
View File
@@ -94,6 +94,28 @@ class RlottieEngine {
int _nextJobId = 1;
int _rrIndex = 0;
static const int _maxConcurrentDiskDecodes = 3;
int _activeDiskDecodes = 0;
final List<Completer<void>> _diskDecodeQueue = [];
Future<void> _acquireDiskDecodeSlot() async {
if (_activeDiskDecodes < _maxConcurrentDiskDecodes) {
_activeDiskDecodes++;
return;
}
final waiter = Completer<void>();
_diskDecodeQueue.add(waiter);
await waiter.future;
}
void _releaseDiskDecodeSlot() {
if (_diskDecodeQueue.isNotEmpty) {
_diskDecodeQueue.removeAt(0).complete();
} else {
_activeDiskDecodes--;
}
}
bool? _available;
Future<List<SendPort>>? _poolFuture;
@@ -279,18 +301,23 @@ class RlottieEngine {
}
Future<void> _decodeDiskProgressive(RlottieClip clip, DiskClip disk) async {
for (var i = 0; i < disk.frameCount; i++) {
if (!identical(_clips[clip.key], clip)) return;
final image = await _decode(disk.frames[i], clip.px);
if (!identical(_clips[clip.key], clip)) {
image.dispose();
return;
await _acquireDiskDecodeSlot();
try {
for (var i = 0; i < disk.frameCount; i++) {
if (!identical(_clips[clip.key], clip)) return;
final image = await _decode(disk.frames[i], clip.px);
if (!identical(_clips[clip.key], clip)) {
image.dispose();
return;
}
clip._setFrame(i, image);
_totalBytes += clip.px * clip.px * 4;
}
clip._setFrame(i, image);
_totalBytes += clip.px * clip.px * 4;
clip.complete = true;
_evictIfNeeded();
} finally {
_releaseDiskDecodeSlot();
}
clip.complete = true;
_evictIfNeeded();
}
Future<ui.Image> _decode(Uint8List bgra, int px) {
+12
View File
@@ -0,0 +1,12 @@
Future<void> sendMediaSeparately<T>(
List<T> items,
String caption, {
required Future<void> Function(T item, String caption) send,
required bool Function() canSend,
}) async {
final pending = List<T>.of(items);
for (var i = 0; i < pending.length; i++) {
if (!canSend()) return;
await send(pending[i], i == 0 ? caption : '');
}
}
+12 -5
View File
@@ -236,9 +236,9 @@ class VideoTranscoder {
if (startMs > 0) {
args.addAll(['-ss', (startMs / 1000).toStringAsFixed(3)]);
}
args.addAll(['-i', spec.input]);
args.addAll(['-i', File(spec.input).absolute.path]);
final overlay = spec.overlayPath;
if (overlay != null) args.addAll(['-i', overlay]);
if (overlay != null) args.addAll(['-i', File(overlay).absolute.path]);
final endMs = spec.endMs;
if (endMs != null && endMs > startMs) {
args.addAll(['-t', ((endMs - startMs) / 1000).toStringAsFixed(3)]);
@@ -269,7 +269,10 @@ class VideoTranscoder {
}
chain.add('scale=${spec.outWidth}:${spec.outHeight}');
if (lut != null) {
chain.add("lut3d=file='${lut.path.replaceAll("'", r"\'")}'");
// The generated basename is safe in FFmpeg's filter syntax. Use its
// directory as cwd so drive letters and user directory names never
// need to pass through the filter parser's two escaping layers.
chain.add('lut3d=file=${p.basename(lut.path)}');
}
chain.add('format=yuv420p');
@@ -299,9 +302,13 @@ class VideoTranscoder {
} else {
args.addAll(['-c:a', 'aac', '-b:a', '128k']);
}
args.addAll(['-movflags', '+faststart', spec.output]);
args.addAll(['-movflags', '+faststart', File(spec.output).absolute.path]);
final process = await Process.start('ffmpeg', args);
final process = await Process.start(
'ffmpeg',
args,
workingDirectory: lut?.parent.absolute.path,
);
_desktopProcess = process;
final totalMs = (endMs ?? 0) - startMs;
final progress = process.stdout
+20
View File
@@ -0,0 +1,20 @@
import 'dart:typed_data';
abstract interface class PluginHost {
String get args;
Map<String, dynamic> get arguments;
Map<String, dynamic>? get replyMessage;
bool get isOnline;
bool get isActive;
Future<String> sendText(String text);
Future<void> editText(String messageId, String text);
Future<void> sendPhoto(
Uint8List bytes, {
required String filename,
required String caption,
});
Future<void> sendFile(Uint8List bytes, {required String filename});
Future<void> notify(String message);
Future<Map<String, dynamic>?> getPeer();
}
+44
View File
@@ -0,0 +1,44 @@
import 'dart:async';
import 'dart:io';
import 'plugin_models.dart';
import 'plugin_package.dart';
class PluginInstaller {
const PluginInstaller();
static const _timeout = Duration(seconds: 20);
static const _maxBytes = 5 * 1024 * 1024;
Future<PluginPackagePreview> preview(List<int> bytes) =>
PluginPackage.preview(bytes);
Future<PluginPackagePreview> download(Uri uri) async {
if (uri.scheme != 'https') {
throw const FormatException('Плагин можно загрузить только по HTTPS');
}
final client = HttpClient()..connectionTimeout = _timeout;
try {
final request = await client.getUrl(uri);
request.headers.set(
HttpHeaders.userAgentHeader,
'QlyraPluginInstaller/1',
);
final response = await request.close().timeout(_timeout);
if (response.statusCode != HttpStatus.ok) {
await response.drain<void>();
throw HttpException('HTTP ${response.statusCode}', uri: uri);
}
final bytes = <int>[];
await for (final chunk in response.timeout(_timeout)) {
bytes.addAll(chunk);
if (bytes.length > _maxBytes) {
throw const FormatException('.kinet слишком большой');
}
}
return await preview(bytes);
} finally {
client.close(force: true);
}
}
}
+340
View File
@@ -0,0 +1,340 @@
import 'dart:convert';
const int kPluginApiVersion = 1;
const String kPluginPackageExtension = '.kinet';
enum PluginPermission {
chatWrite('chat.write', 'Отправка сообщений'),
chatEdit('chat.edit', 'Редактирование отправленных сообщений'),
uiNotify('ui.notify', 'Показ уведомлений'),
contactRead('contact.read', 'Чтение данных собеседника'),
replyRead(
'message.readReply',
'Чтение сообщения, на которое отвечает команда',
),
network('network', 'Доступ к интернету'),
photoWrite('chat.photo', 'Отправка фотографий'),
fileWrite('chat.file', 'Отправка файлов'),
storage('storage', 'Локальное хранилище плагина');
const PluginPermission(this.id, this.label);
final String id;
final String label;
static PluginPermission? fromId(String id) {
for (final permission in values) {
if (permission.id == id) return permission;
}
return null;
}
}
class PluginCommandManifest {
const PluginCommandManifest({
required this.name,
required this.description,
required this.handler,
this.arguments = const [],
this.hidden = false,
});
final String name;
final String description;
final String handler;
final List<PluginCommandArgumentManifest> arguments;
final bool hidden;
factory PluginCommandManifest.fromJson(Map<String, dynamic> json) {
final rawName = _requiredString(json, 'name');
final name = rawName.startsWith('/') ? rawName : '/$rawName';
if (!RegExp(r'^/[A-Za-z][A-Za-z0-9_-]{0,31}$').hasMatch(name)) {
throw const FormatException('Некорректное имя команды');
}
final handler = _requiredString(json, 'handler');
if (!RegExp(r'^[A-Za-z_$][A-Za-z0-9_$]*$').hasMatch(handler)) {
throw const FormatException('Некорректное имя обработчика');
}
final rawArguments = json['arguments'];
final arguments = <PluginCommandArgumentManifest>[];
if (rawArguments != null) {
if (rawArguments is! List) {
throw const FormatException('arguments должен быть массивом');
}
for (final raw in rawArguments) {
if (raw is! Map) {
throw const FormatException('Некорректный аргумент команды');
}
arguments.add(
PluginCommandArgumentManifest.fromJson(
Map<String, dynamic>.from(raw),
),
);
}
}
final argumentNames = <String>{};
for (var index = 0; index < arguments.length; index++) {
final argument = arguments[index];
if (!argumentNames.add(argument.name)) {
throw FormatException('Аргумент ${argument.name} объявлен дважды');
}
if (argument.rest && index != arguments.length - 1) {
throw const FormatException('rest-аргумент должен быть последним');
}
}
return PluginCommandManifest(
name: name,
description: _requiredString(json, 'description'),
handler: handler,
arguments: List.unmodifiable(arguments),
hidden: json['hidden'] == true,
);
}
Map<String, dynamic> toJson() => {
'name': name,
'description': description,
'handler': handler,
if (arguments.isNotEmpty)
'arguments': arguments.map((argument) => argument.toJson()).toList(),
if (hidden) 'hidden': true,
};
}
class PluginCommandArgumentManifest {
const PluginCommandArgumentManifest({
required this.name,
required this.description,
required this.required,
required this.rest,
});
final String name;
final String description;
final bool required;
final bool rest;
factory PluginCommandArgumentManifest.fromJson(Map<String, dynamic> json) {
final name = _requiredString(json, 'name');
if (!RegExp(r'^[A-Za-z][A-Za-z0-9_-]{0,31}$').hasMatch(name)) {
throw const FormatException('Некорректное имя аргумента');
}
return PluginCommandArgumentManifest(
name: name,
description: _optionalString(json, 'description'),
required: json['required'] != false,
rest: json['rest'] == true,
);
}
Map<String, dynamic> toJson() => {
'name': name,
'description': description,
'required': required,
if (rest) 'rest': true,
};
}
class PluginManifest {
const PluginManifest({
required this.id,
required this.name,
required this.version,
required this.apiVersion,
required this.description,
required this.author,
required this.main,
required this.permissions,
required this.commands,
this.updateUrl,
this.signature,
});
final String id;
final String name;
final String version;
final int apiVersion;
final String description;
final String author;
final String main;
final Set<PluginPermission> permissions;
final List<PluginCommandManifest> commands;
final Uri? updateUrl;
final PluginSignatureManifest? signature;
factory PluginManifest.fromJson(Map<String, dynamic> json) {
final schemaVersion = json['schemaVersion'];
if (schemaVersion != 1) {
throw const FormatException('Неподдерживаемая версия manifest');
}
final id = _requiredString(json, 'id');
if (!RegExp(r'^[a-z][a-z0-9]*(?:\.[a-z0-9]+)+$').hasMatch(id)) {
throw const FormatException('Некорректный id плагина');
}
final version = _requiredString(json, 'version');
if (!RegExp(r'^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$').hasMatch(version)) {
throw const FormatException('Некорректная версия плагина');
}
final apiVersion = json['apiVersion'];
if (apiVersion is! int || apiVersion < 1) {
throw const FormatException('Некорректная версия API');
}
if (apiVersion > kPluginApiVersion) {
throw FormatException('Плагину требуется API $apiVersion');
}
final main = _safeRelativePath(_requiredString(json, 'main'));
if (!main.endsWith('.js')) {
throw const FormatException(
'Главный модуль должен быть JavaScript-файлом',
);
}
final rawPermissions = json['permissions'];
if (rawPermissions is! List) {
throw const FormatException('permissions должен быть массивом');
}
final permissions = <PluginPermission>{};
for (final raw in rawPermissions) {
if (raw is! String) {
throw const FormatException('Некорректное разрешение');
}
final permission = PluginPermission.fromId(raw);
if (permission == null) {
throw FormatException('Неизвестное разрешение: $raw');
}
permissions.add(permission);
}
final rawCommands = json['commands'];
if (rawCommands is! List || rawCommands.isEmpty) {
throw const FormatException('Плагин должен содержать команды');
}
final commands = rawCommands
.map((raw) {
if (raw is! Map) {
throw const FormatException('Некорректная команда');
}
return PluginCommandManifest.fromJson(Map<String, dynamic>.from(raw));
})
.toList(growable: false);
final commandNames = <String>{};
for (final command in commands) {
if (!commandNames.add(command.name.toLowerCase())) {
throw FormatException('Команда ${command.name} объявлена дважды');
}
}
Uri? updateUrl;
final rawUpdateUrl = json['updateUrl'];
if (rawUpdateUrl != null) {
if (rawUpdateUrl is! String) {
throw const FormatException('Некорректный updateUrl');
}
updateUrl = Uri.tryParse(rawUpdateUrl.trim());
if (updateUrl == null || updateUrl.scheme != 'https') {
throw const FormatException('updateUrl должен использовать HTTPS');
}
}
PluginSignatureManifest? signature;
final rawSignature = json['signature'];
if (rawSignature != null) {
if (rawSignature is! Map) {
throw const FormatException('Некорректная подпись плагина');
}
signature = PluginSignatureManifest.fromJson(
Map<String, dynamic>.from(rawSignature),
);
}
return PluginManifest(
id: id,
name: _requiredString(json, 'name'),
version: version,
apiVersion: apiVersion,
description: _optionalString(json, 'description'),
author: _optionalString(json, 'author'),
main: main,
permissions: Set.unmodifiable(permissions),
commands: List.unmodifiable(commands),
updateUrl: updateUrl,
signature: signature,
);
}
factory PluginManifest.decode(String source) {
final decoded = jsonDecode(source);
if (decoded is! Map) {
throw const FormatException('manifest.json должен быть объектом');
}
return PluginManifest.fromJson(Map<String, dynamic>.from(decoded));
}
Map<String, dynamic> toJson() => {
'schemaVersion': 1,
'id': id,
'name': name,
'version': version,
'apiVersion': apiVersion,
'description': description,
'author': author,
'main': main,
'permissions': permissions.map((permission) => permission.id).toList(),
'commands': commands.map((command) => command.toJson()).toList(),
if (updateUrl != null) 'updateUrl': updateUrl.toString(),
if (signature != null) 'signature': signature!.toJson(),
};
Map<String, dynamic> toUnsignedJson() {
final json = toJson();
json.remove('signature');
return json;
}
}
class PluginSignatureManifest {
const PluginSignatureManifest({
required this.algorithm,
required this.publicKey,
required this.value,
});
final String algorithm;
final String publicKey;
final String value;
factory PluginSignatureManifest.fromJson(Map<String, dynamic> json) {
final algorithm = _requiredString(json, 'algorithm');
if (algorithm != 'ed25519') {
throw FormatException('Неподдерживаемый алгоритм подписи: $algorithm');
}
return PluginSignatureManifest(
algorithm: algorithm,
publicKey: _requiredString(json, 'publicKey'),
value: _requiredString(json, 'value'),
);
}
Map<String, dynamic> toJson() => {
'algorithm': algorithm,
'publicKey': publicKey,
'value': value,
};
}
String _requiredString(Map<String, dynamic> json, String key) {
final value = json[key];
if (value is! String || value.trim().isEmpty) {
throw FormatException('Поле $key обязательно');
}
return value.trim();
}
String _optionalString(Map<String, dynamic> json, String key) {
final value = json[key];
return value is String ? value.trim() : '';
}
String _safeRelativePath(String path) {
final normalized = path.replaceAll('\\', '/');
if (normalized.startsWith('/') ||
normalized.split('/').any((part) => part.isEmpty || part == '..')) {
throw const FormatException('Некорректный путь в плагине');
}
return normalized;
}
@@ -0,0 +1,138 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
class PluginMediaDownloader {
PluginMediaDownloader._();
static const int _attempts = 3;
static const int _maxRedirects = 5;
static const Duration _connectionTimeout = Duration(seconds: 10);
static const Duration _responseTimeout = Duration(seconds: 20);
static Future<Uint8List> download(
Uri uri, {
required int maxBytes,
bool allowHttpForTesting = false,
}) async {
Object? lastError;
for (var attempt = 0; attempt < _attempts; attempt++) {
try {
return await _downloadOnce(
uri,
maxBytes: maxBytes,
allowHttpForTesting: allowHttpForTesting,
);
} on FormatException {
rethrow;
} on HttpException catch (error) {
lastError = error;
} on SocketException catch (error) {
lastError = error;
} on TimeoutException catch (error) {
lastError = error;
}
if (attempt + 1 < _attempts) {
await Future.delayed(Duration(milliseconds: 250 * (attempt + 1)));
}
}
throw HttpException(
'Не удалось полностью загрузить файл после $_attempts попыток: $lastError',
uri: uri,
);
}
static Future<Uint8List> _downloadOnce(
Uri initialUri, {
required int maxBytes,
required bool allowHttpForTesting,
}) async {
final client = HttpClient()..connectionTimeout = _connectionTimeout;
try {
var uri = initialUri;
for (var redirect = 0; redirect <= _maxRedirects; redirect++) {
_validateUri(uri, allowHttpForTesting: allowHttpForTesting);
final request = await client.getUrl(uri);
request
..followRedirects = false
..persistentConnection = false;
request.headers
..set(HttpHeaders.userAgentHeader, 'QlyraPluginMedia/1')
..set(
HttpHeaders.acceptHeader,
'image/*, application/octet-stream;q=0.9, */*;q=0.1',
)
..set(HttpHeaders.cacheControlHeader, 'no-cache');
final response = await request.close().timeout(_responseTimeout);
if (response.isRedirect) {
final location = response.headers.value(HttpHeaders.locationHeader);
await response.drain<void>();
if (location == null || redirect == _maxRedirects) {
throw HttpException('Некорректный HTTP redirect', uri: uri);
}
uri = uri.resolve(location);
continue;
}
if (response.statusCode < 200 || response.statusCode >= 300) {
await response.drain<void>();
throw HttpException('HTTP ${response.statusCode}', uri: uri);
}
final contentLength = response.contentLength;
if (contentLength > maxBytes) {
await response.drain<void>();
throw const FormatException('Файл слишком большой');
}
final bytes = <int>[];
await for (final chunk in response.timeout(_responseTimeout)) {
bytes.addAll(chunk);
if (bytes.length > maxBytes) {
throw const FormatException('Файл слишком большой');
}
}
if (contentLength >= 0 && bytes.length != contentLength) {
throw HttpException(
'Получено ${bytes.length} из $contentLength байт',
uri: uri,
);
}
return Uint8List.fromList(bytes);
}
throw HttpException('Слишком много HTTP redirect', uri: initialUri);
} finally {
client.close(force: true);
}
}
static void _validateUri(Uri uri, {required bool allowHttpForTesting}) {
final validScheme =
uri.scheme == 'https' || (allowHttpForTesting && uri.scheme == 'http');
if (!validScheme || uri.host.isEmpty) {
throw const FormatException('Разрешены только корректные HTTPS URL');
}
if (allowHttpForTesting) return;
final host = uri.host.toLowerCase();
if (host == 'localhost' || host.endsWith('.localhost')) {
throw const FormatException('Локальные адреса запрещены');
}
final address = InternetAddress.tryParse(host);
if (address != null && _isPrivateAddress(address)) {
throw const FormatException('Локальные адреса запрещены');
}
}
static bool _isPrivateAddress(InternetAddress address) {
if (address.isLoopback || address.isLinkLocal) return true;
final bytes = address.rawAddress;
if (address.type == InternetAddressType.IPv4) {
return bytes[0] == 10 ||
bytes[0] == 127 ||
bytes[0] == 0 ||
(bytes[0] == 169 && bytes[1] == 254) ||
(bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) ||
(bytes[0] == 192 && bytes[1] == 168);
}
return bytes.every((byte) => byte == 0) ||
(bytes[0] & 0xfe) == 0xfc ||
(bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80);
}
}
+72
View File
@@ -0,0 +1,72 @@
import 'plugin_manifest.dart';
enum PluginOrigin { bundled, installed }
enum PluginSignatureStatus { unsigned, verified, bundled }
class PluginDescriptor {
const PluginDescriptor({
required this.manifest,
required this.origin,
required this.enabled,
required this.grantedPermissions,
required this.loadModules,
required this.signatureStatus,
this.signerFingerprint,
});
final PluginManifest manifest;
final PluginOrigin origin;
final bool enabled;
final Set<PluginPermission> grantedPermissions;
final Future<Map<String, String>> Function() loadModules;
final PluginSignatureStatus signatureStatus;
final String? signerFingerprint;
PluginDescriptor copyWith({bool? enabled}) => PluginDescriptor(
manifest: manifest,
origin: origin,
enabled: enabled ?? this.enabled,
grantedPermissions: grantedPermissions,
loadModules: loadModules,
signatureStatus: signatureStatus,
signerFingerprint: signerFingerprint,
);
}
class PluginCommandDescriptor {
const PluginCommandDescriptor({required this.plugin, required this.command});
final PluginDescriptor plugin;
final PluginCommandManifest command;
}
class PluginPackagePreview {
const PluginPackagePreview({
required this.manifest,
required this.bytes,
required this.signatureStatus,
this.signerFingerprint,
});
final PluginManifest manifest;
final List<int> bytes;
final PluginSignatureStatus signatureStatus;
final String? signerFingerprint;
}
class PluginUpdateInfo {
const PluginUpdateInfo({
required this.plugin,
required this.version,
required this.packageUrl,
required this.size,
required this.sha256,
});
final PluginDescriptor plugin;
final String version;
final Uri packageUrl;
final int size;
final String sha256;
}
@@ -0,0 +1,30 @@
class PluginOutgoingText {
const PluginOutgoingText({required this.plaintext, required this.wireText});
final String plaintext;
final String wireText;
bool get encrypted => plaintext != wireText;
}
class PluginOutgoingTextException implements Exception {
const PluginOutgoingTextException(this.message);
final String message;
@override
String toString() => message;
}
Future<PluginOutgoingText> preparePluginOutgoingText(
String plaintext,
Future<String?> Function(String plaintext) encrypt,
) async {
final wireText = await encrypt(plaintext);
if (wireText == null) {
throw const PluginOutgoingTextException(
'Не удалось зашифровать сообщение плагина',
);
}
return PluginOutgoingText(plaintext: plaintext, wireText: wireText);
}
+88
View File
@@ -0,0 +1,88 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:archive/archive.dart';
import 'plugin_manifest.dart';
import 'plugin_models.dart';
import 'plugin_signing.dart';
const int _maxPackageBytes = 5 * 1024 * 1024;
const int _maxExtractedBytes = 10 * 1024 * 1024;
const int _maxFiles = 128;
const int _maxFileBytes = 2 * 1024 * 1024;
class PluginPackage {
const PluginPackage({required this.manifest, required this.files});
final PluginManifest manifest;
final Map<String, Uint8List> files;
static Future<PluginPackagePreview> preview(List<int> bytes) async {
final package = decode(bytes);
final verification = await PluginSigning.verify(
package.manifest,
package.files,
);
return PluginPackagePreview(
manifest: package.manifest,
bytes: bytes,
signatureStatus: verification.status,
signerFingerprint: verification.fingerprint,
);
}
static PluginPackage decode(List<int> bytes) {
if (bytes.isEmpty || bytes.length > _maxPackageBytes) {
throw const FormatException('Некорректный размер .kinet');
}
final archive = ZipDecoder().decodeBytes(bytes, verify: true);
if (archive.isEmpty || archive.length > _maxFiles) {
throw const FormatException('Некорректное количество файлов');
}
final files = <String, Uint8List>{};
var extractedSize = 0;
for (final entry in archive) {
if (entry.isSymbolicLink) {
throw const FormatException('Символические ссылки запрещены');
}
if (!entry.isFile) continue;
final name = _safePath(entry.name);
if (entry.size > _maxFileBytes) {
throw FormatException('Файл $name слишком большой');
}
final content = entry.content;
extractedSize += content.length;
if (extractedSize > _maxExtractedBytes) {
throw const FormatException('Распакованный плагин слишком большой');
}
if (files.containsKey(name)) {
throw FormatException('Файл $name объявлен дважды');
}
files[name] = content;
}
final manifestBytes = files['manifest.json'];
if (manifestBytes == null) {
throw const FormatException('manifest.json не найден');
}
final manifest = PluginManifest.decode(utf8.decode(manifestBytes));
if (!files.containsKey(manifest.main)) {
throw FormatException('${manifest.main} не найден');
}
for (final path in files.keys) {
if (path != 'manifest.json' && !path.endsWith('.js')) {
throw FormatException('Неподдерживаемый файл: $path');
}
}
return PluginPackage(manifest: manifest, files: Map.unmodifiable(files));
}
}
String _safePath(String raw) {
final path = raw.replaceAll('\\', '/');
if (path.startsWith('/') ||
path.split('/').any((part) => part.isEmpty || part == '..')) {
throw const FormatException('Опасный путь в архиве');
}
return path;
}
+498
View File
@@ -0,0 +1,498 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:fjs/fjs.dart';
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'
show ExternalLibrary;
import 'package:path/path.dart' as p;
import 'plugin_host.dart';
import 'plugin_manifest.dart';
import 'plugin_media_downloader.dart';
import 'plugin_models.dart';
import 'plugin_storage.dart';
class PluginRuntime {
PluginRuntime._();
static Future<void>? _initialization;
static Future<void> initialize({ExternalLibrary? externalLibrary}) async {
final pending = _initialization ??= LibFjs.init(
externalLibrary: externalLibrary,
);
try {
await pending;
} catch (_) {
if (identical(_initialization, pending)) _initialization = null;
rethrow;
}
}
static Future<void> run(
PluginCommandDescriptor command,
PluginHost host,
) async {
await initialize();
final plugin = command.plugin;
final storage = PluginStorage(plugin.manifest.id);
final sentMessageIds = <String>{};
final engine = await JsEngine.create(
builtins: JsBuiltinOptions.none(),
runtimeOptions: JsEngineRuntimeOptions(
memoryLimit: BigInt.from(16 * 1024 * 1024),
gcThreshold: BigInt.from(4 * 1024 * 1024),
maxStackSize: BigInt.from(256 * 1024),
info: plugin.manifest.id,
),
);
var closed = false;
Future<void> close() async {
if (closed) return;
closed = true;
await engine.close();
}
try {
await engine.init(
bridge: (value) =>
_bridge(plugin, host, storage, sentMessageIds, value),
);
await engine.declareNewModule(
module: JsModule.code(module: 'komet:api', code: _apiModule),
);
final sources = await plugin.loadModules();
final prefix = 'plugin:${plugin.manifest.id}/';
await engine.declareNewModules(
modules: sources.entries
.map(
(entry) => JsModule.code(
module: '$prefix${entry.key}',
code: _rewriteImports(entry.value, prefix, entry.key),
),
)
.toList(),
);
final moduleName = '$prefix${plugin.manifest.main}';
final call = engine.call(
module: moduleName,
method: command.command.handler,
params: [
JsValue.from({
'args': host.args,
'arguments': host.arguments,
'reply':
plugin.grantedPermissions.contains(PluginPermission.replyRead)
? host.replyMessage
: null,
'apiVersion': kPluginApiVersion,
}),
],
);
await call.timeout(
const Duration(seconds: 30),
onTimeout: () async {
await close();
throw TimeoutException('Плагин превысил лимит времени');
},
);
} finally {
await close();
}
}
static Future<JsResult> _bridge(
PluginDescriptor plugin,
PluginHost host,
PluginStorage storage,
Set<String> sentMessageIds,
JsValue value,
) async {
try {
if (!host.isActive) throw StateError('Чат плагина закрыт');
final request = value.value;
if (request is! Map) {
throw const FormatException('Некорректный вызов API');
}
final method = request['method'];
final args = request['args'];
if (method is! String || args is! List) {
throw const FormatException('Некорректный вызов API');
}
final Object? result;
switch (method) {
case 'chat.sendText':
result = await _sendText(plugin, host, sentMessageIds, args);
case 'chat.editText':
await _editText(plugin, host, sentMessageIds, args);
result = null;
case 'chat.sendPhoto':
await _sendPhoto(plugin, host, args);
result = null;
case 'chat.sendFile':
await _sendFile(plugin, host, args);
result = null;
case 'ui.notify':
await _notify(plugin, host, args);
result = null;
case 'contact.getPeer':
result = await _getPeer(plugin, host);
case 'runtime.sleep':
await _sleep(args);
result = null;
case 'runtime.isOnline':
result = host.isOnline;
case 'runtime.isActive':
result = host.isActive;
case 'network.fetch':
result = await _fetch(plugin, args);
case 'storage.get':
result = await _storageGet(plugin, storage, args);
case 'storage.set':
await _storageSet(plugin, storage, args);
result = null;
case 'storage.remove':
await _storageRemove(plugin, storage, args);
result = null;
default:
throw FormatException('Неизвестный метод API: $method');
}
return JsResult.ok(JsValue.from({'ok': true, 'value': result}));
} catch (error) {
return JsResult.ok(JsValue.from({'ok': false, 'error': '$error'}));
}
}
static Future<String> _sendText(
PluginDescriptor plugin,
PluginHost host,
Set<String> sentMessageIds,
List<dynamic> args,
) async {
_require(plugin, PluginPermission.chatWrite);
final id = await host.sendText(_stringArg(args, 0));
if (id.isNotEmpty) sentMessageIds.add(id);
return id;
}
static Future<void> _editText(
PluginDescriptor plugin,
PluginHost host,
Set<String> sentMessageIds,
List<dynamic> args,
) {
_require(plugin, PluginPermission.chatEdit);
final messageId = _stringArg(args, 0);
if (!sentMessageIds.contains(messageId)) {
throw const FormatException(
'Плагин может редактировать только созданные им сообщения',
);
}
return host.editText(messageId, _stringArg(args, 1));
}
static Future<void> _notify(
PluginDescriptor plugin,
PluginHost host,
List<dynamic> args,
) {
_require(plugin, PluginPermission.uiNotify);
return host.notify(_stringArg(args, 0));
}
static Future<void> _sendPhoto(
PluginDescriptor plugin,
PluginHost host,
List<dynamic> args,
) async {
_require(plugin, PluginPermission.photoWrite);
final options = _mapArg(args, 0);
final bytes = await _mediaBytes(
plugin,
options,
maxBytes: 15 * 1024 * 1024,
);
await host.sendPhoto(
bytes,
filename: _filename(options, 'plugin_photo.jpg'),
caption: options['caption']?.toString() ?? '',
);
}
static Future<void> _sendFile(
PluginDescriptor plugin,
PluginHost host,
List<dynamic> args,
) async {
_require(plugin, PluginPermission.fileWrite);
final options = _mapArg(args, 0);
final bytes = await _mediaBytes(
plugin,
options,
maxBytes: 25 * 1024 * 1024,
);
await host.sendFile(bytes, filename: _filename(options, 'plugin_file.bin'));
}
static Future<Map<String, dynamic>> _fetch(
PluginDescriptor plugin,
List<dynamic> args,
) async {
_require(plugin, PluginPermission.network);
final url = _stringArg(args, 0);
final options = args.length > 1 && args[1] is Map
? Map<String, dynamic>.from(args[1] as Map)
: const <String, dynamic>{};
final uri = _httpsUri(url);
final method = (options['method']?.toString() ?? 'GET').toUpperCase();
if (!const {'GET', 'POST', 'PUT', 'PATCH', 'DELETE'}.contains(method)) {
throw const FormatException('Неподдерживаемый HTTP-метод');
}
final client = HttpClient()
..connectionTimeout = const Duration(seconds: 10);
try {
final request = await client.openUrl(method, uri);
request.followRedirects = false;
final rawHeaders = options['headers'];
if (rawHeaders is Map) {
rawHeaders.forEach((key, value) {
final name = key.toString();
if (_forbiddenHeader(name)) return;
request.headers.set(name, value.toString());
});
}
final body = options['body'];
if (body != null) request.write(body.toString());
final response = await request.close().timeout(
const Duration(seconds: 15),
);
if (response.isRedirect) {
await response.drain<void>();
throw const HttpException('HTTP redirects are disabled for plugins');
}
final bytes = await _readLimited(response, 1024 * 1024);
final headers = <String, String>{};
response.headers.forEach((name, values) {
headers[name] = values.join(', ');
});
return {
'status': response.statusCode,
'headers': headers,
'body': utf8.decode(bytes, allowMalformed: true),
'base64': base64Encode(bytes),
};
} finally {
client.close(force: true);
}
}
static Future<Uint8List> _mediaBytes(
PluginDescriptor plugin,
Map<String, dynamic> options, {
required int maxBytes,
}) async {
final encoded = options['base64'];
if (encoded is String && encoded.isNotEmpty) {
final bytes = base64Decode(encoded);
if (bytes.length > maxBytes) {
throw const FormatException('Файл слишком большой');
}
return bytes;
}
final url = options['url'];
if (url is! String || url.isEmpty) {
throw const FormatException('Нужно указать url или base64');
}
_require(plugin, PluginPermission.network);
return PluginMediaDownloader.download(_httpsUri(url), maxBytes: maxBytes);
}
static Future<Uint8List> _readLimited(
HttpClientResponse response,
int maxBytes,
) async {
final bytes = <int>[];
await for (final chunk in response.timeout(const Duration(seconds: 20))) {
bytes.addAll(chunk);
if (bytes.length > maxBytes) {
throw const FormatException('Ответ слишком большой');
}
}
return Uint8List.fromList(bytes);
}
static Uri _httpsUri(String source) {
final uri = Uri.tryParse(source);
if (uri == null || uri.scheme != 'https' || uri.host.isEmpty) {
throw const FormatException('Разрешены только корректные HTTPS URL');
}
final host = uri.host.toLowerCase();
if (host == 'localhost' || host.endsWith('.localhost')) {
throw const FormatException('Локальные адреса запрещены');
}
final address = InternetAddress.tryParse(host);
if (address != null && _isPrivateAddress(address)) {
throw const FormatException('Локальные адреса запрещены');
}
return uri;
}
static bool _isPrivateAddress(InternetAddress address) {
if (address.isLoopback || address.isLinkLocal) return true;
final bytes = address.rawAddress;
if (address.type == InternetAddressType.IPv4) {
return bytes[0] == 10 ||
bytes[0] == 127 ||
bytes[0] == 0 ||
(bytes[0] == 169 && bytes[1] == 254) ||
(bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) ||
(bytes[0] == 192 && bytes[1] == 168);
}
return bytes.every((byte) => byte == 0) ||
(bytes[0] & 0xfe) == 0xfc ||
(bytes[0] == 0xfe && (bytes[1] & 0xc0) == 0x80);
}
static bool _forbiddenHeader(String name) {
final lower = name.toLowerCase();
return lower == 'host' ||
lower == 'content-length' ||
lower == 'connection' ||
lower == 'proxy-authorization';
}
static Map<String, dynamic> _mapArg(List<dynamic> args, int index) {
if (index >= args.length || args[index] is! Map) {
throw const FormatException('Ожидался объект');
}
return Map<String, dynamic>.from(args[index] as Map);
}
static String _filename(Map<String, dynamic> options, String fallback) {
final raw = options['filename']?.toString().trim() ?? '';
final value = raw.isEmpty ? fallback : raw;
return value
.replaceAll(RegExp(r'[^A-Za-zА-Яа-яЁё0-9._ -]'), '_')
.substring(0, value.length > 120 ? 120 : value.length);
}
static Future<Map<String, dynamic>?> _getPeer(
PluginDescriptor plugin,
PluginHost host,
) {
_require(plugin, PluginPermission.contactRead);
return host.getPeer();
}
static Future<void> _sleep(List<dynamic> args) async {
final value = args.isEmpty ? null : args.first;
if (value is! num || value < 0 || value > 10000) {
throw const FormatException('Некорректная задержка');
}
await Future.delayed(Duration(milliseconds: value.round()));
}
static Future<Object?> _storageGet(
PluginDescriptor plugin,
PluginStorage storage,
List<dynamic> args,
) {
_require(plugin, PluginPermission.storage);
return storage.get(_storageKey(args));
}
static Future<void> _storageSet(
PluginDescriptor plugin,
PluginStorage storage,
List<dynamic> args,
) {
_require(plugin, PluginPermission.storage);
if (args.length < 2) throw const FormatException('Не задано значение');
return storage.set(_storageKey(args), args[1]);
}
static Future<void> _storageRemove(
PluginDescriptor plugin,
PluginStorage storage,
List<dynamic> args,
) {
_require(plugin, PluginPermission.storage);
return storage.remove(_storageKey(args));
}
static void _require(PluginDescriptor plugin, PluginPermission permission) {
if (!plugin.grantedPermissions.contains(permission)) {
throw FormatException('Нет разрешения ${permission.id}');
}
}
static String _stringArg(List<dynamic> args, int index) {
if (index >= args.length || args[index] is! String) {
throw const FormatException('Ожидалась строка');
}
final value = args[index] as String;
if (value.length > 65536) {
throw const FormatException('Строка слишком длинная');
}
return value;
}
static String _storageKey(List<dynamic> args) {
final key = _stringArg(args, 0);
if (!RegExp(r'^[A-Za-z0-9._-]{1,64}$').hasMatch(key)) {
throw const FormatException('Некорректный ключ хранилища');
}
return key;
}
static String _rewriteImports(
String source,
String prefix,
String modulePath,
) {
return source.replaceAllMapped(
RegExp(r'''(from\s+|import\s+|import\s*\()(['"])(\.?\.?/[^'"]+)\2'''),
(match) {
final relative = match.group(3)!;
final resolved = p.posix.normalize(
p.posix.join(p.posix.dirname(modulePath), relative),
);
if (resolved == '..' || resolved.startsWith('../')) {
throw const FormatException('Импорт за пределы плагина запрещён');
}
return '${match.group(1)}${match.group(2)}$prefix$resolved${match.group(2)}';
},
);
}
static const String _apiModule = '''
const call = async (method, args = []) => {
const response = await fjs.bridge_call({ method, args });
if (!response.ok) throw new Error(response.error || 'Qlyra API error');
return response.value;
};
export const chat = Object.freeze({
sendText: text => call('chat.sendText', [text]),
editText: (messageId, text) => call('chat.editText', [messageId, text]),
sendPhoto: options => call('chat.sendPhoto', [options]),
sendFile: options => call('chat.sendFile', [options])
});
export const ui = Object.freeze({ notify: message => call('ui.notify', [message]) });
export const contact = Object.freeze({ getPeer: () => call('contact.getPeer') });
export const runtime = Object.freeze({
sleep: milliseconds => call('runtime.sleep', [milliseconds]),
isOnline: () => call('runtime.isOnline'),
isActive: () => call('runtime.isActive')
});
export const network = Object.freeze({
fetch: (url, options = {}) => call('network.fetch', [url, options])
});
export const storage = Object.freeze({
get: key => call('storage.get', [key]),
set: (key, value) => call('storage.set', [key, value]),
remove: key => call('storage.remove', [key])
});
''';
}
+128
View File
@@ -0,0 +1,128 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:cryptography/cryptography.dart';
import 'plugin_manifest.dart';
import 'plugin_models.dart';
class PluginSignatureVerification {
const PluginSignatureVerification({required this.status, this.fingerprint});
final PluginSignatureStatus status;
final String? fingerprint;
}
class PluginSigning {
PluginSigning._();
static final Ed25519 _algorithm = Ed25519();
static Future<PluginSignatureVerification> verify(
PluginManifest manifest,
Map<String, Uint8List> files,
) async {
final signature = manifest.signature;
if (signature == null) {
return const PluginSignatureVerification(
status: PluginSignatureStatus.unsigned,
);
}
try {
final publicKeyBytes = base64Decode(signature.publicKey);
final signatureBytes = base64Decode(signature.value);
if (publicKeyBytes.length != 32 || signatureBytes.length != 64) {
throw const FormatException('Некорректный размер ключа или подписи');
}
final publicKey = SimplePublicKey(
publicKeyBytes,
type: KeyPairType.ed25519,
);
final valid = await _algorithm.verify(
payload(manifest, files),
signature: Signature(signatureBytes, publicKey: publicKey),
);
if (!valid) {
throw const FormatException('Подпись плагина недействительна');
}
return PluginSignatureVerification(
status: PluginSignatureStatus.verified,
fingerprint: fingerprint(publicKeyBytes),
);
} on FormatException {
rethrow;
} catch (_) {
throw const FormatException('Подпись плагина недействительна');
}
}
static Uint8List payload(
PluginManifest manifest,
Map<String, Uint8List> files,
) {
final modules = <String, String>{};
final paths = files.keys.where((path) => path.endsWith('.js')).toList()
..sort();
for (final path in paths) {
modules[path] = sha256.convert(files[path]!).toString();
}
final canonical = _canonicalJson({
'format': 'komet-plugin-signature-v1',
'manifest': manifest.toUnsignedJson(),
'modules': modules,
});
return Uint8List.fromList(utf8.encode(canonical));
}
static Future<PluginSignatureManifest> sign(
PluginManifest manifest,
Map<String, Uint8List> files,
List<int> privateKeyBytes,
) async {
if (privateKeyBytes.length != 32) {
throw const FormatException(
'Приватный Ed25519 ключ должен содержать 32 байта',
);
}
final keyPair = await _algorithm.newKeyPairFromSeed(privateKeyBytes);
final signed = await _algorithm.sign(
payload(manifest, files),
keyPair: keyPair,
);
final publicKey = await keyPair.extractPublicKey();
return PluginSignatureManifest(
algorithm: 'ed25519',
publicKey: base64Encode(publicKey.bytes),
value: base64Encode(signed.bytes),
);
}
static Future<({List<int> privateKey, List<int> publicKey})>
generateKeyPair() async {
final keyPair = await _algorithm.newKeyPair();
return (
privateKey: await keyPair.extractPrivateKeyBytes(),
publicKey: (await keyPair.extractPublicKey()).bytes,
);
}
static String fingerprint(List<int> publicKey) {
final digest = sha256.convert(publicKey).toString().toUpperCase();
return List.generate(
8,
(index) => digest.substring(index * 4, index * 4 + 4),
).join(':');
}
static String _canonicalJson(Object? value) {
if (value is Map) {
final keys = value.keys.map((key) => key.toString()).toList()..sort();
return '{${keys.map((key) => '${jsonEncode(key)}:${_canonicalJson(value[key])}').join(',')}}';
}
if (value is List) {
return '[${value.map(_canonicalJson).join(',')}]';
}
return jsonEncode(value);
}
}
+48
View File
@@ -0,0 +1,48 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class PluginStorage {
PluginStorage(this.pluginId);
final String pluginId;
String get _key => 'plugin_storage_v1_$pluginId';
Future<Map<String, dynamic>> _readAll() async {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(_key);
if (raw == null) return {};
try {
final decoded = jsonDecode(raw);
return decoded is Map ? Map<String, dynamic>.from(decoded) : {};
} catch (_) {
return {};
}
}
Future<Object?> get(String key) async => (await _readAll())[key];
Future<void> set(String key, Object? value) async {
final all = await _readAll();
all[key] = value;
final encoded = jsonEncode(all);
if (encoded.length > 65536) {
throw const FormatException('Хранилище плагина переполнено');
}
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_key, encoded);
}
Future<void> remove(String key) async {
final all = await _readAll();
if (all.remove(key) == null) return;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_key, jsonEncode(all));
}
Future<void> clear() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_key);
}
}
+299
View File
@@ -0,0 +1,299 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../storage/app_instance.dart';
import 'plugin_manifest.dart';
import 'plugin_models.dart';
import 'plugin_package.dart';
import 'plugin_signing.dart';
import 'plugin_storage.dart';
class PluginStore {
PluginStore._();
static final PluginStore instance = PluginStore._();
static const _stateKey = 'plugins_state_v1';
static const _bundled = <String>[
'assets/plugins/info',
'assets/plugins/nekos',
'assets/plugins/weather',
];
final ValueNotifier<List<PluginDescriptor>> plugins = ValueNotifier(const []);
Directory? _root;
Map<String, dynamic> _state = {};
static bool isBundledId(String id) => id.startsWith('pw.qlyra.');
Future<void> load() async {
final prefs = await SharedPreferences.getInstance();
final rawState = prefs.getString(_stateKey);
if (rawState != null) {
try {
final decoded = jsonDecode(rawState);
if (decoded is Map) _state = Map<String, dynamic>.from(decoded);
} catch (_) {}
}
final base = await getApplicationSupportDirectory();
_root = Directory(p.join(base.path, 'plugins${AppInstance.suffix}'));
await _root!.create(recursive: true);
await _recoverInterruptedInstalls();
await refresh();
}
Future<void> _recoverInterruptedInstalls() async {
final root = _root;
if (root == null) return;
await for (final entity in root.list()) {
if (entity is! Directory) continue;
final name = p.basename(entity.path);
if (!name.startsWith('.')) continue;
if (name.endsWith('.backup')) {
final pluginId = name.substring(1, name.length - '.backup'.length);
final target = Directory(p.join(root.path, pluginId));
if (await target.exists()) {
await entity.delete(recursive: true);
} else {
await entity.rename(target.path);
}
} else {
await entity.delete(recursive: true);
}
}
}
Future<void> refresh() async {
final descriptors = <PluginDescriptor>[];
for (final assetPath in _bundled) {
try {
descriptors.add(await _loadBundled(assetPath));
} catch (_) {}
}
final root = _root;
if (root != null && await root.exists()) {
await for (final entity in root.list()) {
if (entity is! Directory || p.basename(entity.path).startsWith('.')) {
continue;
}
try {
descriptors.add(await _loadInstalled(entity));
} catch (_) {}
}
}
descriptors.sort((a, b) {
final origin = a.origin.index.compareTo(b.origin.index);
return origin != 0 ? origin : a.manifest.name.compareTo(b.manifest.name);
});
plugins.value = List.unmodifiable(descriptors);
}
Future<PluginDescriptor> _loadBundled(String assetPath) async {
final manifest = PluginManifest.decode(
await rootBundle.loadString('$assetPath/manifest.json'),
);
return PluginDescriptor(
manifest: manifest,
origin: PluginOrigin.bundled,
enabled: _enabled(manifest.id, fallback: true),
grantedPermissions: manifest.permissions,
loadModules: () async => {
manifest.main: await rootBundle.loadString(
'$assetPath/${manifest.main}',
),
},
signatureStatus: PluginSignatureStatus.bundled,
signerFingerprint: 'KOMET:BUNDLED',
);
}
Future<PluginDescriptor> _loadInstalled(Directory directory) async {
final manifestFile = File(p.join(directory.path, 'manifest.json'));
final manifestBytes = await manifestFile.readAsBytes();
final manifest = PluginManifest.decode(utf8.decode(manifestBytes));
final state = _pluginState(manifest.id);
var signerFingerprint = state['signerFingerprint']?.toString();
if (manifest.signature != null) {
final files = await _loadInstalledBytes(directory);
files['manifest.json'] = manifestBytes;
final verification = await PluginSigning.verify(manifest, files);
if (signerFingerprint != null &&
verification.fingerprint != signerFingerprint) {
throw const FormatException(
'Ключ подписи установленного плагина изменён',
);
}
signerFingerprint = verification.fingerprint;
} else if (signerFingerprint != null) {
throw const FormatException('Подпись установленного плагина удалена');
}
final granted = <PluginPermission>{};
final rawGranted = state['granted'];
if (rawGranted is List) {
for (final raw in rawGranted.whereType<String>()) {
final permission = PluginPermission.fromId(raw);
if (permission != null && manifest.permissions.contains(permission)) {
granted.add(permission);
}
}
}
return PluginDescriptor(
manifest: manifest,
origin: PluginOrigin.installed,
enabled: _enabled(manifest.id, fallback: true),
grantedPermissions: Set.unmodifiable(granted),
loadModules: () => _loadInstalledModules(directory),
signatureStatus: signerFingerprint == null
? PluginSignatureStatus.unsigned
: PluginSignatureStatus.verified,
signerFingerprint: signerFingerprint,
);
}
Future<Map<String, String>> _loadInstalledModules(Directory directory) async {
final modules = <String, String>{};
await for (final entity in directory.list(recursive: true)) {
if (entity is! File || !entity.path.endsWith('.js')) continue;
final relative = p
.relative(entity.path, from: directory.path)
.replaceAll('\\', '/');
modules[relative] = await entity.readAsString();
}
return modules;
}
Future<Map<String, Uint8List>> _loadInstalledBytes(
Directory directory,
) async {
final files = <String, Uint8List>{};
await for (final entity in directory.list(recursive: true)) {
if (entity is! File || !entity.path.endsWith('.js')) continue;
final relative = p
.relative(entity.path, from: directory.path)
.replaceAll('\\', '/');
files[relative] = await entity.readAsBytes();
}
return files;
}
Future<PluginDescriptor> install(
List<int> bytes, {
required Set<PluginPermission> grantedPermissions,
Uri? sourceUrl,
}) async {
final package = PluginPackage.decode(bytes);
final verification = await PluginSigning.verify(
package.manifest,
package.files,
);
if (isBundledId(package.manifest.id)) {
throw const FormatException('Этот id зарезервирован Qlyra');
}
if (!package.manifest.permissions.containsAll(grantedPermissions)) {
throw const FormatException('Выданы неизвестные разрешения');
}
final previousState = _pluginState(package.manifest.id);
final previousPublicKey = previousState['signerPublicKey']?.toString();
final signerPublicKey = package.manifest.signature?.publicKey;
if (previousPublicKey != null && signerPublicKey != previousPublicKey) {
throw const FormatException(
'Обновление должно быть подписано прежним ключом автора',
);
}
final root = _root;
if (root == null) throw StateError('PluginStore не инициализирован');
final target = Directory(p.join(root.path, package.manifest.id));
final staging = Directory(
p.join(
root.path,
'.${package.manifest.id}.${DateTime.now().microsecondsSinceEpoch}',
),
);
final backup = Directory(
p.join(root.path, '.${package.manifest.id}.backup'),
);
await staging.create(recursive: true);
try {
for (final entry in package.files.entries) {
final file = File(p.join(staging.path, entry.key));
await file.parent.create(recursive: true);
await file.writeAsBytes(entry.value, flush: true);
}
if (await backup.exists()) await backup.delete(recursive: true);
if (await target.exists()) await target.rename(backup.path);
try {
await staging.rename(target.path);
} catch (_) {
if (await backup.exists()) await backup.rename(target.path);
rethrow;
}
if (await backup.exists()) await backup.delete(recursive: true);
_state[package.manifest.id] = {
'enabled': true,
'granted': grantedPermissions
.map((permission) => permission.id)
.toList(),
if (sourceUrl != null) 'sourceUrl': sourceUrl.toString(),
'signerFingerprint': ?verification.fingerprint,
'signerPublicKey': ?signerPublicKey,
};
await _persistState();
await refresh();
return plugins.value.firstWhere(
(plugin) => plugin.manifest.id == package.manifest.id,
);
} finally {
if (await staging.exists()) await staging.delete(recursive: true);
}
}
Future<void> setEnabled(String pluginId, bool enabled) async {
final state = _pluginState(pluginId);
state['enabled'] = enabled;
_state[pluginId] = state;
await _persistState();
await refresh();
}
Future<void> uninstall(String pluginId) async {
final plugin = plugins.value.firstWhere(
(item) => item.manifest.id == pluginId,
);
if (plugin.origin == PluginOrigin.bundled) {
throw StateError('Встроенный плагин нельзя удалить');
}
final root = _root;
if (root != null) {
final directory = Directory(p.join(root.path, pluginId));
if (await directory.exists()) await directory.delete(recursive: true);
}
_state.remove(pluginId);
await PluginStorage(pluginId).clear();
await _persistState();
await refresh();
}
Uri? sourceUrl(String pluginId) {
final raw = _pluginState(pluginId)['sourceUrl'];
return raw is String ? Uri.tryParse(raw) : null;
}
bool _enabled(String pluginId, {required bool fallback}) {
final value = _pluginState(pluginId)['enabled'];
return value is bool ? value : fallback;
}
Map<String, dynamic> _pluginState(String pluginId) {
final raw = _state[pluginId];
return raw is Map ? Map<String, dynamic>.from(raw) : <String, dynamic>{};
}
Future<void> _persistState() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_stateKey, jsonEncode(_state));
}
}
+150
View File
@@ -0,0 +1,150 @@
import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'plugin_installer.dart';
import 'plugin_models.dart';
import 'plugin_store.dart';
class PluginUpdater {
PluginUpdater({
PluginInstaller installer = const PluginInstaller(),
PluginStore? store,
}) : _installer = installer,
_store = store ?? PluginStore.instance;
final PluginInstaller _installer;
final PluginStore _store;
Future<PluginUpdateInfo?> check(PluginDescriptor plugin) async {
final manifestUrl = plugin.manifest.updateUrl;
if (manifestUrl == null) return null;
final client = HttpClient()
..connectionTimeout = const Duration(seconds: 15);
try {
final request = await client.getUrl(manifestUrl);
request.headers.set(HttpHeaders.userAgentHeader, 'QlyraPluginUpdater/1');
final response = await request.close().timeout(
const Duration(seconds: 15),
);
if (response.statusCode != HttpStatus.ok) {
await response.drain<void>();
throw HttpException('HTTP ${response.statusCode}', uri: manifestUrl);
}
final decoded = jsonDecode(
await response.transform(const Utf8Decoder()).join(),
);
if (decoded is! Map) {
throw const FormatException('Некорректный update manifest');
}
final version = decoded['version'];
final packageUrl = decoded['packageUrl'];
final size = decoded['size'];
final digest = decoded['sha256'];
if (version is! String ||
packageUrl is! String ||
size is! int ||
digest is! String) {
throw const FormatException('Некорректный update manifest');
}
if (_compareVersions(version, plugin.manifest.version) <= 0) return null;
final uri = manifestUrl.resolve(packageUrl);
if (uri.scheme != 'https') {
throw const FormatException('packageUrl должен использовать HTTPS');
}
return PluginUpdateInfo(
plugin: plugin,
version: version,
packageUrl: uri,
size: size,
sha256: digest.toLowerCase(),
);
} finally {
client.close(force: true);
}
}
Future<PluginDescriptor> apply(PluginUpdateInfo update) async {
final preview = await _installer.download(update.packageUrl);
if (preview.manifest.id != update.plugin.manifest.id ||
preview.manifest.version != update.version) {
throw const FormatException('Обновление принадлежит другому плагину');
}
if (update.size > 0 && preview.bytes.length != update.size) {
throw const FormatException('Размер обновления не совпадает');
}
if (update.sha256.isNotEmpty &&
sha256.convert(preview.bytes).toString() != update.sha256) {
throw const FormatException('SHA-256 обновления не совпадает');
}
final missing = preview.manifest.permissions.difference(
update.plugin.grantedPermissions,
);
if (missing.isNotEmpty) {
throw FormatException(
'Обновление запрашивает новые разрешения: ${missing.map((item) => item.label).join(', ')}',
);
}
return _store.install(
preview.bytes,
grantedPermissions: update.plugin.grantedPermissions.intersection(
preview.manifest.permissions,
),
sourceUrl: _store.sourceUrl(update.plugin.manifest.id),
);
}
}
int _compareVersions(String a, String b) {
final left = _ParsedVersion.parse(a);
final right = _ParsedVersion.parse(b);
for (var i = 0; i < 3; i++) {
final comparison = left.core[i].compareTo(right.core[i]);
if (comparison != 0) return comparison;
}
if (left.preRelease.isEmpty && right.preRelease.isNotEmpty) return 1;
if (left.preRelease.isNotEmpty && right.preRelease.isEmpty) return -1;
final length = left.preRelease.length > right.preRelease.length
? left.preRelease.length
: right.preRelease.length;
for (var i = 0; i < length; i++) {
if (i >= left.preRelease.length) return -1;
if (i >= right.preRelease.length) return 1;
final leftPart = left.preRelease[i];
final rightPart = right.preRelease[i];
final leftNumber = int.tryParse(leftPart);
final rightNumber = int.tryParse(rightPart);
if (leftNumber != null && rightNumber != null) {
final comparison = leftNumber.compareTo(rightNumber);
if (comparison != 0) return comparison;
continue;
}
if (leftNumber != null) return -1;
if (rightNumber != null) return 1;
final comparison = leftPart.compareTo(rightPart);
if (comparison != 0) return comparison;
}
return 0;
}
class _ParsedVersion {
const _ParsedVersion(this.core, this.preRelease);
final List<int> core;
final List<String> preRelease;
factory _ParsedVersion.parse(String value) {
final withoutBuild = value.split('+').first;
final separator = withoutBuild.indexOf('-');
final coreSource = separator == -1
? withoutBuild
: withoutBuild.substring(0, separator);
final preRelease = separator == -1
? const <String>[]
: withoutBuild.substring(separator + 1).split('.');
final core = coreSource.split('.').map(int.parse).toList();
if (core.length != 3) throw const FormatException('Некорректная версия');
return _ParsedVersion(core, preRelease);
}
}
+7
View File
@@ -102,3 +102,10 @@ bool isSessionStateError(Object error) {
text.contains('авторизационная сессия') ||
text.contains('сессия не онлайн');
}
bool isAuthSessionLostError(Object error) {
if (error is SessionExpiredException) return true;
final text = error.toString().toLowerCase();
return text.contains('сессия не найдена') ||
text.contains('авторизационная сессия');
}
+35 -17
View File
@@ -8,6 +8,7 @@ import '../../frontend/widgets/max_link_nav.dart';
import '../../main.dart';
import '../utils/logger.dart';
// #***! открытие чата по тапу на уведомление
class NotificationBridge {
NotificationBridge._();
static final NotificationBridge instance = NotificationBridge._();
@@ -17,13 +18,18 @@ class NotificationBridge {
static const _retryDelay = Duration(milliseconds: 300);
static const _maxRetries = 100;
// #***! стек открытых чатов, натив не уведомляет про то что на экране
final List<int> _activeChats = [];
bool _started = false;
bool _ready = false;
int _pendingChatId = 0;
int _activeChatId = 0;
int _sentChatId = 0;
int _retriesLeft = 0;
Timer? _retry;
int get _activeChatId => _activeChats.isEmpty ? 0 : _activeChats.last;
bool get _native {
try {
return Platform.isAndroid || Platform.isIOS;
@@ -32,6 +38,7 @@ class NotificationBridge {
}
}
// #***! подписка на уведомления и сессию
void init() {
if (_started || !_native) return;
_started = true;
@@ -49,6 +56,7 @@ class NotificationBridge {
_flushPending();
}
// #***! запустили тапом по уведомлению, забираем чат который натив придержал
Future<void> checkInitialChat() async {
if (!_native) return;
try {
@@ -58,28 +66,37 @@ class NotificationBridge {
}
}
Future<void> setActiveChat(int chatId) async {
// #***! вошли в чат, говорим нативу чтоб не уведомлял
Future<void> pushActiveChat(int chatId) async {
if (!_native || chatId <= 0) return;
if (_activeChatId == chatId) return;
_activeChatId = chatId;
_activeChats.add(chatId);
await _syncActiveChat();
}
Future<void> popActiveChat(int chatId) async {
if (!_native || chatId <= 0) return;
final index = _activeChats.lastIndexOf(chatId);
if (index < 0) return;
_activeChats.removeAt(index);
await _syncActiveChat();
}
Future<void> _syncActiveChat() async {
final chatId = _activeChatId;
if (chatId == _sentChatId) return;
_sentChatId = chatId;
try {
await _method.invokeMethod<void>('setActiveChat', {'chatId': chatId});
if (chatId > 0) {
await _method.invokeMethod<void>('setActiveChat', {'chatId': chatId});
} else {
await _method.invokeMethod<void>('clearActiveChat');
}
} catch (e) {
logger.w('NotificationBridge.setActiveChat: $e');
}
}
Future<void> clearActiveChat(int chatId) async {
if (!_native) return;
if (chatId > 0 && _activeChatId != chatId) return;
_activeChatId = 0;
try {
await _method.invokeMethod<void>('clearActiveChat');
} catch (e) {
logger.w('NotificationBridge.clearActiveChat: $e');
logger.w('NotificationBridge: активный чат не синхронизирован: $e');
}
}
// #***! событие это просто id чата
void _onEvent(Object? event) {
final chatId = event is int ? event : int.tryParse(event?.toString() ?? '');
if (chatId == null || chatId <= 0) return;
@@ -88,6 +105,7 @@ class NotificationBridge {
_flushPending();
}
// #***! ждём дерево и сессию иначе ретраим, открытый чат не переоткрываем
void _flushPending() {
final chatId = _pendingChatId;
if (chatId <= 0) return;
+23 -6
View File
@@ -210,7 +210,6 @@ class PushService {
await initLocalNotificationActions();
final messaging = FirebaseMessaging.instance;
await messaging.requestPermission();
messaging.onTokenRefresh.listen((t) async {
_token = t;
@@ -220,8 +219,27 @@ class PushService {
final prefs = await SharedPreferences.getInstance();
_token = prefs.getString(_prefsTokenKey);
final settings = await messaging.getNotificationSettings();
if (!_isAuthorized(settings.authorizationStatus)) return;
await _refreshToken();
}
Future<bool> requestPermissionFromUser() async {
if (!_initialized) return false;
final settings = await FirebaseMessaging.instance.requestPermission();
if (!_isAuthorized(settings.authorizationStatus)) return false;
await _refreshToken();
await _registerWithServer();
return true;
}
bool _isAuthorized(AuthorizationStatus status) =>
status == AuthorizationStatus.authorized ||
status == AuthorizationStatus.provisional;
Future<void> _refreshToken() async {
try {
_token = await messaging.getToken() ?? _token;
_token = await FirebaseMessaging.instance.getToken() ?? _token;
if (_token != null) await _persistToken(_token!);
logger.i('Push: FCM-токен получен (${_token?.length ?? 0} симв.)');
} catch (e) {
@@ -232,10 +250,9 @@ class PushService {
Future<void> onLoginSuccess() async {
if (!_initialized) return;
if (_token == null) {
try {
_token = await FirebaseMessaging.instance.getToken();
if (_token != null) await _persistToken(_token!);
} catch (_) {}
final settings = await FirebaseMessaging.instance
.getNotificationSettings();
if (_isAuthorized(settings.authorizationStatus)) await _refreshToken();
}
await _registerWithServer();
}
+54 -1
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'message_persistence.dart';
import 'package:qlyra/core/storage/app_instance.dart';
import 'package:qlyra/core/utils/logger.dart';
@@ -9,6 +10,7 @@ import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart' show databaseFactorySqflitePlugin;
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
// #***! профиль как строка таблицы profile
class ProfileData {
final int id;
final String firstName;
@@ -91,6 +93,7 @@ class ProfileData {
);
}
// #***! profileOptions в базе строкой а от сервера списком
static List<int>? _parseProfileOptions(dynamic raw) {
if (raw is! List) return null;
final options = raw
@@ -129,6 +132,7 @@ class ProfileData {
);
}
// #***! обратно в строку для sqflite
Map<String, dynamic> toDbRow({bool isActive = false}) => {
'id': id,
'first_name': firstName,
@@ -145,6 +149,7 @@ class ProfileData {
};
}
// #***! ключи sync_state, докуда мы досинхронизировались
abstract class SyncKey {
static const chatsSync = 'chats_sync';
static const contactsSync = 'contacts_sync';
@@ -157,13 +162,17 @@ abstract class SyncKey {
static const chatCacheFingerprint = 'chat_cache_fingerprint';
static const serverTime = 'server_time';
static const loginInfo = 'login_info';
static const serverConfigSeen = 'server_config_seen';
static const profileInviteLink = 'profile_invite_link';
}
// #***! вся локальная база, профили чаты контакты сообщения
class AppDatabase {
static Database? _db;
static String? _mobileDbDir;
// #***! зовётся один раз на старте до первого обращения
static Future<void> init() async {
if (Platform.isAndroid || Platform.isIOS) {
_mobileDbDir = await databaseFactorySqflitePlugin.getDatabasesPath();
@@ -174,6 +183,7 @@ class AppDatabase {
static Completer<Database>? _initCompleter;
// #***! ленивое открытие с защитой от гонки чтоб базу не открыли дважды
static Future<Database> get _instance async {
if (_db != null) return _db!;
if (_initCompleter != null) return _initCompleter!.future;
@@ -189,6 +199,7 @@ class AppDatabase {
return _db!;
}
// #***! на десктопе в support, на мобилках в системной папке баз
static Future<String> _databasesDir() async {
if (Platform.isLinux || Platform.isWindows || Platform.isMacOS) {
final dir = await getApplicationSupportDirectory();
@@ -198,6 +209,7 @@ class AppDatabase {
.getDatabasesPath();
}
// #***! разовый перенос со старого пути
static Future<void> _migrateLegacyDb(String target) async {
if (AppInstance.isNamed) return;
if (!(Platform.isLinux || Platform.isWindows || Platform.isMacOS)) return;
@@ -214,6 +226,7 @@ class AppDatabase {
}
}
// #***! версия 23, поднял версию дописывай миграцию ниже
static Future<Database> _open() async {
final dbPath = await _databasesDir();
await Directory(dbPath).create(recursive: true);
@@ -221,6 +234,7 @@ class AppDatabase {
await _migrateLegacyDb(target);
return openDatabase(
target,
// #***! каждый if oldVersion < N это шаг миграции, идут по порядку
version: 23,
onOpen: (db) => db.execute('PRAGMA foreign_keys = ON'),
onCreate: (db, _) => _createTables(db),
@@ -365,6 +379,7 @@ class AppDatabase {
);
}
// #***! создание таблиц с нуля для свежей установки
static Future<void> _createTables(Database db) async {
await db.execute('''
CREATE TABLE profile (
@@ -393,6 +408,7 @@ class AppDatabase {
await _createChatParticipantsIndex(db);
}
// #***! в sqlite нет ADD COLUMN IF NOT EXISTS, делаем сами
static Future<void> _addColumnIfMissing(
Database db,
String table,
@@ -405,6 +421,7 @@ class AppDatabase {
await db.execute('ALTER TABLE $table ADD COLUMN $column $definition');
}
// #***! индексы под частые выборки, без них список чатов тормозит
static Future<void> _createIndexes(Database db) async {
await db.execute(
'CREATE INDEX IF NOT EXISTS idx_messages_chat ON messages(account_id, chat_id, time DESC)',
@@ -424,6 +441,7 @@ class AppDatabase {
);
}
// #***! участники отдельной таблицей чтоб искать диалог по собеседнику
static List<int> _participantIdsFromRaw(Object? raw) {
if (raw is! String || raw.isEmpty) return const [];
try {
@@ -440,6 +458,7 @@ class AppDatabase {
}
}
// #***! дозаполняем участников для баз где таблицы ещё не было
static Future<void> _backfillChatParticipants(Database db) async {
final chats = await db.query(
'chats_cache',
@@ -462,6 +481,7 @@ class AppDatabase {
await batch.commit(noResult: true);
}
// #***! схемы таблиц строками, их же жуют onCreate и миграции
static const _contactsSchema = '''
CREATE TABLE contacts (
id INTEGER PRIMARY KEY,
@@ -570,6 +590,7 @@ class AppDatabase {
)
''';
// #***! дальше операции с данными
static Future<void> saveProfile(
ProfileData profile, {
bool isActive = true,
@@ -812,6 +833,7 @@ class AppDatabase {
// Chats cache
// #***! чаты пачкой в одной транзакции, по одному было бы на порядок медленнее
static Future<void> saveChats(List<Map<String, dynamic>> rows) async {
if (rows.isEmpty) return;
try {
@@ -857,6 +879,7 @@ class AppDatabase {
}
}
// #***! чиним имена отправителей после неполной синхры
static Future<void> repairLastMessageSenders(int accountId) async {
try {
final db = await _instance;
@@ -889,6 +912,7 @@ class AppDatabase {
);
}
// #***! в списке значит активный и не скрытый
static bool chatRowIsInList(Map<String, dynamic> row) {
final value = row['in_list'];
return value is! int || value != 0;
@@ -914,6 +938,7 @@ class AppDatabase {
);
}
// #***! общий счётчик непрочитанных для бейджа
static Future<int> sumUnread(
int accountId, {
int? excludeChatId,
@@ -939,6 +964,7 @@ class AppDatabase {
return (result.first['total'] as int?) ?? 0;
}
// #***! поиск диалога по собеседнику, ради этого и таблица участников
static Future<int?> findDialogChatByParticipant(
int accountId,
int contactId,
@@ -966,6 +992,7 @@ class AppDatabase {
);
}
// #***! экранируем LIKE иначе поиск по % вернёт всё
static String _escapeLike(String value) => value
.replaceAll('\\', '\\\\')
.replaceAll('%', '\\%')
@@ -1042,6 +1069,7 @@ class AppDatabase {
);
}
// #***! контакты пачкой как и чаты
static Future<void> saveContacts(List<Map<String, dynamic>> rows) async {
final db = await _instance;
final batch = db.batch();
@@ -1103,6 +1131,13 @@ class AppDatabase {
);
}
static Future<void> replaceMessage(
Map<String, dynamic> row, {
String? removeId,
}) async {
await MessagePersistence.replace(await _instance, row, removeId: removeId);
}
static Future<void> saveMessages(List<Map<String, dynamic>> rows) async {
final db = await _instance;
await db.transaction((txn) async {
@@ -1118,6 +1153,7 @@ class AppDatabase {
});
}
// #***! дальше выборки истории, с конца до сообщения между и вокруг
static Future<List<Map<String, dynamic>>> loadMessages(
int accountId,
int chatId, {
@@ -1178,6 +1214,7 @@ class AppDatabase {
);
}
// #***! вокруг нужно для перехода по ответу, грузим окно с обеих сторон
static Future<List<Map<String, dynamic>>> loadMessagesAround(
int accountId,
int chatId, {
@@ -1207,6 +1244,7 @@ class AppDatabase {
return [...newer.reversed, ...older];
}
// #***! удалённое не стираем а помечаем, с настройкой его ещё можно глянуть
static Future<void> markMessageDeleted(
int accountId,
int chatId,
@@ -1282,6 +1320,20 @@ class AppDatabase {
return rows.first;
}
static Future<void> deleteSyntheticMessages(
int accountId,
int chatId, {
required String prefix,
}) async {
if (prefix != 'sim_') throw ArgumentError.value(prefix, 'prefix');
final db = await _instance;
await db.delete(
'messages',
where: 'account_id = ? AND chat_id = ? AND substr(id, 1, 4) = ?',
whereArgs: [accountId, chatId, prefix],
);
}
static Future<void> deleteMessage(
int accountId,
int chatId,
@@ -1295,13 +1347,14 @@ class AppDatabase {
);
}
// #***! неотправленные, их подхватит outbox при коннекте
static Future<List<Map<String, dynamic>>> loadPendingMessages(
int accountId,
) async {
final db = await _instance;
return db.query(
'messages',
where: 'account_id = ? AND status = ?',
where: 'account_id = ? AND status = ? AND deleted = 0',
whereArgs: [accountId, 'pending'],
orderBy: 'time ASC',
);
+82 -12
View File
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:io';
import 'dart:ui' show Color;
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
@@ -7,10 +8,13 @@ import 'package:path_provider/path_provider.dart';
import '../utils/logger.dart';
import 'per_chat_json_store.dart';
// #***! chatId 0 это обои по умолчанию
const int kGlobalWallpaperChatId = 0;
enum ChatWallpaperKind { image, theme }
// #***! обои, своя картинка, встроенная тема или свой градиент
enum ChatWallpaperKind { image, theme, gradient }
// #***! правки картинки, затемнение блюр параллакс сдвиг
@immutable
class WallpaperImageSettings {
final double dim;
@@ -26,11 +30,15 @@ class WallpaperImageSettings {
});
}
// #***! один объект на все виды, у темы/градиента настройки картинки нулевые
@immutable
class ChatWallpaper {
final ChatWallpaperKind kind;
final String? imagePath;
final String? themeId;
final List<Color>? gradientColors;
final bool gradientAnimated;
final double gradientRotation;
final double dim;
final bool blur;
final bool motion;
@@ -44,28 +52,59 @@ class ChatWallpaper {
this.offsetX = 0,
}) : kind = ChatWallpaperKind.image,
imagePath = path,
themeId = null;
themeId = null,
gradientColors = null,
gradientAnimated = true,
gradientRotation = 0;
const ChatWallpaper.theme(String id)
: kind = ChatWallpaperKind.theme,
imagePath = null,
themeId = id,
gradientColors = null,
gradientAnimated = true,
gradientRotation = 0,
dim = 0,
blur = false,
motion = false,
offsetX = 0;
bool get isImage => kind == ChatWallpaperKind.image;
const ChatWallpaper.gradient(
List<Color> colors, {
this.gradientAnimated = false,
this.gradientRotation = 0,
}) : kind = ChatWallpaperKind.gradient,
imagePath = null,
themeId = null,
gradientColors = colors,
dim = 0,
blur = false,
motion = false,
offsetX = 0;
Map<String, dynamic> _toJson() => isImage
? {
'path': imagePath,
'dim': dim,
'blur': blur,
'motion': motion,
'offsetX': offsetX,
}
: {'theme': themeId};
bool get isImage => kind == ChatWallpaperKind.image;
bool get isGradient => kind == ChatWallpaperKind.gradient;
// #***! в джейсон или путь с настройками, или id темы, или свои цвета
Map<String, dynamic> _toJson() {
if (isImage) {
return {
'path': imagePath,
'dim': dim,
'blur': blur,
'motion': motion,
'offsetX': offsetX,
};
}
if (isGradient) {
return {
'colors': gradientColors!.map((c) => c.toARGB32()).toList(),
'animated': gradientAnimated,
'rotation': gradientRotation,
};
}
return {'theme': themeId};
}
static ChatWallpaper? _fromJson(Object? raw) {
if (raw is! Map) return null;
@@ -79,13 +118,25 @@ class ChatWallpaper {
offsetX: (raw['offsetX'] as num?)?.toDouble() ?? 0,
);
}
final colors = raw['colors'];
if (colors is List && colors.isNotEmpty) {
return ChatWallpaper.gradient(
colors.whereType<num>().map((v) => Color(v.toInt())).toList(),
gradientAnimated: raw['animated'] == true,
gradientRotation: (raw['rotation'] as num?)?.toDouble() ?? 0,
);
}
final theme = raw['theme'];
if (theme is String && theme.isNotEmpty) return ChatWallpaper.theme(theme);
return null;
}
}
// #***! обои по чатам поверх общего хранилища
class ChatWallpaperStore extends PerChatJsonStore<ChatWallpaper> {
@visibleForTesting
ChatWallpaperStore.forTesting() : this._();
ChatWallpaperStore._()
: super(
prefsKey: 'chat_wallpapers',
@@ -99,6 +150,7 @@ class ChatWallpaperStore extends PerChatJsonStore<ChatWallpaper> {
ChatWallpaper? get(int accountId, int chatId) => read(accountId, chatId);
// #***! картинку копируем к себе, исходник из галереи может исчезнуть
Future<ChatWallpaper?> setImage(
int accountId,
int chatId,
@@ -109,6 +161,7 @@ class ChatWallpaperStore extends PerChatJsonStore<ChatWallpaper> {
final dir = await getApplicationDocumentsDirectory();
final wpDir = Directory('${dir.path}/$_dirName');
if (!await wpDir.exists()) await wpDir.create(recursive: true);
// #***! время в имени файла, иначе флаттер отдаст старую из кэша
final stamp = DateTime.now().millisecondsSinceEpoch;
final file = File('${wpDir.path}/${accountId}_${chatId}_$stamp.img');
await file.writeAsBytes(bytes, flush: true);
@@ -133,9 +186,26 @@ class ChatWallpaperStore extends PerChatJsonStore<ChatWallpaper> {
return wallpaper;
}
Future<ChatWallpaper> setGradient(
int accountId,
int chatId,
List<Color> colors, {
bool animated = false,
double rotation = 0,
}) async {
final wallpaper = ChatWallpaper.gradient(
colors,
gradientAnimated: animated,
gradientRotation: rotation,
);
await write(accountId, chatId, wallpaper);
return wallpaper;
}
Future<void> clear(int accountId, int chatId) =>
write(accountId, chatId, null);
// #***! старый файл удаляем иначе обои копятся на диске
@override
void onBeforeWrite(String key, ChatWallpaper? previous, ChatWallpaper? next) {
if (previous != null &&
+22
View File
@@ -0,0 +1,22 @@
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
class MessagePersistence {
static Future<void> replace(
Database db,
Map<String, dynamic> row, {
String? removeId,
}) => db.transaction((txn) async {
await txn.insert(
'messages',
row,
conflictAlgorithm: ConflictAlgorithm.replace,
);
if (removeId != null && removeId != row['id']) {
await txn.delete(
'messages',
where: 'account_id = ? AND chat_id = ? AND id = ?',
whereArgs: [row['account_id'], row['chat_id'], removeId],
);
}
});
}
@@ -0,0 +1,24 @@
import 'package:shared_preferences/shared_preferences.dart';
// #***! когда запланировано удаление профиля
abstract final class ProfileDeletionStore {
static String _key(int accountId) => 'profile_delete_at_$accountId';
static Future<DateTime?> scheduledAt(int accountId) async {
final prefs = await SharedPreferences.getInstance();
final millis = prefs.getInt(_key(accountId)) ?? 0;
if (millis <= 0) return null;
return DateTime.fromMillisecondsSinceEpoch(millis);
}
static Future<void> save(int accountId, int millis) async {
final prefs = await SharedPreferences.getInstance();
if (millis > 0) {
await prefs.setInt(_key(accountId), millis);
} else {
await prefs.remove(_key(accountId));
}
}
static Future<void> clear(int accountId) => save(accountId, 0);
}
+2
View File
@@ -4,6 +4,7 @@ import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import '../config/device_presets.dart';
import '../config/build_profile.dart';
import '../../models/spoof_profile.dart';
import 'token_storage.dart';
import '../utils/ids.dart';
@@ -121,6 +122,7 @@ class SpoofingService {
static Future<Map<String, dynamic>?> getSpoofedSessionData({
String? scope,
}) async {
if (!BuildProfile.spoofUi) return null;
final prefs = await SharedPreferences.getInstance();
final profile = await _read(prefs, scope ?? await activeScope());
if (profile == null || !profile.enabled) return null;
+2
View File
@@ -2,6 +2,7 @@ import 'package:kusoft/kusoft.dart' show setTrustMincifryCa;
import 'package:shared_preferences/shared_preferences.dart';
import '../config/config.dart';
import '../config/build_profile.dart';
abstract class TlsConfig {
static const String prefKey = 'dev_tls_insecure';
@@ -16,6 +17,7 @@ abstract class TlsConfig {
}
static Future<bool> isInsecureAllowed() async {
if (!BuildProfile.insecureTransport) return false;
final prefs = await SharedPreferences.getInstance();
return prefs.getBool(prefKey) ?? false;
}
+12
View File
@@ -0,0 +1,12 @@
import 'package:flutter/foundation.dart';
// #***! на переднем плане или нет, в фоне экономим
/// Признак «приложение на переднем плане» для подсистем, которые обязаны
/// экономить в фоне: реконнект, пинг ядра, запись отладочного лога.
abstract class AppForeground {
static final ValueNotifier<bool> notifier = ValueNotifier(true);
static bool get value => notifier.value;
static void update({required bool foreground}) => notifier.value = foreground;
}
+29 -4
View File
@@ -5,9 +5,11 @@ import 'dart:io';
import 'package:path_provider/path_provider.dart';
import '../protocol/opcode_map.dart';
import 'app_foreground.dart';
import 'format.dart';
import 'log_redact.dart';
// #***! файл в архиве экспорта
class DebugExportFile {
final String name;
final String content;
@@ -15,6 +17,7 @@ class DebugExportFile {
DebugExportFile(this.name, this.content);
}
// #***! запрос с ответом, сматчены по seq
class _LogEntry {
final int opcode;
final int seq;
@@ -32,6 +35,7 @@ class _LogEntry {
required this.request,
});
// #***! в файл сессии джейсоном
Map<String, dynamic> toJson() => {
'opcode': opcode,
'seq': seq,
@@ -61,6 +65,7 @@ class _LogEntry {
}
}
// #***! одна сессия, запросы плюс строки лога
class _SessionData {
final DateTime startedAt;
final List<_LogEntry> entries;
@@ -103,15 +108,20 @@ class _SessionData {
}
}
// #***! отладочный лог, пишется на диск и выгружается архивом из дев меню
class DebugSessionLog {
DebugSessionLog._();
static final DebugSessionLog instance = DebugSessionLog._();
// #***! старше суток и лишние сверх 30 удаляем
static const Duration _retention = Duration(hours: 24);
static const int _maxStoredSessions = 30;
// #***! потолки на сессию чтоб файл не рос бесконечно
static const int _maxEntriesPerSession = 2000;
static const int _maxLogLinesPerSession = 5000;
// #***! в фоне пишем раз в минуту а не в три секунды, батарея
static const Duration _flushDebounce = Duration(seconds: 3);
static const Duration _backgroundFlushDebounce = Duration(seconds: 60);
static final RegExp _ansiEscape = RegExp(r'\x1B\[[0-9;]*m');
@@ -126,6 +136,7 @@ class DebugSessionLog {
bool _dirty = false;
Timer? _flushTimer;
// #***! каталог сессий и ротация
Future<void> init() async {
if (_initialized) return;
_initialized = true;
@@ -146,6 +157,7 @@ class DebugSessionLog {
}
}
// #***! чистим ANSI цвета иначе в файле мусор
void recordLogLine(String line) {
final clean = line.replaceAll(_ansiEscape, '');
_logLines.add(clean);
@@ -156,6 +168,7 @@ class DebugSessionLog {
_scheduleFlush();
}
// #***! исходящий запрос, payload чистим от секретов
void recordRequest(int opcode, int seq, dynamic payload) {
_entries.add(
_LogEntry(
@@ -172,6 +185,7 @@ class DebugSessionLog {
_scheduleFlush();
}
// #***! ответ подшиваем к запросу по seq
void recordResponse(int seq, int cmd, dynamic payload) {
final entry = _findPending(seq);
if (entry == null) return;
@@ -181,6 +195,7 @@ class DebugSessionLog {
_scheduleFlush();
}
// #***! ошибку тоже подшиваем
void recordError(int seq, Object error) {
final entry = _findPending(seq);
if (entry == null) return;
@@ -189,6 +204,7 @@ class DebugSessionLog {
_scheduleFlush();
}
// #***! ищем с конца, seq переиспользуются нужен последний неотвеченный
_LogEntry? _findPending(int seq) {
for (var i = _entries.length - 1; i >= 0; i--) {
final entry = _entries[i];
@@ -201,15 +217,20 @@ class DebugSessionLog {
return null;
}
// #***! пишем с задержкой иначе файл переписывается на каждый пакет
void _scheduleFlush() {
_dirty = true;
if (_currentFile == null) return;
_flushTimer ??= Timer(_flushDebounce, () {
_flushTimer = null;
_flush();
});
_flushTimer ??= Timer(
AppForeground.value ? _flushDebounce : _backgroundFlushDebounce,
() {
_flushTimer = null;
_flush();
},
);
}
// #***! снимок сессии целиком одним джейсоном
Future<void> _flush() async {
final file = _currentFile;
if (file == null || !_dirty) return;
@@ -232,6 +253,7 @@ class DebugSessionLog {
await _flush();
}
// #***! ротация, удаляем протухшие и лишние
Future<void> _rotate() async {
final files = await _sessionFiles();
final cutoff = DateTime.now().subtract(_retention).millisecondsSinceEpoch;
@@ -272,6 +294,7 @@ class DebugSessionLog {
return int.tryParse(digits) ?? 0;
}
// #***! сборка архива для выгрузки
Future<List<DebugExportFile>?> buildExportFiles({String? endpoint}) async {
final cutoff = DateTime.now().subtract(_retention);
final sessions = <_SessionData>[];
@@ -329,6 +352,7 @@ class DebugSessionLog {
return files;
}
// #***! сессия в читаемый текст
String _buildSessionText(int index, _SessionData session) {
final buffer = StringBuffer();
buffer.writeln('==================================================');
@@ -394,6 +418,7 @@ class DebugSessionLog {
}
}
// #***! числовой cmd в имя
String _cmdName(int? cmd) {
switch (cmd) {
case 0:
+27
View File
@@ -0,0 +1,27 @@
import 'dart:io';
// #***! язык по дефолту если системный не определили
const String defaultLanguageCode = 'ru';
final RegExp _languageSubtag = RegExp(r'^[a-z]{2,3}$');
// #***! из ru_RU.UTF-8 достаём только ru
String languageCodeOf(String localeName) {
final subtag = localeName
.split(RegExp(r'[.@]'))
.first
.split(RegExp(r'[-_]'))
.first
.toLowerCase();
return _languageSubtag.hasMatch(subtag) ? subtag : defaultLanguageCode;
}
// #***! на линуксе локаль не читаем, она там часто мусорная
String deviceLanguageCode() {
if (Platform.isLinux) return defaultLanguageCode;
try {
return languageCodeOf(Platform.localeName);
} catch (_) {
return defaultLanguageCode;
}
}
+36 -6
View File
@@ -3,6 +3,7 @@ import 'package:open_filex/open_filex.dart';
import 'download_history.dart';
import 'media_cache.dart';
// #***! итог скачивания, путь или ошибка
class FileDownloadResult {
final bool ok;
final String? path;
@@ -11,6 +12,7 @@ class FileDownloadResult {
const FileDownloadResult({required this.ok, this.path, this.error});
}
// #***! открыть файл, скачав если надо
/// Открывает файл из кэша, скачивая его при отсутствии.
///
/// [cacheName] — стабильное имя в кэше (например, `<fileId>_имя.ext`).
@@ -26,6 +28,39 @@ Future<FileDownloadResult> openCachedFile(
void Function()? onReady,
DownloadMetadata? download,
}) async {
final result = await ensureCachedFile(
cacheName,
resolveUrl,
onProgress: onProgress,
onReady: onReady,
download: download,
);
if (!result.ok || result.path == null) return result;
try {
final opened = await OpenFilex.open(result.path!);
return FileDownloadResult(
ok: opened.type == ResultType.done,
path: result.path,
error: opened.type == ResultType.done ? null : opened.message,
);
} catch (e) {
return FileDownloadResult(
ok: false,
path: result.path,
error: e.toString(),
);
}
}
// #***! скачивание в кэш, onReady зовётся как только файл на диске
Future<FileDownloadResult> ensureCachedFile(
String cacheName,
Future<String?> Function() resolveUrl, {
void Function(double progress)? onProgress,
void Function()? onReady,
DownloadMetadata? download,
}) async {
// #***! ready зовётся из разных веток, защита от повтора
var readyFired = false;
void ready() {
if (readyFired) return;
@@ -59,12 +94,7 @@ Future<FileDownloadResult> openCachedFile(
await DownloadHistory.record(download, file);
} catch (_) {}
}
final opened = await OpenFilex.open(file.path);
return FileDownloadResult(
ok: opened.type == ResultType.done,
path: file.path,
error: opened.type == ResultType.done ? null : opened.message,
);
return FileDownloadResult(ok: true, path: file.path);
} catch (e) {
ready();
return FileDownloadResult(ok: false, error: e.toString());
+183
View File
@@ -0,0 +1,183 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:image/image.dart' as img;
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
enum ImageByteFormat { jpeg, png, gif, webp, bmp, heic, unknown }
const Map<ImageByteFormat, String> _extensionByFormat = {
ImageByteFormat.jpeg: '.jpg',
ImageByteFormat.png: '.png',
ImageByteFormat.gif: '.gif',
ImageByteFormat.webp: '.webp',
ImageByteFormat.bmp: '.bmp',
ImageByteFormat.heic: '.heic',
};
const Set<String> _heicBrands = {
'heic',
'heix',
'heim',
'heis',
'hevc',
'hevx',
'hevm',
'hevs',
'mif1',
'msf1',
};
const int _webpAnimationFlag = 0x02;
const int _transcodeJpegQuality = 95;
const int _headerBytes = 32;
bool _startsWith(Uint8List bytes, int offset, List<int> signature) {
if (bytes.length < offset + signature.length) return false;
for (var i = 0; i < signature.length; i++) {
if (bytes[offset + i] != signature[i]) return false;
}
return true;
}
String _fourcc(Uint8List bytes, int offset, [int length = 4]) {
if (bytes.length < offset + length) return '';
return String.fromCharCodes(bytes, offset, offset + length);
}
ImageByteFormat sniffImageFormat(Uint8List bytes) {
if (_startsWith(bytes, 0, const [0xFF, 0xD8, 0xFF])) {
return ImageByteFormat.jpeg;
}
if (_startsWith(bytes, 0, const [
0x89,
0x50,
0x4E,
0x47,
0x0D,
0x0A,
0x1A,
0x0A,
])) {
return ImageByteFormat.png;
}
if (_fourcc(bytes, 0) == 'GIF8') return ImageByteFormat.gif;
if (_fourcc(bytes, 0) == 'RIFF' && _fourcc(bytes, 8) == 'WEBP') {
return ImageByteFormat.webp;
}
if (_fourcc(bytes, 0, 2) == 'BM') return ImageByteFormat.bmp;
if (_fourcc(bytes, 4) == 'ftyp' && _heicBrands.contains(_fourcc(bytes, 8))) {
return ImageByteFormat.heic;
}
return ImageByteFormat.unknown;
}
bool isAnimatedWebp(Uint8List bytes) {
if (sniffImageFormat(bytes) != ImageByteFormat.webp) return false;
if (_fourcc(bytes, 12) != 'VP8X' || bytes.length < 21) return false;
return (bytes[20] & _webpAnimationFlag) != 0;
}
String? extensionForImageFormat(ImageByteFormat format) =>
_extensionByFormat[format];
String withImageExtension(String name, String extension) {
if (extension.isEmpty) return name;
return '${p.basenameWithoutExtension(name)}$extension';
}
class SaveReadyImage {
final File file;
final String extension;
final bool temporary;
const SaveReadyImage({
required this.file,
required this.extension,
required this.temporary,
});
Future<void> discard() async {
if (!temporary) return;
try {
await file.delete();
await file.parent.delete();
} catch (_) {}
}
}
Future<SaveReadyImage?> prepareImageForSave(File source) async {
final head = await _readHeader(source);
if (head == null) return null;
final format = sniffImageFormat(head);
final asIs = SaveReadyImage(
file: source,
extension:
extensionForImageFormat(format) ??
p.extension(source.path).toLowerCase(),
temporary: false,
);
if (format != ImageByteFormat.webp || isAnimatedWebp(head)) return asIs;
Uint8List bytes;
try {
bytes = await source.readAsBytes();
} catch (_) {
return asIs;
}
final converted = await compute(_transcodeWebp, bytes);
if (converted == null) return asIs;
final (data, extension) = converted;
try {
final directory = await (await getTemporaryDirectory()).createTemp(
'qlyra_image_save_',
);
final target = File(
p.join(
directory.path,
'${p.basenameWithoutExtension(source.path)}_save$extension',
),
);
await target.writeAsBytes(data, flush: true);
return SaveReadyImage(file: target, extension: extension, temporary: true);
} catch (_) {
return asIs;
}
}
Future<Uint8List?> _readHeader(File source) async {
RandomAccessFile? handle;
try {
handle = await source.open();
return await handle.read(_headerBytes);
} catch (_) {
return null;
} finally {
await handle?.close();
}
}
(Uint8List, String)? _transcodeWebp(Uint8List bytes) {
final decoded = img.decodeWebP(bytes);
if (decoded == null) return null;
if (!_isOpaque(decoded)) return (img.encodePng(decoded), '.png');
return (img.encodeJpg(decoded, quality: _transcodeJpegQuality), '.jpg');
}
bool _isOpaque(img.Image image) {
final data = image.data;
if (data is! img.ImageDataUint8 || data.numChannels != 4) {
return !image.hasAlpha;
}
final raw = data.toUint8List();
for (var i = 3; i < raw.length; i += 4) {
if (raw[i] != 255) return false;
}
return true;
}
+49 -13
View File
@@ -1,14 +1,30 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:image/image.dart' as img;
// #***! аватарка до 1024 px и примерно 900 КБ
const int _avatarMaxDimension = 1024;
const int _avatarTargetBytes = 900 * 1024;
// #***! обои ужимаем под экран, иначе полный кадр декодится при каждом открытии чата.
// 1920 покрывает физическое разрешение большинства экранов по длинной стороне
const int _wallpaperMaxDimension = 1920;
const int _wallpaperQuality = 92;
/// Maximum accepted size for a user-picked avatar before compression.
const int kMaxAvatarBytes = 8 * 1024 * 1024;
Future<Uint8List?> compressAvatar(Uint8List input) =>
compute(_encodeAvatar, input);
/// Maximum accepted size for a user-picked chat wallpaper before compression.
const int kMaxWallpaperBytes = 16 * 1024 * 1024;
// #***! сжимаем в изоляте иначе кадры пропадают, файл читаем тоже там:
// главный изолят не должен держать полный кадр
Future<Uint8List?> compressAvatarFile(String path) =>
compute(_encodeAvatarFile, path);
Future<Uint8List?> compressWallpaperFile(String path) =>
compute(_encodeWallpaperFile, path);
Future<Uint8List?> encodeRgbaToJpeg(Uint8List rgba, int width, int height) =>
compute(_encodeRgba, (rgba, width, height));
@@ -26,20 +42,37 @@ Uint8List? _encodeRgba((Uint8List, int, int) args) {
return img.encodeJpg(image, quality: 90);
}
Uint8List? _encodeAvatar(Uint8List input) {
img.Image? _decodeFitted(Uint8List input, int maxDimension) {
final decoded = img.decodeImage(input);
if (decoded == null) return null;
final oriented = img.bakeOrientation(decoded);
final image =
oriented.width > _avatarMaxDimension ||
oriented.height > _avatarMaxDimension
? img.copyResize(
oriented,
width: oriented.width >= oriented.height ? _avatarMaxDimension : null,
height: oriented.height > oriented.width ? _avatarMaxDimension : null,
interpolation: img.Interpolation.average,
)
: oriented;
if (oriented.width <= maxDimension && oriented.height <= maxDimension) {
return oriented;
}
return img.copyResize(
oriented,
width: oriented.width >= oriented.height ? maxDimension : null,
height: oriented.height > oriented.width ? maxDimension : null,
interpolation: img.Interpolation.average,
);
}
Uint8List? _encodeAvatarFile(String path) =>
_encodeAvatar(File(path).readAsBytesSync());
Uint8List? _encodeWallpaperFile(String path) {
final image = _decodeFitted(
File(path).readAsBytesSync(),
_wallpaperMaxDimension,
);
if (image == null) return null;
return img.encodeJpg(image, quality: _wallpaperQuality);
}
// #***! качество снижаем шагами пока не влезем
Uint8List? _encodeAvatar(Uint8List input) {
final image = _decodeFitted(input, _avatarMaxDimension);
if (image == null) return null;
var quality = 88;
var out = img.encodeJpg(image, quality: quality);
while (out.lengthInBytes > _avatarTargetBytes && quality > 35) {
@@ -48,3 +81,6 @@ Uint8List? _encodeAvatar(Uint8List input) {
}
return out;
}
Future<Uint8List?> compressAvatar(Uint8List input) =>
compute(_encodeAvatar, input);
+86
View File
@@ -0,0 +1,86 @@
import 'dart:convert';
import 'dart:io';
import '../config/build_profile.dart';
class IpLookupDetails {
final String city;
final String country;
final String isp;
final String network;
final bool mobile;
final bool proxy;
final String timezone;
const IpLookupDetails({
required this.city,
required this.country,
required this.isp,
required this.network,
required this.mobile,
required this.proxy,
required this.timezone,
});
factory IpLookupDetails.fromIpWhoIs(Map<String, dynamic> data) {
if (data['success'] != true) {
throw FormatException(data['message']?.toString() ?? 'IP lookup failed');
}
final connection = data['connection'] is Map
? (data['connection'] as Map).cast<String, dynamic>()
: const <String, dynamic>{};
final security = data['security'] is Map
? (data['security'] as Map).cast<String, dynamic>()
: const <String, dynamic>{};
final timezoneData = data['timezone'] is Map
? (data['timezone'] as Map).cast<String, dynamic>()
: const <String, dynamic>{};
final asn = connection['asn'];
final organization = connection['org']?.toString() ?? '';
final network = [
if (asn != null) 'AS$asn',
if (organization.isNotEmpty) organization,
].join(' ');
return IpLookupDetails(
city: data['city']?.toString() ?? '',
country: data['country']?.toString() ?? '',
isp: connection['isp']?.toString() ?? organization,
network: network,
mobile: security['mobile'] == true,
proxy: security['proxy'] == true,
timezone: timezoneData['id']?.toString() ?? '',
);
}
}
abstract class IpLookupService {
static const String providerName = 'ipwho.is';
static const Duration _timeout = Duration(seconds: 8);
static Future<IpLookupDetails> lookup(String ip) async {
if (!BuildProfile.ipGeoLookup) {
throw StateError('IP lookup is unavailable in this build');
}
final uri = Uri.https(providerName, '/$ip');
final client = HttpClient()..connectionTimeout = _timeout;
try {
final request = await client.getUrl(uri);
request.headers.set(HttpHeaders.userAgentHeader, 'QlyraIpLookup');
final response = await request.close().timeout(_timeout);
if (response.statusCode != HttpStatus.ok) {
await response.drain<void>();
throw HttpException('HTTP ${response.statusCode}', uri: uri);
}
final body = await response
.transform(const Utf8Decoder())
.join()
.timeout(_timeout);
final decoded = jsonDecode(body);
if (decoded is! Map) {
throw const FormatException('Invalid IP lookup response');
}
return IpLookupDetails.fromIpWhoIs(decoded.cast<String, dynamic>());
} finally {
client.close(force: true);
}
}
}

Some files were not shown because too many files have changed in this diff Show More